From 397a283d5f0b610602a5a25bef55d45122fddb74 Mon Sep 17 00:00:00 2001 From: Sean Emmer Date: Tue, 2 Jun 2015 14:38:33 -0700 Subject: [PATCH] initial commit --- .jshintrc | 41 + LICENSE | 21 + README.md | 0 index.js | 128 + node_modules/async/.jshintrc | 25 + node_modules/async/.travis.yml | 6 + node_modules/async/CHANGELOG.md | 51 + node_modules/async/LICENSE | 19 + node_modules/async/README.md | 1803 +++ node_modules/async/bower.json | 40 + node_modules/async/component.json | 17 + node_modules/async/coverage/base.css | 182 + node_modules/async/coverage/index.html | 73 + .../async/coverage/lcov-report/base.css | 182 + .../async/coverage/lcov-report/index.html | 73 + .../coverage/lcov-report/lib/async.js.html | 3900 +++++ .../async/coverage/lcov-report/lib/index.html | 73 + .../async/coverage/lcov-report/prettify.css | 1 + .../async/coverage/lcov-report/prettify.js | 1 + .../lcov-report/sort-arrow-sprite.png | Bin 0 -> 209 bytes .../async/coverage/lcov-report/sorter.js | 156 + node_modules/async/coverage/lcov.info | 1452 ++ node_modules/async/coverage/lib/async.js.html | 3597 +++++ node_modules/async/coverage/lib/index.html | 73 + node_modules/async/coverage/prettify.css | 1 + node_modules/async/coverage/prettify.js | 1 + .../async/coverage/sort-arrow-sprite.png | Bin 0 -> 209 bytes node_modules/async/coverage/sorter.js | 156 + node_modules/async/lib/async.js | 1187 ++ node_modules/async/nyc_output/5074.json | 1 + node_modules/async/package.json | 96 + .../async/support/sync-package-managers.js | 53 + node_modules/chalk/index.js | 100 + node_modules/chalk/license | 21 + node_modules/chalk/node_modules/.bin/has-ansi | 1 + .../chalk/node_modules/.bin/strip-ansi | 1 + .../chalk/node_modules/.bin/supports-color | 1 + .../chalk/node_modules/ansi-styles/index.js | 56 + .../chalk/node_modules/ansi-styles/license | 21 + .../node_modules/ansi-styles/package.json | 71 + .../chalk/node_modules/ansi-styles/readme.md | 86 + .../escape-string-regexp/index.js | 11 + .../node_modules/escape-string-regexp/license | 21 + .../escape-string-regexp/package.json | 61 + .../escape-string-regexp/readme.md | 27 + .../chalk/node_modules/has-ansi/cli.js | 45 + .../chalk/node_modules/has-ansi/index.js | 4 + .../chalk/node_modules/has-ansi/license | 21 + .../has-ansi/node_modules/ansi-regex/index.js | 4 + .../has-ansi/node_modules/ansi-regex/license | 21 + .../node_modules/ansi-regex/package.json | 77 + .../node_modules/ansi-regex/readme.md | 33 + .../has-ansi/node_modules/get-stdin/index.js | 49 + .../node_modules/get-stdin/package.json | 48 + .../has-ansi/node_modules/get-stdin/readme.md | 44 + .../chalk/node_modules/has-ansi/package.json | 83 + .../chalk/node_modules/has-ansi/readme.md | 45 + .../chalk/node_modules/strip-ansi/cli.js | 47 + .../chalk/node_modules/strip-ansi/index.js | 6 + .../node_modules/ansi-regex/index.js | 4 + .../node_modules/ansi-regex/license | 21 + .../node_modules/ansi-regex/package.json | 77 + .../node_modules/ansi-regex/readme.md | 33 + .../node_modules/strip-ansi/package.json | 69 + .../chalk/node_modules/strip-ansi/readme.md | 43 + .../chalk/node_modules/supports-color/cli.js | 29 + .../node_modules/supports-color/index.js | 43 + .../chalk/node_modules/supports-color/license | 21 + .../node_modules/supports-color/package.json | 76 + .../node_modules/supports-color/readme.md | 46 + node_modules/chalk/package.json | 74 + node_modules/chalk/readme.md | 197 + node_modules/lodash/LICENSE.txt | 22 + node_modules/lodash/README.md | 120 + node_modules/lodash/array.js | 44 + node_modules/lodash/array/chunk.js | 47 + node_modules/lodash/array/compact.js | 30 + node_modules/lodash/array/difference.js | 28 + node_modules/lodash/array/drop.js | 39 + node_modules/lodash/array/dropRight.js | 40 + node_modules/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 + node_modules/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 | 54 + 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 + node_modules/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 + node_modules/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 | 34 + 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 | 15 + node_modules/lodash/chain/chain.js | 35 + node_modules/lodash/chain/commit.js | 1 + node_modules/lodash/chain/lodash.js | 123 + 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 + node_modules/lodash/chain/wrapperCommit.js | 32 + node_modules/lodash/chain/wrapperPlant.js | 45 + node_modules/lodash/chain/wrapperReverse.js | 38 + node_modules/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 + node_modules/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 + node_modules/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 + node_modules/lodash/collection/findLast.js | 25 + node_modules/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 + node_modules/lodash/collection/includes.js | 60 + 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 + node_modules/lodash/collection/partition.js | 66 + node_modules/lodash/collection/pluck.js | 31 + node_modules/lodash/collection/reduce.js | 43 + node_modules/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 + node_modules/lodash/collection/sortByAll.js | 52 + node_modules/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 | 27 + 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 + node_modules/lodash/function/curryRight.js | 48 + node_modules/lodash/function/debounce.js | 187 + 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/negate.js | 32 + node_modules/lodash/function/once.js | 24 + node_modules/lodash/function/partial.js | 43 + node_modules/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 | 72 + node_modules/lodash/function/wrap.js | 33 + node_modules/lodash/index.js | 12235 ++++++++++++++++ node_modules/lodash/internal/LazyWrapper.js | 27 + node_modules/lodash/internal/LodashWrapper.js | 21 + node_modules/lodash/internal/MapCache.js | 24 + node_modules/lodash/internal/SetCache.js | 29 + node_modules/lodash/internal/arrayCopy.js | 20 + node_modules/lodash/internal/arrayEach.js | 22 + .../lodash/internal/arrayEachRight.js | 21 + node_modules/lodash/internal/arrayEvery.js | 23 + node_modules/lodash/internal/arrayExtremum.js | 30 + node_modules/lodash/internal/arrayFilter.js | 25 + node_modules/lodash/internal/arrayMap.js | 21 + node_modules/lodash/internal/arrayReduce.js | 26 + .../lodash/internal/arrayReduceRight.js | 24 + node_modules/lodash/internal/arraySome.js | 23 + node_modules/lodash/internal/arraySum.js | 18 + .../lodash/internal/assignDefaults.js | 13 + .../lodash/internal/assignOwnDefaults.js | 26 + node_modules/lodash/internal/assignWith.js | 32 + node_modules/lodash/internal/baseAssign.js | 19 + node_modules/lodash/internal/baseAt.js | 32 + node_modules/lodash/internal/baseCallback.js | 35 + node_modules/lodash/internal/baseClone.js | 128 + .../lodash/internal/baseCompareAscending.js | 34 + node_modules/lodash/internal/baseCopy.js | 23 + node_modules/lodash/internal/baseCreate.js | 23 + node_modules/lodash/internal/baseDelay.js | 21 + .../lodash/internal/baseDifference.js | 52 + node_modules/lodash/internal/baseEach.js | 15 + node_modules/lodash/internal/baseEachRight.js | 15 + node_modules/lodash/internal/baseEvery.js | 22 + node_modules/lodash/internal/baseExtremum.js | 29 + node_modules/lodash/internal/baseFill.js | 31 + node_modules/lodash/internal/baseFilter.js | 22 + node_modules/lodash/internal/baseFind.js | 25 + node_modules/lodash/internal/baseFindIndex.js | 23 + node_modules/lodash/internal/baseFlatten.js | 43 + node_modules/lodash/internal/baseFor.js | 17 + node_modules/lodash/internal/baseForIn.js | 17 + node_modules/lodash/internal/baseForOwn.js | 17 + .../lodash/internal/baseForOwnRight.js | 17 + node_modules/lodash/internal/baseForRight.js | 15 + node_modules/lodash/internal/baseFunctions.js | 27 + node_modules/lodash/internal/baseGet.js | 29 + node_modules/lodash/internal/baseIndexOf.js | 27 + node_modules/lodash/internal/baseIsEqual.js | 28 + .../lodash/internal/baseIsEqualDeep.js | 102 + .../lodash/internal/baseIsFunction.js | 15 + node_modules/lodash/internal/baseIsMatch.js | 52 + node_modules/lodash/internal/baseLodash.js | 10 + node_modules/lodash/internal/baseMap.js | 23 + node_modules/lodash/internal/baseMatches.js | 30 + .../lodash/internal/baseMatchesProperty.js | 45 + node_modules/lodash/internal/baseMerge.js | 56 + node_modules/lodash/internal/baseMergeDeep.js | 67 + node_modules/lodash/internal/baseProperty.js | 14 + .../lodash/internal/basePropertyDeep.js | 19 + node_modules/lodash/internal/basePullAt.js | 30 + node_modules/lodash/internal/baseRandom.js | 20 + node_modules/lodash/internal/baseReduce.js | 24 + node_modules/lodash/internal/baseSetData.js | 17 + node_modules/lodash/internal/baseSlice.js | 32 + node_modules/lodash/internal/baseSome.js | 23 + node_modules/lodash/internal/baseSortBy.js | 21 + .../lodash/internal/baseSortByOrder.js | 31 + node_modules/lodash/internal/baseSum.js | 20 + node_modules/lodash/internal/baseToString.js | 16 + node_modules/lodash/internal/baseUniq.js | 57 + node_modules/lodash/internal/baseValues.js | 22 + node_modules/lodash/internal/baseWhile.js | 24 + .../lodash/internal/baseWrapperValue.js | 37 + node_modules/lodash/internal/binaryIndex.js | 39 + node_modules/lodash/internal/binaryIndexBy.js | 59 + node_modules/lodash/internal/bindCallback.js | 39 + node_modules/lodash/internal/bufferClone.js | 55 + node_modules/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 | 43 + node_modules/lodash/internal/composeArgs.js | 34 + .../lodash/internal/composeArgsRight.js | 36 + .../lodash/internal/createAggregator.js | 40 + .../lodash/internal/createAssigner.js | 44 + .../lodash/internal/createBaseEach.js | 31 + node_modules/lodash/internal/createBaseFor.js | 27 + .../lodash/internal/createBindWrapper.js | 22 + node_modules/lodash/internal/createCache.js | 22 + .../lodash/internal/createCompounder.js | 26 + .../lodash/internal/createCtorWrapper.js | 35 + node_modules/lodash/internal/createCurry.js | 23 + .../lodash/internal/createExtremum.js | 32 + node_modules/lodash/internal/createFind.js | 25 + .../lodash/internal/createFindIndex.js | 21 + node_modules/lodash/internal/createFindKey.js | 18 + node_modules/lodash/internal/createFlow.js | 69 + node_modules/lodash/internal/createForEach.js | 20 + node_modules/lodash/internal/createForIn.js | 20 + node_modules/lodash/internal/createForOwn.js | 19 + .../lodash/internal/createHybridWrapper.js | 111 + .../lodash/internal/createObjectMapper.js | 26 + node_modules/lodash/internal/createPadDir.js | 18 + node_modules/lodash/internal/createPadding.js | 31 + node_modules/lodash/internal/createPartial.js | 20 + .../lodash/internal/createPartialWrapper.js | 43 + node_modules/lodash/internal/createReduce.js | 22 + .../lodash/internal/createSortedIndex.js | 20 + node_modules/lodash/internal/createWrapper.js | 86 + node_modules/lodash/internal/deburrLetter.js | 33 + node_modules/lodash/internal/equalArrays.js | 51 + node_modules/lodash/internal/equalByTag.js | 48 + node_modules/lodash/internal/equalObjects.js | 67 + .../lodash/internal/escapeHtmlChar.js | 22 + .../lodash/internal/escapeStringChar.js | 23 + node_modules/lodash/internal/getData.js | 15 + node_modules/lodash/internal/getFuncName.js | 25 + node_modules/lodash/internal/getLength.js | 15 + node_modules/lodash/internal/getMatchData.js | 21 + node_modules/lodash/internal/getNative.js | 16 + node_modules/lodash/internal/getView.js | 33 + node_modules/lodash/internal/indexOfNaN.js | 23 + .../lodash/internal/initCloneArray.js | 26 + .../lodash/internal/initCloneByTag.js | 63 + .../lodash/internal/initCloneObject.js | 16 + node_modules/lodash/internal/invokePath.js | 26 + node_modules/lodash/internal/isArrayLike.js | 15 + node_modules/lodash/internal/isIndex.js | 24 + .../lodash/internal/isIterateeCall.js | 28 + node_modules/lodash/internal/isKey.js | 28 + node_modules/lodash/internal/isLaziable.js | 26 + node_modules/lodash/internal/isLength.js | 20 + node_modules/lodash/internal/isObjectLike.js | 12 + node_modules/lodash/internal/isSpace.js | 14 + .../lodash/internal/isStrictComparable.js | 15 + node_modules/lodash/internal/lazyClone.js | 27 + node_modules/lodash/internal/lazyReverse.js | 23 + node_modules/lodash/internal/lazyValue.js | 81 + 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 + node_modules/lodash/internal/metaMap.js | 9 + node_modules/lodash/internal/pickByArray.js | 28 + .../lodash/internal/pickByCallback.js | 22 + node_modules/lodash/internal/reEscape.js | 4 + node_modules/lodash/internal/reEvaluate.js | 4 + node_modules/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 + .../lodash/internal/shimIsPlainObject.js | 50 + node_modules/lodash/internal/shimKeys.js | 41 + node_modules/lodash/internal/sortedUniq.js | 29 + node_modules/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 + node_modules/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 | 36 + 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 | 41 + 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 | 38 + node_modules/lodash/lang/isFunction.js | 42 + node_modules/lodash/lang/isMatch.js | 49 + node_modules/lodash/lang/isNaN.js | 34 + node_modules/lodash/lang/isNative.js | 57 + 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 | 61 + 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 | 6 + node_modules/lodash/math/add.js | 19 + node_modules/lodash/math/max.js | 56 + node_modules/lodash/math/min.js | 56 + node_modules/lodash/math/sum.js | 52 + 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 | 30 + node_modules/lodash/object/assign.js | 43 + node_modules/lodash/object/create.js | 47 + node_modules/lodash/object/defaults.js | 32 + 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 | 94 + 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 + node_modules/lodash/string/escapeRegExp.js | 32 + node_modules/lodash/string/kebabCase.js | 26 + node_modules/lodash/string/pad.js | 49 + node_modules/lodash/string/padLeft.js | 27 + node_modules/lodash/string/padRight.js | 27 + node_modules/lodash/string/parseInt.js | 67 + node_modules/lodash/string/repeat.js | 49 + 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 | 34 + 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 | 89 + 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 | 68 + node_modules/lodash/utility/times.js | 62 + node_modules/lodash/utility/uniqueId.js | 27 + node_modules/mongoose/.npmignore | 16 + node_modules/mongoose/.travis.yml | 7 + node_modules/mongoose/CONTRIBUTING.md | 58 + node_modules/mongoose/History.md | 2409 +++ node_modules/mongoose/README.md | 317 + node_modules/mongoose/contRun.sh | 10 + node_modules/mongoose/examples/README.md | 41 + .../mongoose/examples/aggregate/aggregate.js | 78 + .../mongoose/examples/aggregate/package.json | 14 + .../mongoose/examples/aggregate/person.js | 17 + node_modules/mongoose/examples/doc-methods.js | 70 + .../mongoose/examples/express/README.md | 1 + .../express/connection-sharing/README.md | 6 + .../express/connection-sharing/app.js | 18 + .../express/connection-sharing/modelA.js | 6 + .../express/connection-sharing/package.json | 14 + .../express/connection-sharing/routes.js | 20 + .../examples/geospatial/geoJSONSchema.js | 22 + .../examples/geospatial/geoJSONexample.js | 49 + .../examples/geospatial/geospatial.js | 67 + .../mongoose/examples/geospatial/package.json | 14 + .../mongoose/examples/geospatial/person.js | 28 + .../examples/globalschemas/gs_example.js | 40 + .../mongoose/examples/globalschemas/person.js | 15 + node_modules/mongoose/examples/lean/lean.js | 61 + .../mongoose/examples/lean/package.json | 14 + node_modules/mongoose/examples/lean/person.js | 17 + .../mongoose/examples/mapreduce/mapreduce.js | 77 + .../mongoose/examples/mapreduce/package.json | 14 + .../mongoose/examples/mapreduce/person.js | 16 + .../population-across-three-collections.js | 135 + .../examples/population/population-basic.js | 95 + .../population/population-of-existing-doc.js | 101 + .../population-of-multiple-existing-docs.js | 112 + .../examples/population/population-options.js | 124 + .../population/population-plain-objects.js | 96 + .../mongoose/examples/promises/package.json | 14 + .../mongoose/examples/promises/person.js | 15 + .../mongoose/examples/promises/promise.js | 70 + .../examples/querybuilder/package.json | 14 + .../mongoose/examples/querybuilder/person.js | 15 + .../examples/querybuilder/querybuilder.js | 65 + .../examples/replicasets/package.json | 14 + .../mongoose/examples/replicasets/person.js | 15 + .../examples/replicasets/replica-sets.js | 53 + .../mongoose/examples/schema/schema.js | 102 + .../schema/storing-schemas-as-json/index.js | 27 + .../storing-schemas-as-json/schema.json | 9 + .../mongoose/examples/statics/person.js | 21 + .../mongoose/examples/statics/statics.js | 38 + node_modules/mongoose/index.js | 7 + node_modules/mongoose/lib/aggregate.js | 488 + node_modules/mongoose/lib/browser.js | 97 + node_modules/mongoose/lib/browserDocument.js | 117 + node_modules/mongoose/lib/cast.js | 207 + node_modules/mongoose/lib/collection.js | 188 + node_modules/mongoose/lib/connection.js | 700 + node_modules/mongoose/lib/connectionstate.js | 27 + node_modules/mongoose/lib/document.js | 2117 +++ .../mongoose/lib/document_provider.js | 20 + node_modules/mongoose/lib/drivers/SPEC.md | 4 + .../lib/drivers/node-mongodb-native/binary.js | 8 + .../drivers/node-mongodb-native/collection.js | 215 + .../drivers/node-mongodb-native/connection.js | 378 + .../drivers/node-mongodb-native/objectid.js | 15 + node_modules/mongoose/lib/error.js | 52 + .../lib/error/browserMissingSchema.js | 33 + node_modules/mongoose/lib/error/cast.js | 37 + .../mongoose/lib/error/divergentArray.js | 42 + node_modules/mongoose/lib/error/messages.js | 43 + .../mongoose/lib/error/missingSchema.js | 33 + .../mongoose/lib/error/overwriteModel.js | 31 + node_modules/mongoose/lib/error/validation.js | 58 + node_modules/mongoose/lib/error/validator.js | 67 + node_modules/mongoose/lib/error/version.js | 32 + node_modules/mongoose/lib/index.js | 655 + node_modules/mongoose/lib/internal.js | 31 + node_modules/mongoose/lib/model.js | 2851 ++++ node_modules/mongoose/lib/promise.js | 259 + node_modules/mongoose/lib/query.js | 2929 ++++ node_modules/mongoose/lib/queryhelpers.js | 79 + node_modules/mongoose/lib/querystream.js | 340 + node_modules/mongoose/lib/schema.js | 1027 ++ node_modules/mongoose/lib/schema/array.js | 397 + node_modules/mongoose/lib/schema/boolean.js | 105 + node_modules/mongoose/lib/schema/buffer.js | 183 + node_modules/mongoose/lib/schema/date.js | 293 + .../mongoose/lib/schema/documentarray.js | 249 + node_modules/mongoose/lib/schema/index.js | 28 + node_modules/mongoose/lib/schema/mixed.js | 91 + node_modules/mongoose/lib/schema/number.js | 273 + node_modules/mongoose/lib/schema/objectid.js | 203 + node_modules/mongoose/lib/schema/string.js | 477 + node_modules/mongoose/lib/schematype.js | 796 + .../mongoose/lib/services/updateValidators.js | 147 + node_modules/mongoose/lib/statemachine.js | 179 + node_modules/mongoose/lib/types/array.js | 729 + node_modules/mongoose/lib/types/buffer.js | 276 + .../mongoose/lib/types/documentarray.js | 218 + node_modules/mongoose/lib/types/embedded.js | 310 + node_modules/mongoose/lib/types/index.js | 13 + node_modules/mongoose/lib/types/objectid.js | 20 + node_modules/mongoose/lib/utils.js | 787 + node_modules/mongoose/lib/virtualtype.js | 103 + .../mongoose/node_modules/async/.travis.yml | 3 + .../mongoose/node_modules/async/LICENSE | 19 + .../mongoose/node_modules/async/README.md | 1646 +++ .../node_modules/async/component.json | 11 + .../mongoose/node_modules/async/lib/async.js | 1123 ++ .../mongoose/node_modules/async/package.json | 45 + .../mongoose/node_modules/bson/.travis.yml | 4 + .../mongoose/node_modules/bson/HISTORY | 42 + .../mongoose/node_modules/bson/LICENSE | 201 + .../mongoose/node_modules/bson/README.md | 69 + .../node_modules/bson/browser_build/bson.js | 4843 ++++++ .../bson/browser_build/package.json | 8 + .../node_modules/bson/lib/bson/binary.js | 344 + .../bson/lib/bson/binary_parser.js | 385 + .../node_modules/bson/lib/bson/bson.js | 1573 ++ .../node_modules/bson/lib/bson/bson_new.js | 776 + .../node_modules/bson/lib/bson/code.js | 24 + .../node_modules/bson/lib/bson/db_ref.js | 32 + .../node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 121 + .../node_modules/bson/lib/bson/index.js | 81 + .../node_modules/bson/lib/bson/long.js | 856 ++ .../node_modules/bson/lib/bson/max_key.js | 14 + .../node_modules/bson/lib/bson/min_key.js | 14 + .../node_modules/bson/lib/bson/objectid.js | 274 + .../node_modules/bson/lib/bson/symbol.js | 47 + .../node_modules/bson/lib/bson/timestamp.js | 856 ++ .../bson/node_modules/bson-ext/.npmignore | 38 + .../bson/node_modules/bson-ext/HISTORY | 31 + .../bson/node_modules/bson-ext/LICENSE | 201 + .../bson/node_modules/bson-ext/Makefile | 16 + .../bson/node_modules/bson-ext/README.md | 37 + .../bson/node_modules/bson-ext/binding.gyp | 30 + .../bson/node_modules/bson-ext/build/Makefile | 350 + .../build/Release/.deps/Release/bson.node.d | 1 + .../Release/obj.target/bson/ext/bson.o.d | 38 + .../bson-ext/build/Release/bson.node | Bin 0 -> 63500 bytes .../bson-ext/build/Release/linker.lock | 0 .../build/Release/obj.target/bson/ext/bson.o | Bin 0 -> 393364 bytes .../bson-ext/build/binding.Makefile | 6 + .../bson-ext/build/bson.target.mk | 154 + .../node_modules/bson-ext/build/config.gypi | 134 + .../node_modules/bson-ext/build/gyp-mac-tool | 512 + .../bson/node_modules/bson-ext/ext/.npmignore | 3 + .../bson/node_modules/bson-ext/ext/Makefile | 28 + .../bson/node_modules/bson-ext/ext/bson.cc | 1072 ++ .../bson/node_modules/bson-ext/ext/bson.h | 278 + .../bson/node_modules/bson-ext/ext/index.js | 31 + .../bson/node_modules/bson-ext/ext/wscript | 39 + .../bson/node_modules/bson-ext/index.js | 14 + .../node_modules/bson-ext/lib/bson/binary.js | 344 + .../bson-ext/lib/bson/binary_parser.js | 385 + .../node_modules/bson-ext/lib/bson/code.js | 24 + .../node_modules/bson-ext/lib/bson/db_ref.js | 32 + .../node_modules/bson-ext/lib/bson/double.js | 33 + .../node_modules/bson-ext/lib/bson/long.js | 856 ++ .../node_modules/bson-ext/lib/bson/max_key.js | 14 + .../node_modules/bson-ext/lib/bson/min_key.js | 14 + .../bson-ext/lib/bson/objectid.js | 274 + .../node_modules/bson-ext/lib/bson/symbol.js | 47 + .../bson-ext/lib/bson/timestamp.js | 856 ++ .../bson-ext/node_modules/.bin/node-pre-gyp | 1 + .../bson-ext/node_modules/nan/.dntrc | 30 + .../bson-ext/node_modules/nan/CHANGELOG.md | 294 + .../bson-ext/node_modules/nan/LICENSE.md | 13 + .../bson-ext/node_modules/nan/README.md | 1402 ++ .../bson-ext/node_modules/nan/appveyor.yml | 38 + .../bson-ext/node_modules/nan/include_dirs.js | 1 + .../bson-ext/node_modules/nan/nan.h | 2322 +++ .../nan/nan_implementation_12_inl.h | 261 + .../nan/nan_implementation_pre_12_inl.h | 267 + .../bson-ext/node_modules/nan/nan_new.h | 328 + .../node_modules/nan/nan_string_bytes.h | 312 + .../bson-ext/node_modules/nan/package.json | 90 + .../node_modules/node-pre-gyp/.npmignore | 18 + .../node_modules/node-pre-gyp/.travis.yml | 41 + .../node_modules/node-pre-gyp/CHANGELOG.md | 210 + .../node_modules/node-pre-gyp/LICENSE | 27 + .../node_modules/node-pre-gyp/README.md | 581 + .../node_modules/node-pre-gyp/appveyor.yml | 30 + .../node-pre-gyp/bin/node-pre-gyp.js | 131 + .../node_modules/node-pre-gyp/lib/build.js | 43 + .../node_modules/node-pre-gyp/lib/clean.js | 23 + .../node-pre-gyp/lib/configure.js | 48 + .../node_modules/node-pre-gyp/lib/info.js | 40 + .../node_modules/node-pre-gyp/lib/install.js | 205 + .../node-pre-gyp/lib/node-pre-gyp.js | 192 + .../node_modules/node-pre-gyp/lib/package.js | 46 + .../node-pre-gyp/lib/pre-binding.js | 25 + .../node-pre-gyp/lib/publish-maybe.js | 146 + .../node_modules/node-pre-gyp/lib/publish.js | 77 + .../node_modules/node-pre-gyp/lib/rebuild.js | 13 + .../node-pre-gyp/lib/reinstall.js | 13 + .../node_modules/node-pre-gyp/lib/reveal.js | 31 + .../node-pre-gyp/lib/testbinary.js | 73 + .../node-pre-gyp/lib/testpackage.js | 49 + .../node-pre-gyp/lib/unpublish.js | 41 + .../node-pre-gyp/lib/util/abi_crosswalk.json | 366 + .../node-pre-gyp/lib/util/compile.js | 87 + .../node-pre-gyp/lib/util/handle_gyp_opts.js | 94 + .../lib/util/nw-pre-gyp/index.html | 26 + .../lib/util/nw-pre-gyp/package.json | 9 + .../node-pre-gyp/lib/util/s3_setup.js | 27 + .../node-pre-gyp/lib/util/versioning.js | 276 + .../node-pre-gyp/node_modules/.bin/mkdirp | 1 + .../node-pre-gyp/node_modules/.bin/nopt | 1 + .../node-pre-gyp/node_modules/.bin/rc | 1 + .../node-pre-gyp/node_modules/.bin/rimraf | 1 + .../node-pre-gyp/node_modules/.bin/semver | 1 + .../node_modules/mkdirp/.travis.yml | 8 + .../node-pre-gyp/node_modules/mkdirp/LICENSE | 21 + .../node_modules/mkdirp/bin/cmd.js | 33 + .../node_modules/mkdirp/bin/usage.txt | 12 + .../node_modules/mkdirp/examples/pow.js | 6 + .../node-pre-gyp/node_modules/mkdirp/index.js | 98 + .../mkdirp/node_modules/minimist/.travis.yml | 4 + .../mkdirp/node_modules/minimist/LICENSE | 18 + .../node_modules/minimist/example/parse.js | 2 + .../mkdirp/node_modules/minimist/index.js | 187 + .../mkdirp/node_modules/minimist/package.json | 67 + .../node_modules/minimist/readme.markdown | 73 + .../mkdirp/node_modules/minimist/test/dash.js | 24 + .../minimist/test/default_bool.js | 20 + .../node_modules/minimist/test/dotted.js | 16 + .../mkdirp/node_modules/minimist/test/long.js | 31 + .../node_modules/minimist/test/parse.js | 318 + .../minimist/test/parse_modified.js | 9 + .../node_modules/minimist/test/short.js | 67 + .../node_modules/minimist/test/whitespace.js | 8 + .../node_modules/mkdirp/package.json | 60 + .../node_modules/mkdirp/readme.markdown | 100 + .../node_modules/mkdirp/test/chmod.js | 41 + .../node_modules/mkdirp/test/clobber.js | 38 + .../node_modules/mkdirp/test/mkdirp.js | 28 + .../node_modules/mkdirp/test/opts_fs.js | 29 + .../node_modules/mkdirp/test/opts_fs_sync.js | 27 + .../node_modules/mkdirp/test/perm.js | 32 + .../node_modules/mkdirp/test/perm_sync.js | 36 + .../node_modules/mkdirp/test/race.js | 37 + .../node_modules/mkdirp/test/rel.js | 32 + .../node_modules/mkdirp/test/return.js | 25 + .../node_modules/mkdirp/test/return_sync.js | 24 + .../node_modules/mkdirp/test/root.js | 19 + .../node_modules/mkdirp/test/sync.js | 32 + .../node_modules/mkdirp/test/umask.js | 28 + .../node_modules/mkdirp/test/umask_sync.js | 32 + .../node-pre-gyp/node_modules/nopt/.npmignore | 1 + .../node-pre-gyp/node_modules/nopt/LICENSE | 15 + .../node-pre-gyp/node_modules/nopt/README.md | 209 + .../node_modules/nopt/bin/nopt.js | 54 + .../node_modules/nopt/examples/my-program.js | 30 + .../node_modules/nopt/lib/nopt.js | 414 + .../nopt/node_modules/abbrev/.npmignore | 4 + .../nopt/node_modules/abbrev/.travis.yml | 5 + .../nopt/node_modules/abbrev/CONTRIBUTING.md | 3 + .../nopt/node_modules/abbrev/LICENSE | 15 + .../nopt/node_modules/abbrev/README.md | 23 + .../nopt/node_modules/abbrev/abbrev.js | 62 + .../nopt/node_modules/abbrev/package.json | 47 + .../nopt/node_modules/abbrev/test.js | 47 + .../node_modules/nopt/package.json | 55 + .../node_modules/nopt/test/basic.js | 251 + .../node-pre-gyp/node_modules/npmlog/.npmrc | 2 + .../node-pre-gyp/node_modules/npmlog/LICENSE | 15 + .../node_modules/npmlog/README.md | 195 + .../node_modules/npmlog/example.js | 39 + .../node-pre-gyp/node_modules/npmlog/log.js | 247 + .../npmlog/node_modules/ansi/.jshintrc | 4 + .../npmlog/node_modules/ansi/.npmignore | 1 + .../npmlog/node_modules/ansi/History.md | 16 + .../npmlog/node_modules/ansi/README.md | 98 + .../node_modules/ansi/examples/beep/index.js | 16 + .../node_modules/ansi/examples/clear/index.js | 15 + .../ansi/examples/cursorPosition.js | 32 + .../ansi/examples/progress/index.js | 87 + .../npmlog/node_modules/ansi/lib/ansi.js | 405 + .../npmlog/node_modules/ansi/lib/newlines.js | 71 + .../npmlog/node_modules/ansi/package.json | 54 + .../node_modules/are-we-there-yet/.npmignore | 3 + .../node_modules/are-we-there-yet/README.md | 183 + .../node_modules/are-we-there-yet/index.js | 130 + .../node_modules/delegates/.npmignore | 1 + .../node_modules/delegates/History.md | 16 + .../node_modules/delegates/Makefile | 8 + .../node_modules/delegates/Readme.md | 94 + .../node_modules/delegates/index.js | 121 + .../node_modules/delegates/package.json | 48 + .../node_modules/delegates/test/index.js | 94 + .../node_modules/readable-stream/.npmignore | 5 + .../node_modules/readable-stream/LICENSE | 18 + .../node_modules/readable-stream/README.md | 15 + .../node_modules/readable-stream/duplex.js | 1 + .../node_modules/readable-stream/float.patch | 923 ++ .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 951 ++ .../readable-stream/lib/_stream_transform.js | 209 + .../readable-stream/lib/_stream_writable.js | 477 + .../node_modules/core-util-is/README.md | 3 + .../node_modules/core-util-is/float.patch | 604 + .../node_modules/core-util-is/lib/util.js | 107 + .../node_modules/core-util-is/package.json | 37 + .../node_modules/core-util-is/util.js | 106 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 35 + .../node_modules/inherits/test.js | 25 + .../node_modules/isarray/README.md | 54 + .../node_modules/isarray/build/build.js | 209 + .../node_modules/isarray/component.json | 19 + .../node_modules/isarray/index.js | 3 + .../node_modules/isarray/package.json | 38 + .../node_modules/string_decoder/.npmignore | 2 + .../node_modules/string_decoder/LICENSE | 20 + .../node_modules/string_decoder/README.md | 7 + .../node_modules/string_decoder/index.js | 221 + .../node_modules/string_decoder/package.json | 34 + .../node_modules/readable-stream/package.json | 46 + .../readable-stream/passthrough.js | 1 + .../node_modules/readable-stream/readable.js | 7 + .../node_modules/readable-stream/transform.js | 1 + .../node_modules/readable-stream/writable.js | 1 + .../are-we-there-yet/package.json | 51 + .../are-we-there-yet/test/tracker.js | 56 + .../are-we-there-yet/test/trackergroup.js | 87 + .../are-we-there-yet/test/trackerstream.js | 65 + .../npmlog/node_modules/gauge/.npmignore | 32 + .../npmlog/node_modules/gauge/LICENSE | 13 + .../npmlog/node_modules/gauge/README.md | 161 + .../npmlog/node_modules/gauge/README.md~ | 153 + .../npmlog/node_modules/gauge/example.png | Bin 0 -> 19689 bytes .../gauge/node_modules/has-unicode/.npmignore | 32 + .../gauge/node_modules/has-unicode/LICENSE | 14 + .../gauge/node_modules/has-unicode/README.md | 40 + .../gauge/node_modules/has-unicode/README.md~ | 4 + .../gauge/node_modules/has-unicode/index.js | 18 + .../node_modules/has-unicode/package.json | 53 + .../node_modules/has-unicode/test/index.js | 26 + .../gauge/node_modules/lodash.pad/LICENSE.txt | 22 + .../gauge/node_modules/lodash.pad/README.md | 20 + .../gauge/node_modules/lodash.pad/index.js | 57 + .../lodash._basetostring/LICENSE.txt | 22 + .../lodash._basetostring/README.md | 20 + .../lodash._basetostring/index.js | 25 + .../lodash._basetostring/package.json | 56 + .../lodash._createpadding/LICENSE.txt | 22 + .../lodash._createpadding/README.md | 20 + .../lodash._createpadding/index.js | 39 + .../node_modules/lodash.repeat/LICENSE.txt | 22 + .../node_modules/lodash.repeat/README.md | 20 + .../node_modules/lodash.repeat/index.js | 57 + .../node_modules/lodash.repeat/package.json | 81 + .../lodash._createpadding/package.json | 75 + .../node_modules/lodash.pad/package.json | 98 + .../node_modules/lodash.padleft/LICENSE.txt | 22 + .../node_modules/lodash.padleft/README.md | 20 + .../node_modules/lodash.padleft/index.js | 50 + .../lodash._basetostring/LICENSE.txt | 22 + .../lodash._basetostring/README.md | 20 + .../lodash._basetostring/index.js | 25 + .../lodash._basetostring/package.json | 56 + .../lodash._createpadding/LICENSE.txt | 22 + .../lodash._createpadding/README.md | 20 + .../lodash._createpadding/index.js | 39 + .../node_modules/lodash.repeat/LICENSE.txt | 22 + .../node_modules/lodash.repeat/README.md | 20 + .../node_modules/lodash.repeat/index.js | 57 + .../node_modules/lodash.repeat/package.json | 81 + .../lodash._createpadding/package.json | 75 + .../node_modules/lodash.padleft/package.json | 98 + .../node_modules/lodash.padright/LICENSE.txt | 22 + .../node_modules/lodash.padright/README.md | 20 + .../node_modules/lodash.padright/index.js | 50 + .../lodash._basetostring/LICENSE.txt | 22 + .../lodash._basetostring/README.md | 20 + .../lodash._basetostring/index.js | 25 + .../lodash._basetostring/package.json | 56 + .../lodash._createpadding/LICENSE.txt | 22 + .../lodash._createpadding/README.md | 20 + .../lodash._createpadding/index.js | 39 + .../node_modules/lodash.repeat/LICENSE.txt | 22 + .../node_modules/lodash.repeat/README.md | 20 + .../node_modules/lodash.repeat/index.js | 57 + .../node_modules/lodash.repeat/package.json | 81 + .../lodash._createpadding/package.json | 75 + .../node_modules/lodash.padright/package.json | 98 + .../npmlog/node_modules/gauge/package.json | 60 + .../npmlog/node_modules/gauge/progress-bar.js | 209 + .../node_modules/gauge/test/progress-bar.js | 148 + .../node_modules/npmlog/package.json | 58 + .../node_modules/npmlog/test/basic.js | 228 + .../node_modules/npmlog/test/progress.js | 114 + .../node-pre-gyp/node_modules/rc/.npmignore | 3 + .../node_modules/rc/LICENSE.APACHE2 | 15 + .../node-pre-gyp/node_modules/rc/LICENSE.BSD | 26 + .../node-pre-gyp/node_modules/rc/LICENSE.MIT | 24 + .../node-pre-gyp/node_modules/rc/README.md | 149 + .../node-pre-gyp/node_modules/rc/browser.js | 7 + .../node-pre-gyp/node_modules/rc/index.js | 60 + .../node-pre-gyp/node_modules/rc/lib/utils.js | 101 + .../rc/node_modules/.bin/strip-json-comments | 1 + .../rc/node_modules/deep-extend/.npmignore | 1 + .../rc/node_modules/deep-extend/LICENSE | 20 + .../rc/node_modules/deep-extend/README.md | 52 + .../rc/node_modules/deep-extend/index.js | 90 + .../rc/node_modules/deep-extend/package.json | 45 + .../deep-extend/test/index.spec.js | 57 + .../node_modules/deep-extend/test/mocha.opts | 1 + .../rc/node_modules/ini/.npmignore | 1 + .../node_modules/rc/node_modules/ini/LICENSE | 15 + .../rc/node_modules/ini/README.md | 102 + .../node_modules/rc/node_modules/ini/ini.js | 190 + .../rc/node_modules/ini/package.json | 53 + .../rc/node_modules/ini/test/bar.js | 23 + .../rc/node_modules/ini/test/fixtures/foo.ini | 65 + .../rc/node_modules/ini/test/foo.js | 107 + .../rc/node_modules/minimist/.travis.yml | 4 + .../rc/node_modules/minimist/LICENSE | 18 + .../rc/node_modules/minimist/example/parse.js | 2 + .../rc/node_modules/minimist/index.js | 187 + .../rc/node_modules/minimist/package.json | 52 + .../rc/node_modules/minimist/readme.markdown | 73 + .../rc/node_modules/minimist/test/bool.js | 119 + .../rc/node_modules/minimist/test/dash.js | 24 + .../minimist/test/default_bool.js | 20 + .../rc/node_modules/minimist/test/dotted.js | 22 + .../rc/node_modules/minimist/test/long.js | 31 + .../rc/node_modules/minimist/test/num.js | 36 + .../rc/node_modules/minimist/test/parse.js | 197 + .../minimist/test/parse_modified.js | 9 + .../rc/node_modules/minimist/test/short.js | 67 + .../node_modules/minimist/test/whitespace.js | 8 + .../node_modules/strip-json-comments/cli.js | 41 + .../strip-json-comments/package.json | 61 + .../strip-json-comments/readme.md | 74 + .../strip-json-comments.js | 64 + .../node-pre-gyp/node_modules/rc/package.json | 60 + .../node-pre-gyp/node_modules/rc/test/ini.js | 16 + .../node_modules/rc/test/nested-env-vars.js | 39 + .../node-pre-gyp/node_modules/rc/test/test.js | 59 + .../node_modules/request/.eslintrc | 45 + .../node_modules/request/.npmignore | 3 + .../node_modules/request/.travis.yml | 12 + .../node_modules/request/CHANGELOG.md | 493 + .../node_modules/request/CONTRIBUTING.md | 44 + .../node-pre-gyp/node_modules/request/LICENSE | 55 + .../node_modules/request/README.md | 1058 ++ .../request/disabled.appveyor.yml | 36 + .../node_modules/request/examples/README.md | 115 + .../node_modules/request/index.js | 159 + .../node_modules/request/lib/auth.js | 153 + .../node_modules/request/lib/cookies.js | 39 + .../node_modules/request/lib/copy.js | 10 + .../request/lib/getProxyFromURI.js | 79 + .../node_modules/request/lib/har.js | 205 + .../node_modules/request/lib/helpers.js | 55 + .../node_modules/request/lib/multipart.js | 109 + .../node_modules/request/lib/oauth.js | 144 + .../node_modules/request/lib/querystring.js | 51 + .../node_modules/request/lib/redirect.js | 153 + .../request/node_modules/.bin/har-validator | 1 + .../request/node_modules/.bin/uuid | 1 + .../request/node_modules/aws-sign2/LICENSE | 55 + .../request/node_modules/aws-sign2/README.md | 4 + .../request/node_modules/aws-sign2/index.js | 202 + .../node_modules/aws-sign2/package.json | 30 + .../request/node_modules/bl/.jshintrc | 59 + .../request/node_modules/bl/.npmignore | 1 + .../request/node_modules/bl/.travis.yml | 11 + .../request/node_modules/bl/LICENSE.md | 13 + .../request/node_modules/bl/README.md | 198 + .../request/node_modules/bl/bl.js | 216 + .../node_modules/readable-stream/.npmignore | 5 + .../bl/node_modules/readable-stream/LICENSE | 18 + .../bl/node_modules/readable-stream/README.md | 15 + .../bl/node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 982 ++ .../readable-stream/lib/_stream_transform.js | 210 + .../readable-stream/lib/_stream_writable.js | 386 + .../node_modules/core-util-is/README.md | 3 + .../node_modules/core-util-is/float.patch | 604 + .../node_modules/core-util-is/lib/util.js | 107 + .../node_modules/core-util-is/package.json | 37 + .../node_modules/core-util-is/util.js | 106 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 35 + .../node_modules/inherits/test.js | 25 + .../node_modules/isarray/README.md | 54 + .../node_modules/isarray/build/build.js | 209 + .../node_modules/isarray/component.json | 19 + .../node_modules/isarray/index.js | 3 + .../node_modules/isarray/package.json | 38 + .../node_modules/string_decoder/.npmignore | 2 + .../node_modules/string_decoder/LICENSE | 20 + .../node_modules/string_decoder/README.md | 7 + .../node_modules/string_decoder/index.js | 221 + .../node_modules/string_decoder/package.json | 34 + .../node_modules/readable-stream/package.json | 46 + .../readable-stream/passthrough.js | 1 + .../node_modules/readable-stream/readable.js | 8 + .../node_modules/readable-stream/transform.js | 1 + .../node_modules/readable-stream/writable.js | 1 + .../request/node_modules/bl/package.json | 45 + .../node_modules/bl/test/basic-test.js | 541 + .../request/node_modules/bl/test/sauce.js | 38 + .../request/node_modules/bl/test/test.js | 9 + .../request/node_modules/caseless/README.md | 45 + .../request/node_modules/caseless/index.js | 65 + .../node_modules/caseless/package.json | 56 + .../request/node_modules/caseless/test.js | 40 + .../node_modules/combined-stream/License | 19 + .../node_modules/combined-stream/Readme.md | 139 + .../combined-stream/lib/combined_stream.js | 188 + .../node_modules/delayed-stream/.npmignore | 1 + .../node_modules/delayed-stream/License | 19 + .../node_modules/delayed-stream/Makefile | 7 + .../node_modules/delayed-stream/Readme.md | 141 + .../delayed-stream/lib/delayed_stream.js | 107 + .../node_modules/delayed-stream/package.json | 63 + .../node_modules/combined-stream/package.json | 66 + .../node_modules/forever-agent/LICENSE | 55 + .../node_modules/forever-agent/README.md | 4 + .../node_modules/forever-agent/index.js | 138 + .../node_modules/forever-agent/package.json | 56 + .../request/node_modules/form-data/License | 19 + .../request/node_modules/form-data/Readme.md | 175 + .../node_modules/form-data/lib/form_data.js | 351 + .../node_modules/combined-stream/License | 19 + .../node_modules/combined-stream/Readme.md | 132 + .../combined-stream/lib/combined_stream.js | 188 + .../node_modules/delayed-stream/.npmignore | 2 + .../node_modules/delayed-stream/License | 19 + .../node_modules/delayed-stream/Makefile | 7 + .../node_modules/delayed-stream/Readme.md | 154 + .../delayed-stream/lib/delayed_stream.js | 99 + .../node_modules/delayed-stream/package.json | 33 + .../delayed-stream/test/common.js | 6 + .../integration/test-delayed-http-upload.js | 38 + .../test-delayed-stream-auto-pause.js | 21 + .../integration/test-delayed-stream-pause.js | 14 + .../test/integration/test-delayed-stream.js | 48 + .../integration/test-handle-source-errors.js | 15 + .../test/integration/test-max-data-size.js | 18 + .../test/integration/test-pipe-resumes.js | 13 + .../test/integration/test-proxy-readable.js | 13 + .../node_modules/delayed-stream/test/run.js | 7 + .../node_modules/combined-stream/package.json | 37 + .../node_modules/form-data/package.json | 48 + .../node_modules/har-validator/LICENSE | 21 + .../node_modules/har-validator/README.md | 362 + .../har-validator/bin/har-validator | 45 + .../node_modules/bluebird/LICENSE | 21 + .../node_modules/bluebird/README.md | 676 + .../node_modules/bluebird/changelog.md | 1653 +++ .../bluebird/js/browser/bluebird.js | 5102 +++++++ .../bluebird/js/browser/bluebird.min.js | 31 + .../node_modules/bluebird/js/main/any.js | 21 + .../node_modules/bluebird/js/main/assert.js | 55 + .../node_modules/bluebird/js/main/async.js | 204 + .../node_modules/bluebird/js/main/bind.js | 73 + .../node_modules/bluebird/js/main/bluebird.js | 11 + .../node_modules/bluebird/js/main/call_get.js | 123 + .../node_modules/bluebird/js/main/cancel.js | 48 + .../bluebird/js/main/captured_trace.js | 492 + .../bluebird/js/main/catch_filter.js | 66 + .../node_modules/bluebird/js/main/context.js | 38 + .../bluebird/js/main/debuggability.js | 147 + .../bluebird/js/main/direct_resolve.js | 62 + .../node_modules/bluebird/js/main/each.js | 12 + .../node_modules/bluebird/js/main/errors.js | 111 + .../node_modules/bluebird/js/main/es5.js | 80 + .../node_modules/bluebird/js/main/filter.js | 12 + .../node_modules/bluebird/js/main/finally.js | 99 + .../bluebird/js/main/generators.js | 136 + .../node_modules/bluebird/js/main/join.js | 107 + .../node_modules/bluebird/js/main/map.js | 131 + .../node_modules/bluebird/js/main/method.js | 44 + .../node_modules/bluebird/js/main/nodeify.js | 58 + .../node_modules/bluebird/js/main/progress.js | 76 + .../node_modules/bluebird/js/main/promise.js | 700 + .../bluebird/js/main/promise_array.js | 142 + .../bluebird/js/main/promise_resolver.js | 123 + .../bluebird/js/main/promisify.js | 291 + .../node_modules/bluebird/js/main/props.js | 79 + .../node_modules/bluebird/js/main/queue.js | 90 + .../node_modules/bluebird/js/main/race.js | 47 + .../node_modules/bluebird/js/main/reduce.js | 146 + .../node_modules/bluebird/js/main/schedule.js | 32 + .../node_modules/bluebird/js/main/settle.js | 40 + .../node_modules/bluebird/js/main/some.js | 125 + .../js/main/synchronous_inspection.js | 94 + .../bluebird/js/main/thenables.js | 89 + .../node_modules/bluebird/js/main/timers.js | 58 + .../node_modules/bluebird/js/main/using.js | 202 + .../node_modules/bluebird/js/main/util.js | 284 + .../node_modules/bluebird/package.json | 98 + .../node_modules/commander/History.md | 256 + .../node_modules/commander/LICENSE | 22 + .../node_modules/commander/Readme.md | 342 + .../node_modules/commander/index.js | 1103 ++ .../node_modules/graceful-readlink/.npmignore | 3 + .../graceful-readlink/.travis.yml | 5 + .../node_modules/graceful-readlink/LICENSE | 22 + .../node_modules/graceful-readlink/README.md | 17 + .../node_modules/graceful-readlink/index.js | 12 + .../graceful-readlink/package.json | 48 + .../node_modules/commander/package.json | 75 + .../node_modules/is-my-json-valid/.npmignore | 2 + .../node_modules/is-my-json-valid/.travis.yml | 3 + .../node_modules/is-my-json-valid/LICENSE | 21 + .../node_modules/is-my-json-valid/README.md | 173 + .../node_modules/is-my-json-valid/example.js | 18 + .../node_modules/is-my-json-valid/formats.js | 14 + .../node_modules/is-my-json-valid/index.js | 569 + .../node_modules/generate-function/.npmignore | 1 + .../generate-function/.travis.yml | 3 + .../node_modules/generate-function/README.md | 72 + .../node_modules/generate-function/example.js | 27 + .../node_modules/generate-function/index.js | 61 + .../generate-function/package.json | 53 + .../node_modules/generate-function/test.js | 33 + .../generate-object-property/.npmignore | 1 + .../generate-object-property/.travis.yml | 3 + .../generate-object-property/LICENSE | 21 + .../generate-object-property/README.md | 19 + .../generate-object-property/index.js | 12 + .../node_modules/is-property/.npmignore | 17 + .../node_modules/is-property/LICENSE | 22 + .../node_modules/is-property/README.md | 28 + .../node_modules/is-property/is-property.js | 5 + .../node_modules/is-property/package.json | 59 + .../generate-object-property/package.json | 51 + .../generate-object-property/test.js | 12 + .../node_modules/jsonpointer/.travis.yml | 6 + .../node_modules/jsonpointer/README.md | 31 + .../node_modules/jsonpointer/jsonpointer.js | 79 + .../node_modules/jsonpointer/package.json | 61 + .../node_modules/jsonpointer/test.js | 100 + .../node_modules/xtend/.jshintrc | 30 + .../node_modules/xtend/.npmignore | 1 + .../node_modules/xtend/LICENCE | 19 + .../node_modules/xtend/Makefile | 4 + .../node_modules/xtend/README.md | 32 + .../node_modules/xtend/immutable.js | 17 + .../node_modules/xtend/mutable.js | 15 + .../node_modules/xtend/package.json | 72 + .../node_modules/xtend/test.js | 63 + .../is-my-json-valid/package.json | 67 + .../node_modules/is-my-json-valid/require.js | 12 + .../is-my-json-valid/test/fixtures/cosmic.js | 84 + .../json-schema-draft4/additionalItems.json | 82 + .../additionalProperties.json | 88 + .../test/json-schema-draft4/allOf.json | 112 + .../test/json-schema-draft4/anyOf.json | 68 + .../test/json-schema-draft4/bignum.json | 107 + .../test/json-schema-draft4/default.json | 49 + .../test/json-schema-draft4/definitions.json | 32 + .../test/json-schema-draft4/dependencies.json | 113 + .../test/json-schema-draft4/enum.json | 72 + .../test/json-schema-draft4/format.json | 143 + .../test/json-schema-draft4/items.json | 46 + .../test/json-schema-draft4/maxItems.json | 28 + .../test/json-schema-draft4/maxLength.json | 28 + .../json-schema-draft4/maxProperties.json | 28 + .../test/json-schema-draft4/maximum.json | 42 + .../test/json-schema-draft4/minItems.json | 28 + .../test/json-schema-draft4/minLength.json | 28 + .../json-schema-draft4/minProperties.json | 28 + .../test/json-schema-draft4/minimum.json | 42 + .../test/json-schema-draft4/multipleOf.json | 60 + .../test/json-schema-draft4/not.json | 96 + .../json-schema-draft4/nullAndFormat.json | 18 + .../test/json-schema-draft4/oneOf.json | 68 + .../test/json-schema-draft4/pattern.json | 23 + .../json-schema-draft4/patternProperties.json | 110 + .../test/json-schema-draft4/properties.json | 92 + .../test/json-schema-draft4/ref.json | 128 + .../test/json-schema-draft4/refRemote.json | 74 + .../test/json-schema-draft4/required.json | 39 + .../test/json-schema-draft4/type.json | 330 + .../test/json-schema-draft4/uniqueItems.json | 79 + .../is-my-json-valid/test/json-schema.js | 23 + .../is-my-json-valid/test/misc.js | 429 + .../node_modules/har-validator/package.json | 84 + .../node_modules/har-validator/src/error.js | 10 + .../node_modules/har-validator/src/index.js | 39 + .../har-validator/src/schemas/cache.json | 13 + .../har-validator/src/schemas/cacheEntry.json | 31 + .../har-validator/src/schemas/content.json | 27 + .../har-validator/src/schemas/cookie.json | 34 + .../har-validator/src/schemas/creator.json | 18 + .../har-validator/src/schemas/entry.json | 48 + .../har-validator/src/schemas/har.json | 11 + .../har-validator/src/schemas/index.js | 49 + .../har-validator/src/schemas/log.json | 34 + .../har-validator/src/schemas/page.json | 30 + .../src/schemas/pageTimings.json | 16 + .../har-validator/src/schemas/postData.json | 41 + .../har-validator/src/schemas/record.json | 18 + .../har-validator/src/schemas/request.json | 55 + .../har-validator/src/schemas/response.json | 52 + .../har-validator/src/schemas/timings.json | 40 + .../request/node_modules/hawk/.npmignore | 20 + .../request/node_modules/hawk/.travis.yml | 5 + .../request/node_modules/hawk/LICENSE | 28 + .../request/node_modules/hawk/Makefile | 8 + .../request/node_modules/hawk/README.md | 635 + .../request/node_modules/hawk/bower.json | 24 + .../request/node_modules/hawk/component.json | 19 + .../node_modules/hawk/example/usage.js | 78 + .../request/node_modules/hawk/images/hawk.png | Bin 0 -> 6945 bytes .../request/node_modules/hawk/images/logo.png | Bin 0 -> 71732 bytes .../request/node_modules/hawk/index.js | 1 + .../request/node_modules/hawk/lib/browser.js | 641 + .../request/node_modules/hawk/lib/client.js | 369 + .../request/node_modules/hawk/lib/crypto.js | 126 + .../request/node_modules/hawk/lib/index.js | 15 + .../request/node_modules/hawk/lib/server.js | 534 + .../request/node_modules/hawk/lib/utils.js | 164 + .../hawk/node_modules/boom/.npmignore | 18 + .../hawk/node_modules/boom/.travis.yml | 7 + .../hawk/node_modules/boom/CONTRIBUTING.md | 1 + .../hawk/node_modules/boom/LICENSE | 28 + .../hawk/node_modules/boom/README.md | 583 + .../hawk/node_modules/boom/images/boom.png | Bin 0 -> 29479 bytes .../hawk/node_modules/boom/index.js | 1 + .../hawk/node_modules/boom/lib/index.js | 293 + .../hawk/node_modules/boom/package.json | 63 + .../hawk/node_modules/boom/test/index.js | 615 + .../hawk/node_modules/cryptiles/.npmignore | 18 + .../hawk/node_modules/cryptiles/.travis.yml | 5 + .../hawk/node_modules/cryptiles/LICENSE | 28 + .../hawk/node_modules/cryptiles/Makefile | 9 + .../hawk/node_modules/cryptiles/README.md | 14 + .../hawk/node_modules/cryptiles/index.js | 1 + .../hawk/node_modules/cryptiles/lib/index.js | 68 + .../hawk/node_modules/cryptiles/package.json | 65 + .../hawk/node_modules/cryptiles/test/index.js | 108 + .../hawk/node_modules/hoek/.npmignore | 18 + .../hawk/node_modules/hoek/.travis.yml | 7 + .../hawk/node_modules/hoek/CONTRIBUTING.md | 1 + .../hawk/node_modules/hoek/LICENSE | 31 + .../hawk/node_modules/hoek/Makefile | 8 + .../hawk/node_modules/hoek/README.md | 574 + .../hawk/node_modules/hoek/images/hoek.png | Bin 0 -> 37939 bytes .../hawk/node_modules/hoek/index.js | 1 + .../hawk/node_modules/hoek/lib/escape.js | 132 + .../hawk/node_modules/hoek/lib/index.js | 977 ++ .../hawk/node_modules/hoek/package.json | 59 + .../hawk/node_modules/hoek/test/escaper.js | 88 + .../hawk/node_modules/hoek/test/index.js | 2425 +++ .../node_modules/hoek/test/modules/ignore.txt | 0 .../node_modules/hoek/test/modules/test1.js | 1 + .../node_modules/hoek/test/modules/test2.js | 1 + .../node_modules/hoek/test/modules/test3.js | 1 + .../hawk/node_modules/sntp/.npmignore | 18 + .../hawk/node_modules/sntp/.travis.yml | 5 + .../hawk/node_modules/sntp/LICENSE | 28 + .../hawk/node_modules/sntp/Makefile | 9 + .../hawk/node_modules/sntp/README.md | 68 + .../hawk/node_modules/sntp/examples/offset.js | 16 + .../hawk/node_modules/sntp/examples/time.js | 25 + .../hawk/node_modules/sntp/index.js | 1 + .../hawk/node_modules/sntp/lib/index.js | 412 + .../hawk/node_modules/sntp/package.json | 65 + .../hawk/node_modules/sntp/test/index.js | 435 + .../request/node_modules/hawk/package.json | 71 + .../request/node_modules/hawk/test/browser.js | 1453 ++ .../request/node_modules/hawk/test/client.js | 443 + .../request/node_modules/hawk/test/crypto.js | 86 + .../request/node_modules/hawk/test/index.js | 378 + .../request/node_modules/hawk/test/message.js | 261 + .../request/node_modules/hawk/test/readme.js | 98 + .../request/node_modules/hawk/test/server.js | 985 ++ .../request/node_modules/hawk/test/uri.js | 590 + .../request/node_modules/hawk/test/utils.js | 120 + .../http-signature/.dir-locals.el | 6 + .../node_modules/http-signature/.npmignore | 7 + .../node_modules/http-signature/LICENSE | 18 + .../node_modules/http-signature/README.md | 79 + .../http-signature/http_signing.md | 296 + .../node_modules/http-signature/lib/index.js | 27 + .../node_modules/http-signature/lib/parser.js | 304 + .../node_modules/http-signature/lib/signer.js | 178 + .../node_modules/http-signature/lib/util.js | 306 + .../node_modules/http-signature/lib/verify.js | 56 + .../node_modules/asn1/.npmignore | 2 + .../http-signature/node_modules/asn1/LICENSE | 19 + .../node_modules/asn1/README.md | 50 + .../node_modules/asn1/lib/ber/errors.js | 13 + .../node_modules/asn1/lib/ber/index.js | 27 + .../node_modules/asn1/lib/ber/reader.js | 267 + .../node_modules/asn1/lib/ber/types.js | 36 + .../node_modules/asn1/lib/ber/writer.js | 317 + .../node_modules/asn1/lib/index.js | 20 + .../node_modules/asn1/package.json | 45 + .../node_modules/asn1/tst/ber/reader.test.js | 172 + .../node_modules/asn1/tst/ber/writer.test.js | 296 + .../node_modules/assert-plus/README.md | 126 + .../node_modules/assert-plus/assert.js | 245 + .../node_modules/assert-plus/package.json | 30 + .../node_modules/ctype/.npmignore | 1 + .../node_modules/ctype/CHANGELOG | 78 + .../http-signature/node_modules/ctype/LICENSE | 24 + .../http-signature/node_modules/ctype/README | 82 + .../node_modules/ctype/README.old | 298 + .../http-signature/node_modules/ctype/ctf.js | 245 + .../http-signature/node_modules/ctype/ctio.js | 1485 ++ .../node_modules/ctype/ctype.js | 944 ++ .../ctype/man/man3ctype/ctio.3ctype | 241 + .../node_modules/ctype/package.json | 27 + .../node_modules/ctype/tools/jsl.conf | 129 + .../node_modules/ctype/tools/jsstyle | 839 ++ .../node_modules/http-signature/package.json | 76 + .../request/node_modules/isstream/.jshintrc | 59 + .../request/node_modules/isstream/.npmignore | 1 + .../request/node_modules/isstream/.travis.yml | 12 + .../request/node_modules/isstream/LICENSE.md | 11 + .../request/node_modules/isstream/README.md | 66 + .../request/node_modules/isstream/isstream.js | 27 + .../node_modules/isstream/package.json | 59 + .../request/node_modules/isstream/test.js | 168 + .../json-stringify-safe/.npmignore | 1 + .../json-stringify-safe/CHANGELOG.md | 14 + .../node_modules/json-stringify-safe/LICENSE | 15 + .../node_modules/json-stringify-safe/Makefile | 35 + .../json-stringify-safe/README.md | 52 + .../json-stringify-safe/package.json | 68 + .../json-stringify-safe/stringify.js | 27 + .../json-stringify-safe/test/mocha.opts | 2 + .../test/stringify_test.js | 246 + .../node_modules/mime-types/HISTORY.md | 109 + .../request/node_modules/mime-types/LICENSE | 22 + .../request/node_modules/mime-types/README.md | 102 + .../request/node_modules/mime-types/index.js | 63 + .../node_modules/mime-db/HISTORY.md | 204 + .../mime-types/node_modules/mime-db/LICENSE | 22 + .../mime-types/node_modules/mime-db/README.md | 76 + .../mime-types/node_modules/mime-db/db.json | 6345 ++++++++ .../mime-types/node_modules/mime-db/index.js | 11 + .../node_modules/mime-db/package.json | 93 + .../node_modules/mime-types/package.json | 83 + .../request/node_modules/node-uuid/.npmignore | 2 + .../request/node_modules/node-uuid/LICENSE.md | 21 + .../request/node_modules/node-uuid/README.md | 243 + .../node-uuid/benchmark/README.md | 53 + .../node-uuid/benchmark/bench.gnu | 174 + .../node_modules/node-uuid/benchmark/bench.sh | 34 + .../node-uuid/benchmark/benchmark-native.c | 34 + .../node-uuid/benchmark/benchmark.js | 84 + .../request/node_modules/node-uuid/bin/uuid | 26 + .../request/node_modules/node-uuid/bower.json | 23 + .../node_modules/node-uuid/component.json | 18 + .../node_modules/node-uuid/package.json | 49 + .../node_modules/node-uuid/test/compare_v1.js | 63 + .../node_modules/node-uuid/test/test.html | 17 + .../node_modules/node-uuid/test/test.js | 228 + .../request/node_modules/node-uuid/uuid.js | 247 + .../request/node_modules/oauth-sign/LICENSE | 55 + .../request/node_modules/oauth-sign/README.md | 4 + .../request/node_modules/oauth-sign/index.js | 134 + .../node_modules/oauth-sign/package.json | 58 + .../request/node_modules/oauth-sign/test.js | 89 + .../request/node_modules/qs/.eslintignore | 1 + .../request/node_modules/qs/.jshintignore | 1 + .../request/node_modules/qs/.jshintrc | 10 + .../request/node_modules/qs/.npmignore | 19 + .../request/node_modules/qs/.travis.yml | 6 + .../request/node_modules/qs/CHANGELOG.md | 88 + .../request/node_modules/qs/CONTRIBUTING.md | 1 + .../request/node_modules/qs/LICENSE | 28 + .../request/node_modules/qs/Makefile | 8 + .../request/node_modules/qs/README.md | 303 + .../request/node_modules/qs/bower.json | 22 + .../request/node_modules/qs/index.js | 1 + .../request/node_modules/qs/lib/index.js | 15 + .../request/node_modules/qs/lib/parse.js | 166 + .../request/node_modules/qs/lib/stringify.js | 121 + .../request/node_modules/qs/lib/utils.js | 190 + .../request/node_modules/qs/package.json | 55 + .../request/node_modules/qs/test/parse.js | 455 + .../request/node_modules/qs/test/stringify.js | 259 + .../request/node_modules/qs/test/utils.js | 28 + .../node_modules/stringstream/.npmignore | 15 + .../node_modules/stringstream/.travis.yml | 4 + .../node_modules/stringstream/LICENSE.txt | 4 + .../node_modules/stringstream/README.md | 38 + .../node_modules/stringstream/example.js | 27 + .../node_modules/stringstream/package.json | 32 + .../node_modules/stringstream/stringstream.js | 102 + .../node_modules/tough-cookie/.editorconfig | 12 + .../node_modules/tough-cookie/.jshintrc | 70 + .../node_modules/tough-cookie/.npmignore | 4 + .../node_modules/tough-cookie/.travis.yml | 9 + .../request/node_modules/tough-cookie/LICENSE | 74 + .../node_modules/tough-cookie/README.md | 422 + .../tough-cookie/generate-pubsuffix.js | 293 + .../node_modules/tough-cookie/lib/cookie.js | 1088 ++ .../node_modules/tough-cookie/lib/memstore.js | 142 + .../tough-cookie/lib/pathMatch.js | 61 + .../tough-cookie/lib/permuteDomain.js | 56 + .../tough-cookie/lib/pubsuffix.js | 98 + .../node_modules/tough-cookie/lib/store.js | 67 + .../node_modules/tough-cookie/package.json | 65 + .../tough-cookie/public-suffix.txt | 10079 +++++++++++++ .../tough-cookie/test/api_test.js | 372 + .../tough-cookie/test/cookie_jar_test.js | 468 + .../tough-cookie/test/cookie_sorting_test.js | 90 + .../tough-cookie/test/cookie_to_json_test.js | 164 + .../test/cookie_to_string_test.js | 162 + .../tough-cookie/test/date_test.js | 79 + .../tough-cookie/test/domain_and_path_test.js | 201 + .../test/ietf_data/dates/bsd-examples.json | 168 + .../test/ietf_data/dates/examples.json | 48 + .../tough-cookie/test/ietf_data/parser.json | 1959 +++ .../tough-cookie/test/ietf_test.js | 106 + .../tough-cookie/test/lifetime_test.js | 97 + .../tough-cookie/test/parsing_test.js | 294 + .../tough-cookie/test/regression_test.js | 143 + .../node_modules/tunnel-agent/.jshintrc | 5 + .../request/node_modules/tunnel-agent/LICENSE | 55 + .../node_modules/tunnel-agent/README.md | 4 + .../node_modules/tunnel-agent/index.js | 236 + .../node_modules/tunnel-agent/package.json | 30 + .../node_modules/request/package.json | 107 + .../node_modules/request/release.sh | 45 + .../node_modules/request/request.js | 1556 ++ .../node-pre-gyp/node_modules/rimraf/LICENSE | 15 + .../node_modules/rimraf/README.md | 36 + .../node-pre-gyp/node_modules/rimraf/bin.js | 33 + .../rimraf/node_modules/glob/LICENSE | 15 + .../rimraf/node_modules/glob/README.md | 369 + .../rimraf/node_modules/glob/common.js | 237 + .../rimraf/node_modules/glob/glob.js | 740 + .../glob/node_modules/inflight/.eslintrc | 17 + .../glob/node_modules/inflight/LICENSE | 15 + .../glob/node_modules/inflight/README.md | 37 + .../glob/node_modules/inflight/inflight.js | 44 + .../inflight/node_modules/wrappy/LICENSE | 15 + .../inflight/node_modules/wrappy/README.md | 36 + .../inflight/node_modules/wrappy/package.json | 36 + .../node_modules/wrappy/test/basic.js | 51 + .../inflight/node_modules/wrappy/wrappy.js | 33 + .../glob/node_modules/inflight/package.json | 36 + .../glob/node_modules/inflight/test.js | 97 + .../glob/node_modules/inherits/LICENSE | 16 + .../glob/node_modules/inherits/README.md | 42 + .../glob/node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../glob/node_modules/inherits/package.json | 35 + .../glob/node_modules/inherits/test.js | 25 + .../glob/node_modules/minimatch/LICENSE | 15 + .../glob/node_modules/minimatch/README.md | 216 + .../glob/node_modules/minimatch/browser.js | 1113 ++ .../glob/node_modules/minimatch/minimatch.js | 867 ++ .../node_modules/brace-expansion/.npmignore | 2 + .../node_modules/brace-expansion/.travis.yml | 3 + .../node_modules/brace-expansion/README.md | 121 + .../node_modules/brace-expansion/example.js | 8 + .../node_modules/brace-expansion/index.js | 191 + .../node_modules/balanced-match/.npmignore | 2 + .../node_modules/balanced-match/.travis.yml | 4 + .../node_modules/balanced-match/Makefile | 6 + .../node_modules/balanced-match/README.md | 80 + .../node_modules/balanced-match/example.js | 5 + .../node_modules/balanced-match/index.js | 38 + .../node_modules/balanced-match/package.json | 56 + .../balanced-match/test/balanced.js | 56 + .../node_modules/concat-map/.travis.yml | 4 + .../node_modules/concat-map/LICENSE | 18 + .../node_modules/concat-map/README.markdown | 62 + .../node_modules/concat-map/example/map.js | 6 + .../node_modules/concat-map/index.js | 13 + .../node_modules/concat-map/package.json | 69 + .../node_modules/concat-map/test/map.js | 39 + .../node_modules/brace-expansion/package.json | 54 + .../brace-expansion/test/bash-comparison.js | 32 + .../brace-expansion/test/bash-results.txt | 1075 ++ .../brace-expansion/test/cases.txt | 182 + .../brace-expansion/test/dollar.js | 9 + .../brace-expansion/test/empty-option.js | 10 + .../brace-expansion/test/generate.sh | 24 + .../test/negative-increment.js | 15 + .../brace-expansion/test/nested.js | 16 + .../brace-expansion/test/order.js | 10 + .../node_modules/brace-expansion/test/pad.js | 13 + .../brace-expansion/test/same-type.js | 7 + .../brace-expansion/test/sequence.js | 50 + .../glob/node_modules/minimatch/package.json | 63 + .../glob/node_modules/once/LICENSE | 15 + .../glob/node_modules/once/README.md | 51 + .../once/node_modules/wrappy/LICENSE | 15 + .../once/node_modules/wrappy/README.md | 36 + .../once/node_modules/wrappy/package.json | 36 + .../once/node_modules/wrappy/test/basic.js | 51 + .../once/node_modules/wrappy/wrappy.js | 33 + .../glob/node_modules/once/once.js | 21 + .../glob/node_modules/once/package.json | 44 + .../glob/node_modules/once/test/once.js | 23 + .../rimraf/node_modules/glob/package.json | 55 + .../rimraf/node_modules/glob/sync.js | 457 + .../node_modules/rimraf/package.json | 58 + .../node_modules/rimraf/rimraf.js | 332 + .../node_modules/semver/.npmignore | 4 + .../node_modules/semver/.travis.yml | 5 + .../node-pre-gyp/node_modules/semver/LICENSE | 15 + .../node-pre-gyp/node_modules/semver/Makefile | 24 + .../node_modules/semver/README.md | 303 + .../node_modules/semver/bin/semver | 133 + .../node_modules/semver/foot.js.txt | 6 + .../node_modules/semver/head.js.txt | 2 + .../node_modules/semver/package.json | 54 + .../node_modules/semver/semver.browser.js | 1201 ++ .../node_modules/semver/semver.browser.js.gz | Bin 0 -> 7992 bytes .../node_modules/semver/semver.js | 1205 ++ .../node_modules/semver/semver.min.js | 1 + .../node_modules/semver/semver.min.js.gz | Bin 0 -> 3790 bytes .../node_modules/semver/test/amd.js | 15 + .../node_modules/semver/test/big-numbers.js | 31 + .../node_modules/semver/test/clean.js | 29 + .../node_modules/semver/test/gtr.js | 173 + .../node_modules/semver/test/index.js | 685 + .../node_modules/semver/test/ltr.js | 181 + .../semver/test/major-minor-patch.js | 72 + .../node_modules/semver/test/no-module.js | 19 + .../node_modules/tar-pack/.npmignore | 14 + .../node_modules/tar-pack/.travis.yml | 4 + .../node_modules/tar-pack/README.md | 81 + .../node_modules/tar-pack/index.js | 246 + .../tar-pack/node_modules/.bin/rimraf | 1 + .../tar-pack/node_modules/debug/Readme.md | 115 + .../tar-pack/node_modules/debug/debug.js | 137 + .../tar-pack/node_modules/debug/index.js | 5 + .../tar-pack/node_modules/debug/lib/debug.js | 147 + .../tar-pack/node_modules/debug/package.json | 63 + .../node_modules/fstream-ignore/.npmignore | 1 + .../node_modules/fstream-ignore/LICENSE | 27 + .../node_modules/fstream-ignore/README.md | 22 + .../fstream-ignore/example/basic.js | 13 + .../node_modules/fstream-ignore/ignore.js | 275 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 35 + .../node_modules/inherits/test.js | 25 + .../node_modules/minimatch/.npmignore | 1 + .../node_modules/minimatch/LICENSE | 23 + .../node_modules/minimatch/README.md | 218 + .../node_modules/minimatch/minimatch.js | 1055 ++ .../node_modules/lru-cache/.npmignore | 1 + .../node_modules/lru-cache/CONTRIBUTORS | 14 + .../minimatch/node_modules/lru-cache/LICENSE | 15 + .../node_modules/lru-cache/README.md | 109 + .../node_modules/lru-cache/lib/lru-cache.js | 274 + .../node_modules/lru-cache/package.json | 58 + .../node_modules/lru-cache/test/basic.js | 395 + .../node_modules/lru-cache/test/foreach.js | 121 + .../lru-cache/test/memory-leak.js | 50 + .../minimatch/node_modules/sigmund/LICENSE | 15 + .../minimatch/node_modules/sigmund/README.md | 53 + .../minimatch/node_modules/sigmund/bench.js | 283 + .../node_modules/sigmund/package.json | 60 + .../minimatch/node_modules/sigmund/sigmund.js | 39 + .../node_modules/sigmund/test/basic.js | 24 + .../node_modules/minimatch/package.json | 42 + .../node_modules/minimatch/test/basic.js | 399 + .../minimatch/test/brace-expand.js | 33 + .../node_modules/minimatch/test/caching.js | 14 + .../node_modules/minimatch/test/defaults.js | 274 + .../test/extglob-ending-with-state-char.js | 8 + .../node_modules/fstream-ignore/package.json | 54 + .../node_modules/fstream-ignore/test/.ignore | 2 + .../fstream-ignore/test/.npmignore | 1 + .../fstream-ignore/test/00-setup.js | 71 + .../node_modules/fstream-ignore/test/basic.js | 28 + .../fstream-ignore/test/common.js | 40 + .../fstream-ignore/test/ignore-most.js | 41 + .../fstream-ignore/test/nested-ignores.js | 51 + .../fstream-ignore/test/unignore-child.js | 38 + .../fstream-ignore/test/zz-cleanup.js | 10 + .../tar-pack/node_modules/fstream/.npmignore | 5 + .../tar-pack/node_modules/fstream/.travis.yml | 3 + .../tar-pack/node_modules/fstream/LICENSE | 27 + .../tar-pack/node_modules/fstream/README.md | 76 + .../fstream/examples/filter-pipe.js | 131 + .../node_modules/fstream/examples/pipe.js | 115 + .../node_modules/fstream/examples/reader.js | 54 + .../fstream/examples/symlink-write.js | 24 + .../tar-pack/node_modules/fstream/fstream.js | 31 + .../node_modules/fstream/lib/abstract.js | 85 + .../node_modules/fstream/lib/collect.js | 67 + .../node_modules/fstream/lib/dir-reader.js | 251 + .../node_modules/fstream/lib/dir-writer.js | 171 + .../node_modules/fstream/lib/file-reader.js | 147 + .../node_modules/fstream/lib/file-writer.js | 104 + .../node_modules/fstream/lib/get-type.js | 32 + .../node_modules/fstream/lib/link-reader.js | 54 + .../node_modules/fstream/lib/link-writer.js | 95 + .../node_modules/fstream/lib/proxy-reader.js | 93 + .../node_modules/fstream/lib/proxy-writer.js | 109 + .../node_modules/fstream/lib/reader.js | 262 + .../node_modules/fstream/lib/socket-reader.js | 38 + .../node_modules/fstream/lib/writer.js | 389 + .../node_modules/graceful-fs/.npmignore | 1 + .../fstream/node_modules/graceful-fs/LICENSE | 15 + .../node_modules/graceful-fs/README.md | 36 + .../fstream/node_modules/graceful-fs/fs.js | 11 + .../node_modules/graceful-fs/graceful-fs.js | 158 + .../node_modules/graceful-fs/package.json | 71 + .../node_modules/graceful-fs/polyfills.js | 255 + .../node_modules/graceful-fs/test/max-open.js | 69 + .../node_modules/graceful-fs/test/open.js | 39 + .../graceful-fs/test/readdir-sort.js | 20 + .../graceful-fs/test/write-then-read.js | 47 + .../fstream/node_modules/inherits/LICENSE | 16 + .../fstream/node_modules/inherits/README.md | 42 + .../fstream/node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 35 + .../fstream/node_modules/inherits/test.js | 25 + .../node_modules/fstream/package.json | 41 + .../node_modules/graceful-fs/.npmignore | 1 + .../tar-pack/node_modules/graceful-fs/LICENSE | 27 + .../node_modules/graceful-fs/README.md | 33 + .../node_modules/graceful-fs/graceful-fs.js | 442 + .../node_modules/graceful-fs/package.json | 51 + .../node_modules/graceful-fs/test/open.js | 46 + .../node_modules/graceful-fs/test/ulimit.js | 158 + .../tar-pack/node_modules/once/LICENSE | 27 + .../tar-pack/node_modules/once/README.md | 33 + .../tar-pack/node_modules/once/once.js | 19 + .../tar-pack/node_modules/once/package.json | 56 + .../tar-pack/node_modules/once/test/once.js | 18 + .../node_modules/readable-stream/.npmignore | 5 + .../node_modules/readable-stream/LICENSE | 18 + .../node_modules/readable-stream/README.md | 15 + .../node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 982 ++ .../readable-stream/lib/_stream_transform.js | 210 + .../readable-stream/lib/_stream_writable.js | 386 + .../node_modules/core-util-is/README.md | 3 + .../node_modules/core-util-is/float.patch | 604 + .../node_modules/core-util-is/lib/util.js | 107 + .../node_modules/core-util-is/package.json | 37 + .../node_modules/core-util-is/util.js | 106 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 35 + .../node_modules/inherits/test.js | 25 + .../node_modules/isarray/README.md | 54 + .../node_modules/isarray/build/build.js | 209 + .../node_modules/isarray/component.json | 19 + .../node_modules/isarray/index.js | 3 + .../node_modules/isarray/package.json | 38 + .../node_modules/string_decoder/.npmignore | 2 + .../node_modules/string_decoder/LICENSE | 20 + .../node_modules/string_decoder/README.md | 7 + .../node_modules/string_decoder/index.js | 221 + .../node_modules/string_decoder/package.json | 34 + .../node_modules/readable-stream/package.json | 46 + .../readable-stream/passthrough.js | 1 + .../node_modules/readable-stream/readable.js | 8 + .../node_modules/readable-stream/transform.js | 1 + .../node_modules/readable-stream/writable.js | 1 + .../tar-pack/node_modules/rimraf/AUTHORS | 6 + .../tar-pack/node_modules/rimraf/LICENSE | 23 + .../tar-pack/node_modules/rimraf/README.md | 30 + .../tar-pack/node_modules/rimraf/bin.js | 33 + .../tar-pack/node_modules/rimraf/package.json | 58 + .../tar-pack/node_modules/rimraf/rimraf.js | 248 + .../tar-pack/node_modules/rimraf/test/run.sh | 16 + .../node_modules/rimraf/test/setup.sh | 47 + .../node_modules/rimraf/test/test-async.js | 5 + .../node_modules/rimraf/test/test-sync.js | 3 + .../tar-pack/node_modules/tar/.npmignore | 5 + .../tar-pack/node_modules/tar/.travis.yml | 3 + .../tar-pack/node_modules/tar/LICENCE | 25 + .../tar-pack/node_modules/tar/README.md | 48 + .../node_modules/tar/examples/extracter.js | 11 + .../node_modules/tar/examples/packer.js | 10 + .../node_modules/tar/examples/reader.js | 36 + .../node_modules/tar/lib/buffer-entry.js | 30 + .../node_modules/tar/lib/entry-writer.js | 169 + .../tar-pack/node_modules/tar/lib/entry.js | 213 + .../tar/lib/extended-header-writer.js | 191 + .../node_modules/tar/lib/extended-header.js | 140 + .../tar-pack/node_modules/tar/lib/extract.js | 78 + .../tar/lib/global-header-writer.js | 14 + .../tar-pack/node_modules/tar/lib/header.js | 385 + .../tar-pack/node_modules/tar/lib/pack.js | 231 + .../tar-pack/node_modules/tar/lib/parse.js | 271 + .../tar/node_modules/block-stream/LICENCE | 25 + .../tar/node_modules/block-stream/LICENSE | 15 + .../tar/node_modules/block-stream/README.md | 14 + .../block-stream/bench/block-stream-pause.js | 70 + .../block-stream/bench/block-stream.js | 68 + .../block-stream/bench/dropper-pause.js | 70 + .../block-stream/bench/dropper.js | 68 + .../node_modules/block-stream/block-stream.js | 209 + .../node_modules/block-stream/package.json | 55 + .../node_modules/block-stream/test/basic.js | 27 + .../block-stream/test/nopad-thorough.js | 68 + .../node_modules/block-stream/test/nopad.js | 57 + .../block-stream/test/pause-resume.js | 73 + .../block-stream/test/thorough.js | 68 + .../block-stream/test/two-stream.js | 59 + .../tar/node_modules/inherits/LICENSE | 16 + .../tar/node_modules/inherits/README.md | 42 + .../tar/node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../tar/node_modules/inherits/package.json | 35 + .../tar/node_modules/inherits/test.js | 25 + .../tar-pack/node_modules/tar/package.json | 54 + .../tar-pack/node_modules/tar/tar.js | 173 + .../tar/test/00-setup-fixtures.js | 53 + .../tar-pack/node_modules/tar/test/extract.js | 367 + .../node_modules/tar/test/fixtures.tgz | Bin 0 -> 19205 bytes .../tar-pack/node_modules/tar/test/header.js | 183 + .../tar/test/pack-no-proprietary.js | 854 ++ .../tar-pack/node_modules/tar/test/pack.js | 897 ++ .../tar-pack/node_modules/tar/test/parse.js | 359 + .../node_modules/tar/test/zz-cleanup.js | 20 + .../tar-pack/node_modules/uid-number/LICENCE | 25 + .../node_modules/uid-number/README.md | 17 + .../node_modules/uid-number/get-uid-gid.js | 24 + .../node_modules/uid-number/package.json | 50 + .../node_modules/uid-number/uid-number.js | 54 + .../node_modules/tar-pack/package.json | 58 + .../tar-pack/test/fixtures/packed-file.txt | 1 + .../tar-pack/test/fixtures/packed.tar | Bin 0 -> 3584 bytes .../tar-pack/test/fixtures/packed.tar.gz | Bin 0 -> 152 bytes .../tar-pack/test/fixtures/to-pack/bar.txt | 1 + .../tar-pack/test/fixtures/to-pack/foo.txt | 1 + .../node_modules/tar-pack/test/index.js | 67 + .../node-pre-gyp/node_modules/tar/.npmignore | 5 + .../node-pre-gyp/node_modules/tar/.travis.yml | 4 + .../node-pre-gyp/node_modules/tar/LICENSE | 12 + .../node-pre-gyp/node_modules/tar/README.md | 50 + .../node_modules/tar/examples/extracter.js | 19 + .../node_modules/tar/examples/packer.js | 24 + .../node_modules/tar/examples/reader.js | 36 + .../node_modules/tar/lib/buffer-entry.js | 30 + .../node_modules/tar/lib/entry-writer.js | 169 + .../node_modules/tar/lib/entry.js | 213 + .../tar/lib/extended-header-writer.js | 191 + .../node_modules/tar/lib/extended-header.js | 140 + .../node_modules/tar/lib/extract.js | 94 + .../tar/lib/global-header-writer.js | 14 + .../node_modules/tar/lib/header.js | 385 + .../node-pre-gyp/node_modules/tar/lib/pack.js | 236 + .../node_modules/tar/lib/parse.js | 271 + .../tar/node_modules/block-stream/LICENCE | 25 + .../tar/node_modules/block-stream/LICENSE | 15 + .../tar/node_modules/block-stream/README.md | 14 + .../block-stream/bench/block-stream-pause.js | 70 + .../block-stream/bench/block-stream.js | 68 + .../block-stream/bench/dropper-pause.js | 70 + .../block-stream/bench/dropper.js | 68 + .../node_modules/block-stream/block-stream.js | 209 + .../node_modules/block-stream/package.json | 55 + .../node_modules/block-stream/test/basic.js | 27 + .../block-stream/test/nopad-thorough.js | 68 + .../node_modules/block-stream/test/nopad.js | 57 + .../block-stream/test/pause-resume.js | 73 + .../block-stream/test/thorough.js | 68 + .../block-stream/test/two-stream.js | 59 + .../tar/node_modules/fstream/.npmignore | 5 + .../tar/node_modules/fstream/.travis.yml | 9 + .../tar/node_modules/fstream/LICENSE | 15 + .../tar/node_modules/fstream/README.md | 76 + .../fstream/examples/filter-pipe.js | 133 + .../tar/node_modules/fstream/examples/pipe.js | 117 + .../node_modules/fstream/examples/reader.js | 68 + .../fstream/examples/symlink-write.js | 25 + .../tar/node_modules/fstream/fstream.js | 35 + .../tar/node_modules/fstream/lib/abstract.js | 85 + .../tar/node_modules/fstream/lib/collect.js | 68 + .../node_modules/fstream/lib/dir-reader.js | 252 + .../node_modules/fstream/lib/dir-writer.js | 174 + .../node_modules/fstream/lib/file-reader.js | 150 + .../node_modules/fstream/lib/file-writer.js | 107 + .../tar/node_modules/fstream/lib/get-type.js | 33 + .../node_modules/fstream/lib/link-reader.js | 53 + .../node_modules/fstream/lib/link-writer.js | 95 + .../node_modules/fstream/lib/proxy-reader.js | 95 + .../node_modules/fstream/lib/proxy-writer.js | 111 + .../tar/node_modules/fstream/lib/reader.js | 255 + .../node_modules/fstream/lib/socket-reader.js | 36 + .../tar/node_modules/fstream/lib/writer.js | 390 + .../node_modules/graceful-fs/.npmignore | 1 + .../fstream/node_modules/graceful-fs/LICENSE | 15 + .../node_modules/graceful-fs/README.md | 36 + .../fstream/node_modules/graceful-fs/fs.js | 11 + .../node_modules/graceful-fs/graceful-fs.js | 158 + .../node_modules/graceful-fs/package.json | 71 + .../node_modules/graceful-fs/polyfills.js | 255 + .../node_modules/graceful-fs/test/max-open.js | 69 + .../node_modules/graceful-fs/test/open.js | 39 + .../graceful-fs/test/readdir-sort.js | 20 + .../graceful-fs/test/write-then-read.js | 47 + .../tar/node_modules/fstream/package.json | 42 + .../tar/node_modules/inherits/LICENSE | 16 + .../tar/node_modules/inherits/README.md | 42 + .../tar/node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../tar/node_modules/inherits/package.json | 35 + .../tar/node_modules/inherits/test.js | 25 + .../node_modules/tar/package.json | 61 + .../node-pre-gyp/node_modules/tar/tar.js | 173 + .../tar/test/00-setup-fixtures.js | 53 + .../tar/test/cb-never-called-1.0.1.tgz | Bin 0 -> 4096 bytes .../tar/test/dir-normalization.js | 177 + .../tar/test/dir-normalization.tar | Bin 0 -> 4608 bytes .../node_modules/tar/test/error-on-broken.js | 33 + .../node_modules/tar/test/extract-move.js | 132 + .../node_modules/tar/test/extract.js | 367 + .../node_modules/tar/test/fixtures.tgz | Bin 0 -> 19352 bytes .../node_modules/tar/test/header.js | 183 + .../tar/test/pack-no-proprietary.js | 886 ++ .../node_modules/tar/test/pack.js | 952 ++ .../node_modules/tar/test/parse.js | 359 + .../node_modules/tar/test/zz-cleanup.js | 20 + .../node_modules/node-pre-gyp/package.json | 80 + .../node-pre-gyp/scripts/abi_crosswalk.js | 160 + .../node-pre-gyp/scripts/clear_bucket.js | 35 + .../node-pre-gyp/scripts/latest-by-abi.js | 27 + .../node-pre-gyp/scripts/test-node-webkit.sh | 54 + .../node-pre-gyp/scripts/test.bat | 22 + .../node_modules/node-pre-gyp/scripts/test.sh | 150 + .../node-pre-gyp/test/app1/.npmignore | 5 + .../node-pre-gyp/test/app1/README.md | 3 + .../node-pre-gyp/test/app1/app1.cc | 38 + .../node-pre-gyp/test/app1/binding.gyp | 19 + .../node-pre-gyp/test/app1/index.js | 7 + .../node-pre-gyp/test/app1/package.json | 19 + .../node-pre-gyp/test/app2/.npmignore | 5 + .../node-pre-gyp/test/app2/README.md | 3 + .../node-pre-gyp/test/app2/app2.cc | 42 + .../node-pre-gyp/test/app2/binding.gyp | 22 + .../node-pre-gyp/test/app2/include/foo.hpp | 6 + .../node-pre-gyp/test/app2/index.js | 1 + .../node-pre-gyp/test/app2/lib/index.js | 14 + .../node-pre-gyp/test/app2/package.json | 21 + .../node-pre-gyp/test/app3/.npmignore | 5 + .../node-pre-gyp/test/app3/README.md | 7 + .../node-pre-gyp/test/app3/app3.cc | 44 + .../node-pre-gyp/test/app3/binding.gyp | 22 + .../node-pre-gyp/test/app3/deps/README.md | 4 + .../test/app3/deps/include/mylib/interface.h | 19 + .../node-pre-gyp/test/app3/deps/mylib.gyp | 18 + .../test/app3/deps/src/implementation.cc | 16 + .../node-pre-gyp/test/app3/index.js | 7 + .../node-pre-gyp/test/app3/package.json | 21 + .../node-pre-gyp/test/app4/.npmignore | 5 + .../node-pre-gyp/test/app4/README.md | 7 + .../node-pre-gyp/test/app4/app4.cpp | 44 + .../node-pre-gyp/test/app4/binding.gyp | 42 + .../node-pre-gyp/test/app4/deps/README.md | 4 + .../test/app4/deps/include/mylib/interface.h | 29 + .../node-pre-gyp/test/app4/deps/mylib.gyp | 21 + .../test/app4/deps/src/implementation.cc | 16 + .../node-pre-gyp/test/app4/index.js | 7 + .../node-pre-gyp/test/app4/package.json | 21 + .../node-pre-gyp/test/app5/.npmignore | 5 + .../node-pre-gyp/test/app5/README.md | 5 + .../node-pre-gyp/test/app5/index.js | 6 + .../node-pre-gyp/test/app5/package.json | 15 + .../node-pre-gyp/test/app6/.npmignore | 5 + .../node-pre-gyp/test/app6/README.md | 3 + .../node-pre-gyp/test/app6/index.js | 6 + .../node-pre-gyp/test/app6/package.json | 12 + .../node-pre-gyp/test/build.test.js | 426 + .../node_modules/node-pre-gyp/test/mocha.opts | 3 + .../node-pre-gyp/test/s3_setup.test.js | 22 + .../node-pre-gyp/test/versioning.test.js | 67 + .../bson/node_modules/bson-ext/package.json | 79 + .../mongoose/node_modules/bson/package.json | 80 + .../mongoose/node_modules/bson/tools/gleak.js | 21 + .../node_modules/hooks-fixed/.npmignore | 2 + .../node_modules/hooks-fixed/Makefile | 9 + .../node_modules/hooks-fixed/README.md | 369 + .../node_modules/hooks-fixed/hooks.alt.js | 134 + .../node_modules/hooks-fixed/hooks.js | 173 + .../node_modules/hooks-fixed/package.json | 66 + .../mongoose/node_modules/hooks-fixed/test.js | 741 + .../mongoose/node_modules/kareem/.npmignore | 28 + .../mongoose/node_modules/kareem/.travis.yml | 7 + .../mongoose/node_modules/kareem/LICENSE | 202 + .../mongoose/node_modules/kareem/Makefile | 5 + .../mongoose/node_modules/kareem/README.md | 379 + .../mongoose/node_modules/kareem/docs.js | 37 + .../mongoose/node_modules/kareem/gulpfile.js | 18 + .../mongoose/node_modules/kareem/index.js | 229 + .../mongoose/node_modules/kareem/package.json | 60 + .../node_modules/kareem/test/examples.test.js | 339 + .../node_modules/kareem/test/post.test.js | 46 + .../node_modules/kareem/test/pre.test.js | 226 + .../node_modules/kareem/test/wrap.test.js | 277 + .../mongoose/node_modules/mongodb/.travis.yml | 10 + .../mongoose/node_modules/mongodb/HISTORY.md | 1142 ++ .../mongoose/node_modules/mongodb/LICENSE | 201 + .../mongoose/node_modules/mongodb/Makefile | 14 + .../mongoose/node_modules/mongodb/README.md | 322 + .../mongoose/node_modules/mongodb/conf.json | 65 + .../mongoose/node_modules/mongodb/index.js | 39 + .../node_modules/mongodb/lib/admin.js | 347 + .../mongodb/lib/aggregation_cursor.js | 396 + .../node_modules/mongodb/lib/bulk/common.js | 393 + .../node_modules/mongodb/lib/bulk/ordered.js | 470 + .../mongodb/lib/bulk/unordered.js | 482 + .../node_modules/mongodb/lib/collection.js | 2097 +++ .../mongodb/lib/command_cursor.js | 282 + .../node_modules/mongodb/lib/cursor.js | 876 ++ .../mongoose/node_modules/mongodb/lib/db.js | 1400 ++ .../node_modules/mongodb/lib/gridfs/chunk.js | 236 + .../mongodb/lib/gridfs/grid_store.js | 1603 ++ .../node_modules/mongodb/lib/mongo_client.js | 413 + .../node_modules/mongodb/lib/mongos.js | 454 + .../mongodb/lib/read_preference.js | 104 + .../node_modules/mongodb/lib/replset.js | 527 + .../node_modules/mongodb/lib/server.js | 408 + .../node_modules/mongodb/lib/topology_base.js | 140 + .../node_modules/mongodb/lib/url_parser.js | 281 + .../node_modules/mongodb/lib/utils.js | 233 + .../node_modules/mongodb-core/.travis.yml | 11 + .../node_modules/mongodb-core/HISTORY.md | 174 + .../mongodb/node_modules/mongodb-core/LICENSE | 201 + .../node_modules/mongodb-core/Makefile | 14 + .../node_modules/mongodb-core/README.md | 225 + .../node_modules/mongodb-core/TESTING.md | 18 + .../node_modules/mongodb-core/conf.json | 60 + .../node_modules/mongodb-core/index.js | 17 + .../mongodb-core/lib/auth/gssapi.js | 244 + .../mongodb-core/lib/auth/mongocr.js | 160 + .../mongodb-core/lib/auth/plain.js | 150 + .../mongodb-core/lib/auth/scram.js | 316 + .../mongodb-core/lib/auth/sspi.js | 234 + .../mongodb-core/lib/auth/x509.js | 145 + .../mongodb-core/lib/connection/commands.js | 482 + .../mongodb-core/lib/connection/connection.js | 454 + .../mongodb-core/lib/connection/logger.js | 193 + .../mongodb-core/lib/connection/pool.js | 266 + .../mongodb-core/lib/connection/utils.js | 77 + .../node_modules/mongodb-core/lib/cursor.js | 617 + .../node_modules/mongodb-core/lib/error.js | 44 + .../mongodb-core/lib/tools/smoke_plugin.js | 59 + .../lib/topologies/command_result.js | 37 + .../mongodb-core/lib/topologies/mongos.js | 975 ++ .../lib/topologies/read_preference.js | 106 + .../mongodb-core/lib/topologies/replset.js | 1303 ++ .../lib/topologies/replset_state.js | 472 + .../mongodb-core/lib/topologies/server.js | 1252 ++ .../mongodb-core/lib/topologies/session.js | 93 + .../lib/topologies/strategies/ping.js | 276 + .../lib/wireprotocol/2_4_support.js | 514 + .../lib/wireprotocol/2_6_support.js | 249 + .../mongodb-core/lib/wireprotocol/commands.js | 335 + .../node_modules/kerberos/LICENSE | 201 + .../node_modules/kerberos/README.md | 4 + .../node_modules/kerberos/binding.gyp | 45 + .../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 | 42 + .../kerberos/lib/kerberos_context.o.d | 40 + .../obj.target/kerberos/lib/kerberosgss.o.d | 6 + .../obj.target/kerberos/lib/worker.o.d | 38 + .../kerberos/build/Release/kerberos.node | Bin 0 -> 53020 bytes .../kerberos/build/Release/linker.lock | 0 .../Release/obj.target/kerberos/lib/base64.o | Bin 0 -> 6296 bytes .../obj.target/kerberos/lib/kerberos.o | Bin 0 -> 217144 bytes .../kerberos/lib/kerberos_context.o | Bin 0 -> 132104 bytes .../obj.target/kerberos/lib/kerberosgss.o | Bin 0 -> 17540 bytes .../Release/obj.target/kerberos/lib/worker.o | Bin 0 -> 80248 bytes .../kerberos/build/binding.Makefile | 6 + .../node_modules/kerberos/build/config.gypi | 130 + .../node_modules/kerberos/build/gyp-mac-tool | 512 + .../kerberos/build/kerberos.target.mk | 172 + .../node_modules/kerberos/builderror.log | 0 .../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 | 592 + .../node_modules/kerberos/lib/kerberos.h | 47 + .../node_modules/kerberos/lib/kerberos.js | 91 + .../kerberos/lib/kerberos_context.cc | 77 + .../kerberos/lib/kerberos_context.h | 48 + .../node_modules/kerberos/lib/kerberosgss.c | 693 + .../node_modules/kerberos/lib/kerberosgss.h | 70 + .../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 | 53 + .../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 | 106 + .../lib/win32/wrappers/security_buffer.h | 48 + .../lib/win32/wrappers/security_buffer.js | 12 + .../wrappers/security_buffer_descriptor.cc | 185 + .../wrappers/security_buffer_descriptor.h | 46 + .../wrappers/security_buffer_descriptor.js | 3 + .../lib/win32/wrappers/security_context.cc | 869 ++ .../lib/win32/wrappers/security_context.h | 74 + .../lib/win32/wrappers/security_context.js | 3 + .../win32/wrappers/security_credentials.cc | 351 + .../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 | 294 + .../kerberos/node_modules/nan/LICENSE.md | 13 + .../kerberos/node_modules/nan/README.md | 1402 ++ .../kerberos/node_modules/nan/appveyor.yml | 38 + .../kerberos/node_modules/nan/include_dirs.js | 1 + .../kerberos/node_modules/nan/nan.h | 2322 +++ .../nan/nan_implementation_12_inl.h | 261 + .../nan/nan_implementation_pre_12_inl.h | 267 + .../kerberos/node_modules/nan/nan_new.h | 328 + .../node_modules/nan/nan_string_bytes.h | 312 + .../kerberos/node_modules/nan/package.json | 90 + .../node_modules/kerberos/package.json | 56 + .../kerberos/test/kerberos_tests.js | 34 + .../kerberos/test/kerberos_win32_test.js | 19 + .../win32/security_buffer_descriptor_tests.js | 41 + .../test/win32/security_buffer_tests.js | 22 + .../test/win32/security_credentials_tests.js | 55 + .../node_modules/mongodb-core/package.json | 65 + .../node_modules/readable-stream/.npmignore | 5 + .../node_modules/readable-stream/LICENSE | 27 + .../node_modules/readable-stream/README.md | 15 + .../node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 982 ++ .../readable-stream/lib/_stream_transform.js | 210 + .../readable-stream/lib/_stream_writable.js | 386 + .../node_modules/core-util-is/README.md | 3 + .../node_modules/core-util-is/float.patch | 604 + .../node_modules/core-util-is/lib/util.js | 107 + .../node_modules/core-util-is/package.json | 37 + .../node_modules/core-util-is/util.js | 106 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 35 + .../node_modules/inherits/test.js | 25 + .../node_modules/isarray/README.md | 54 + .../node_modules/isarray/build/build.js | 209 + .../node_modules/isarray/component.json | 19 + .../node_modules/isarray/index.js | 3 + .../node_modules/isarray/package.json | 38 + .../node_modules/string_decoder/.npmignore | 2 + .../node_modules/string_decoder/LICENSE | 20 + .../node_modules/string_decoder/README.md | 7 + .../node_modules/string_decoder/index.js | 221 + .../node_modules/string_decoder/package.json | 34 + .../node_modules/readable-stream/package.json | 69 + .../readable-stream/passthrough.js | 1 + .../node_modules/readable-stream/readable.js | 6 + .../node_modules/readable-stream/transform.js | 1 + .../node_modules/readable-stream/writable.js | 1 + .../node_modules/mongodb/package.json | 64 + .../mongoose/node_modules/mongodb/t.js | 28 + .../mongoose/node_modules/mongodb/t1.js | 59 + .../mongoose/node_modules/mongodb/wercker.yml | 19 + .../mongoose/node_modules/mpath/.npmignore | 2 + .../mongoose/node_modules/mpath/.travis.yml | 4 + .../mongoose/node_modules/mpath/History.md | 16 + .../mongoose/node_modules/mpath/LICENSE | 22 + .../mongoose/node_modules/mpath/Makefile | 5 + .../mongoose/node_modules/mpath/README.md | 278 + .../mongoose/node_modules/mpath/index.js | 1 + .../mongoose/node_modules/mpath/lib/index.js | 183 + .../mongoose/node_modules/mpath/package.json | 52 + .../mongoose/node_modules/mpath/test/index.js | 1630 ++ .../mongoose/node_modules/mpromise/.npmignore | 4 + .../node_modules/mpromise/.travis.yml | 5 + .../mongoose/node_modules/mpromise/History.md | 74 + .../mongoose/node_modules/mpromise/LICENSE | 22 + .../mongoose/node_modules/mpromise/README.md | 224 + .../node_modules/mpromise/lib/promise.js | 440 + .../node_modules/mpromise/package.json | 61 + .../mpromise/test/promise.domain.test.js | 28 + .../mpromise/test/promise.test.js | 554 + .../mpromise/test/promises.Aplus.js | 15 + .../mongoose/node_modules/mquery/.npmignore | 3 + .../mongoose/node_modules/mquery/.travis.yml | 7 + .../mongoose/node_modules/mquery/History.md | 215 + .../mongoose/node_modules/mquery/LICENSE | 22 + .../mongoose/node_modules/mquery/Makefile | 22 + .../mongoose/node_modules/mquery/README.md | 1220 ++ .../mquery/lib/collection/collection.js | 42 + .../mquery/lib/collection/index.js | 13 + .../mquery/lib/collection/node.js | 100 + .../mongoose/node_modules/mquery/lib/env.js | 22 + .../node_modules/mquery/lib/mquery.js | 2608 ++++ .../node_modules/mquery/lib/permissions.js | 90 + .../mongoose/node_modules/mquery/lib/utils.js | 331 + .../mquery/node_modules/bluebird/LICENSE | 21 + .../mquery/node_modules/bluebird/README.md | 676 + .../mquery/node_modules/bluebird/changelog.md | 1538 ++ .../bluebird/js/browser/bluebird.js | 4693 ++++++ .../bluebird/js/browser/bluebird.min.js | 31 + .../node_modules/bluebird/js/main/any.js | 21 + .../node_modules/bluebird/js/main/assert.js | 55 + .../node_modules/bluebird/js/main/async.js | 106 + .../node_modules/bluebird/js/main/bind.js | 87 + .../node_modules/bluebird/js/main/bluebird.js | 11 + .../node_modules/bluebird/js/main/call_get.js | 123 + .../node_modules/bluebird/js/main/cancel.js | 47 + .../bluebird/js/main/captured_trace.js | 492 + .../bluebird/js/main/catch_filter.js | 66 + .../node_modules/bluebird/js/main/context.js | 38 + .../bluebird/js/main/debuggability.js | 139 + .../bluebird/js/main/direct_resolve.js | 54 + .../node_modules/bluebird/js/main/each.js | 12 + .../node_modules/bluebird/js/main/errors.js | 111 + .../node_modules/bluebird/js/main/es5.js | 80 + .../node_modules/bluebird/js/main/filter.js | 12 + .../node_modules/bluebird/js/main/finally.js | 99 + .../bluebird/js/main/generators.js | 136 + .../node_modules/bluebird/js/main/join.js | 107 + .../node_modules/bluebird/js/main/map.js | 129 + .../node_modules/bluebird/js/main/method.js | 44 + .../node_modules/bluebird/js/main/nodeify.js | 57 + .../node_modules/bluebird/js/main/progress.js | 76 + .../node_modules/bluebird/js/main/promise.js | 715 + .../bluebird/js/main/promise_array.js | 142 + .../bluebird/js/main/promise_resolver.js | 123 + .../bluebird/js/main/promisify.js | 291 + .../node_modules/bluebird/js/main/props.js | 79 + .../node_modules/bluebird/js/main/queue.js | 90 + .../node_modules/bluebird/js/main/race.js | 47 + .../node_modules/bluebird/js/main/reduce.js | 142 + .../node_modules/bluebird/js/main/schedule.js | 27 + .../node_modules/bluebird/js/main/settle.js | 40 + .../node_modules/bluebird/js/main/some.js | 125 + .../js/main/synchronous_inspection.js | 94 + .../bluebird/js/main/thenables.js | 89 + .../node_modules/bluebird/js/main/timers.js | 58 + .../node_modules/bluebird/js/main/using.js | 202 + .../node_modules/bluebird/js/main/util.js | 276 + .../mquery/node_modules/bluebird/package.json | 97 + .../mquery/node_modules/debug/Readme.md | 115 + .../mquery/node_modules/debug/debug.js | 137 + .../mquery/node_modules/debug/index.js | 5 + .../mquery/node_modules/debug/lib/debug.js | 147 + .../mquery/node_modules/debug/package.json | 62 + .../mongoose/node_modules/mquery/package.json | 67 + .../mquery/test/collection/browser.js | 0 .../mquery/test/collection/mongo.js | 0 .../mquery/test/collection/node.js | 29 + .../mongoose/node_modules/mquery/test/env.js | 20 + .../node_modules/mquery/test/index.js | 2858 ++++ .../node_modules/mquery/test/utils.test.js | 143 + .../mongoose/node_modules/ms/.npmignore | 1 + .../mongoose/node_modules/ms/Makefile | 8 + .../mongoose/node_modules/ms/README.md | 65 + node_modules/mongoose/node_modules/ms/ms.js | 35 + .../mongoose/node_modules/ms/package.json | 39 + .../mongoose/node_modules/ms/test/index.html | 19 + .../node_modules/ms/test/support/jquery.js | 9266 ++++++++++++ .../mongoose/node_modules/ms/test/test.js | 61 + .../mongoose/node_modules/muri/.npmignore | 2 + .../mongoose/node_modules/muri/.travis.yml | 4 + .../mongoose/node_modules/muri/History.md | 52 + .../mongoose/node_modules/muri/LICENSE | 22 + .../mongoose/node_modules/muri/Makefile | 5 + .../mongoose/node_modules/muri/README.md | 46 + .../mongoose/node_modules/muri/index.js | 1 + .../mongoose/node_modules/muri/lib/index.js | 235 + .../mongoose/node_modules/muri/package.json | 51 + .../mongoose/node_modules/muri/strict.js | 3 + .../mongoose/node_modules/muri/test/index.js | 312 + .../node_modules/regexp-clone/.npmignore | 2 + .../node_modules/regexp-clone/.travis.yml | 5 + .../node_modules/regexp-clone/History.md | 5 + .../node_modules/regexp-clone/LICENSE | 22 + .../node_modules/regexp-clone/Makefile | 5 + .../node_modules/regexp-clone/README.md | 18 + .../node_modules/regexp-clone/index.js | 20 + .../node_modules/regexp-clone/package.json | 51 + .../node_modules/regexp-clone/test/index.js | 112 + .../mongoose/node_modules/sliced/.npmignore | 2 + .../mongoose/node_modules/sliced/.travis.yml | 4 + .../mongoose/node_modules/sliced/History.md | 30 + .../mongoose/node_modules/sliced/LICENSE | 22 + .../mongoose/node_modules/sliced/Makefile | 5 + .../mongoose/node_modules/sliced/README.md | 62 + .../mongoose/node_modules/sliced/bench.js | 95 + .../node_modules/sliced/component.json | 14 + .../mongoose/node_modules/sliced/index.js | 1 + .../node_modules/sliced/lib/sliced.js | 33 + .../mongoose/node_modules/sliced/package.json | 52 + .../node_modules/sliced/test/index.js | 80 + node_modules/mongoose/package.json | 123 + node_modules/mongoose/release-items.md | 32 + node_modules/mongoose/static.js | 26 + node_modules/mongoose/website.js | 72 + node_modules/path/LICENSE | 18 + node_modules/path/README.md | 15 + node_modules/path/package.json | 54 + node_modules/path/path.js | 522 + package.json | 36 + 2207 files changed, 310707 insertions(+) create mode 100644 .jshintrc create mode 100644 LICENSE create mode 100644 README.md create mode 100644 index.js create mode 100644 node_modules/async/.jshintrc create mode 100644 node_modules/async/.travis.yml create mode 100644 node_modules/async/CHANGELOG.md create mode 100644 node_modules/async/LICENSE create mode 100644 node_modules/async/README.md create mode 100644 node_modules/async/bower.json create mode 100644 node_modules/async/component.json create mode 100644 node_modules/async/coverage/base.css create mode 100644 node_modules/async/coverage/index.html create mode 100644 node_modules/async/coverage/lcov-report/base.css create mode 100644 node_modules/async/coverage/lcov-report/index.html create mode 100644 node_modules/async/coverage/lcov-report/lib/async.js.html create mode 100644 node_modules/async/coverage/lcov-report/lib/index.html create mode 100644 node_modules/async/coverage/lcov-report/prettify.css create mode 100644 node_modules/async/coverage/lcov-report/prettify.js create mode 100644 node_modules/async/coverage/lcov-report/sort-arrow-sprite.png create mode 100644 node_modules/async/coverage/lcov-report/sorter.js create mode 100644 node_modules/async/coverage/lcov.info create mode 100644 node_modules/async/coverage/lib/async.js.html create mode 100644 node_modules/async/coverage/lib/index.html create mode 100644 node_modules/async/coverage/prettify.css create mode 100644 node_modules/async/coverage/prettify.js create mode 100644 node_modules/async/coverage/sort-arrow-sprite.png create mode 100644 node_modules/async/coverage/sorter.js create mode 100644 node_modules/async/lib/async.js create mode 100644 node_modules/async/nyc_output/5074.json create mode 100644 node_modules/async/package.json create mode 100755 node_modules/async/support/sync-package-managers.js create mode 100644 node_modules/chalk/index.js create mode 100644 node_modules/chalk/license create mode 120000 node_modules/chalk/node_modules/.bin/has-ansi create mode 120000 node_modules/chalk/node_modules/.bin/strip-ansi create mode 120000 node_modules/chalk/node_modules/.bin/supports-color create mode 100644 node_modules/chalk/node_modules/ansi-styles/index.js create mode 100644 node_modules/chalk/node_modules/ansi-styles/license create mode 100644 node_modules/chalk/node_modules/ansi-styles/package.json create mode 100644 node_modules/chalk/node_modules/ansi-styles/readme.md create mode 100644 node_modules/chalk/node_modules/escape-string-regexp/index.js create mode 100644 node_modules/chalk/node_modules/escape-string-regexp/license create mode 100644 node_modules/chalk/node_modules/escape-string-regexp/package.json create mode 100644 node_modules/chalk/node_modules/escape-string-regexp/readme.md create mode 100755 node_modules/chalk/node_modules/has-ansi/cli.js create mode 100644 node_modules/chalk/node_modules/has-ansi/index.js create mode 100644 node_modules/chalk/node_modules/has-ansi/license create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/index.js create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/license create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/package.json create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/ansi-regex/readme.md create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/index.js create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/package.json create mode 100644 node_modules/chalk/node_modules/has-ansi/node_modules/get-stdin/readme.md create mode 100644 node_modules/chalk/node_modules/has-ansi/package.json create mode 100644 node_modules/chalk/node_modules/has-ansi/readme.md create mode 100755 node_modules/chalk/node_modules/strip-ansi/cli.js create mode 100644 node_modules/chalk/node_modules/strip-ansi/index.js create mode 100644 node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/index.js create mode 100644 node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/license create mode 100644 node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/package.json create mode 100644 node_modules/chalk/node_modules/strip-ansi/node_modules/ansi-regex/readme.md create mode 100644 node_modules/chalk/node_modules/strip-ansi/package.json create mode 100644 node_modules/chalk/node_modules/strip-ansi/readme.md create mode 100755 node_modules/chalk/node_modules/supports-color/cli.js create mode 100644 node_modules/chalk/node_modules/supports-color/index.js create mode 100644 node_modules/chalk/node_modules/supports-color/license create mode 100644 node_modules/chalk/node_modules/supports-color/package.json create mode 100644 node_modules/chalk/node_modules/supports-color/readme.md create mode 100644 node_modules/chalk/package.json create mode 100644 node_modules/chalk/readme.md create mode 100644 node_modules/lodash/LICENSE.txt create mode 100644 node_modules/lodash/README.md create mode 100644 node_modules/lodash/array.js create mode 100644 node_modules/lodash/array/chunk.js create mode 100644 node_modules/lodash/array/compact.js create mode 100644 node_modules/lodash/array/difference.js create mode 100644 node_modules/lodash/array/drop.js create mode 100644 node_modules/lodash/array/dropRight.js create mode 100644 node_modules/lodash/array/dropRightWhile.js create mode 100644 node_modules/lodash/array/dropWhile.js create mode 100644 node_modules/lodash/array/fill.js create mode 100644 node_modules/lodash/array/findIndex.js create mode 100644 node_modules/lodash/array/findLastIndex.js create mode 100644 node_modules/lodash/array/first.js create mode 100644 node_modules/lodash/array/flatten.js create mode 100644 node_modules/lodash/array/flattenDeep.js create mode 100644 node_modules/lodash/array/head.js create mode 100644 node_modules/lodash/array/indexOf.js create mode 100644 node_modules/lodash/array/initial.js create mode 100644 node_modules/lodash/array/intersection.js create mode 100644 node_modules/lodash/array/last.js create mode 100644 node_modules/lodash/array/lastIndexOf.js create mode 100644 node_modules/lodash/array/object.js create mode 100644 node_modules/lodash/array/pull.js create mode 100644 node_modules/lodash/array/pullAt.js create mode 100644 node_modules/lodash/array/remove.js create mode 100644 node_modules/lodash/array/rest.js create mode 100644 node_modules/lodash/array/slice.js create mode 100644 node_modules/lodash/array/sortedIndex.js create mode 100644 node_modules/lodash/array/sortedLastIndex.js create mode 100644 node_modules/lodash/array/tail.js create mode 100644 node_modules/lodash/array/take.js create mode 100644 node_modules/lodash/array/takeRight.js create mode 100644 node_modules/lodash/array/takeRightWhile.js create mode 100644 node_modules/lodash/array/takeWhile.js create mode 100644 node_modules/lodash/array/union.js create mode 100644 node_modules/lodash/array/uniq.js create mode 100644 node_modules/lodash/array/unique.js create mode 100644 node_modules/lodash/array/unzip.js create mode 100644 node_modules/lodash/array/unzipWith.js create mode 100644 node_modules/lodash/array/without.js create mode 100644 node_modules/lodash/array/xor.js create mode 100644 node_modules/lodash/array/zip.js create mode 100644 node_modules/lodash/array/zipObject.js create mode 100644 node_modules/lodash/array/zipWith.js create mode 100644 node_modules/lodash/chain.js create mode 100644 node_modules/lodash/chain/chain.js create mode 100644 node_modules/lodash/chain/commit.js create mode 100644 node_modules/lodash/chain/lodash.js create mode 100644 node_modules/lodash/chain/plant.js create mode 100644 node_modules/lodash/chain/reverse.js create mode 100644 node_modules/lodash/chain/run.js create mode 100644 node_modules/lodash/chain/tap.js create mode 100644 node_modules/lodash/chain/thru.js create mode 100644 node_modules/lodash/chain/toJSON.js create mode 100644 node_modules/lodash/chain/toString.js create mode 100644 node_modules/lodash/chain/value.js create mode 100644 node_modules/lodash/chain/valueOf.js create mode 100644 node_modules/lodash/chain/wrapperChain.js create mode 100644 node_modules/lodash/chain/wrapperCommit.js create mode 100644 node_modules/lodash/chain/wrapperPlant.js create mode 100644 node_modules/lodash/chain/wrapperReverse.js create mode 100644 node_modules/lodash/chain/wrapperToString.js create mode 100644 node_modules/lodash/chain/wrapperValue.js create mode 100644 node_modules/lodash/collection.js create mode 100644 node_modules/lodash/collection/all.js create mode 100644 node_modules/lodash/collection/any.js create mode 100644 node_modules/lodash/collection/at.js create mode 100644 node_modules/lodash/collection/collect.js create mode 100644 node_modules/lodash/collection/contains.js create mode 100644 node_modules/lodash/collection/countBy.js create mode 100644 node_modules/lodash/collection/detect.js create mode 100644 node_modules/lodash/collection/each.js create mode 100644 node_modules/lodash/collection/eachRight.js create mode 100644 node_modules/lodash/collection/every.js create mode 100644 node_modules/lodash/collection/filter.js create mode 100644 node_modules/lodash/collection/find.js create mode 100644 node_modules/lodash/collection/findLast.js create mode 100644 node_modules/lodash/collection/findWhere.js create mode 100644 node_modules/lodash/collection/foldl.js create mode 100644 node_modules/lodash/collection/foldr.js create mode 100644 node_modules/lodash/collection/forEach.js create mode 100644 node_modules/lodash/collection/forEachRight.js create mode 100644 node_modules/lodash/collection/groupBy.js create mode 100644 node_modules/lodash/collection/include.js create mode 100644 node_modules/lodash/collection/includes.js create mode 100644 node_modules/lodash/collection/indexBy.js create mode 100644 node_modules/lodash/collection/inject.js create mode 100644 node_modules/lodash/collection/invoke.js create mode 100644 node_modules/lodash/collection/map.js create mode 100644 node_modules/lodash/collection/max.js create mode 100644 node_modules/lodash/collection/min.js create mode 100644 node_modules/lodash/collection/partition.js create mode 100644 node_modules/lodash/collection/pluck.js create mode 100644 node_modules/lodash/collection/reduce.js create mode 100644 node_modules/lodash/collection/reduceRight.js create mode 100644 node_modules/lodash/collection/reject.js create mode 100644 node_modules/lodash/collection/sample.js create mode 100644 node_modules/lodash/collection/select.js create mode 100644 node_modules/lodash/collection/shuffle.js create mode 100644 node_modules/lodash/collection/size.js create mode 100644 node_modules/lodash/collection/some.js create mode 100644 node_modules/lodash/collection/sortBy.js create mode 100644 node_modules/lodash/collection/sortByAll.js create mode 100644 node_modules/lodash/collection/sortByOrder.js create mode 100644 node_modules/lodash/collection/sum.js create mode 100644 node_modules/lodash/collection/where.js create mode 100644 node_modules/lodash/date.js create mode 100644 node_modules/lodash/date/now.js create mode 100644 node_modules/lodash/function.js create mode 100644 node_modules/lodash/function/after.js create mode 100644 node_modules/lodash/function/ary.js create mode 100644 node_modules/lodash/function/backflow.js create mode 100644 node_modules/lodash/function/before.js create mode 100644 node_modules/lodash/function/bind.js create mode 100644 node_modules/lodash/function/bindAll.js create mode 100644 node_modules/lodash/function/bindKey.js create mode 100644 node_modules/lodash/function/compose.js create mode 100644 node_modules/lodash/function/curry.js create mode 100644 node_modules/lodash/function/curryRight.js create mode 100644 node_modules/lodash/function/debounce.js create mode 100644 node_modules/lodash/function/defer.js create mode 100644 node_modules/lodash/function/delay.js create mode 100644 node_modules/lodash/function/flow.js create mode 100644 node_modules/lodash/function/flowRight.js create mode 100644 node_modules/lodash/function/memoize.js create mode 100644 node_modules/lodash/function/negate.js create mode 100644 node_modules/lodash/function/once.js create mode 100644 node_modules/lodash/function/partial.js create mode 100644 node_modules/lodash/function/partialRight.js create mode 100644 node_modules/lodash/function/rearg.js create mode 100644 node_modules/lodash/function/restParam.js create mode 100644 node_modules/lodash/function/spread.js create mode 100644 node_modules/lodash/function/throttle.js create mode 100644 node_modules/lodash/function/wrap.js create mode 100644 node_modules/lodash/index.js create mode 100644 node_modules/lodash/internal/LazyWrapper.js create mode 100644 node_modules/lodash/internal/LodashWrapper.js create mode 100644 node_modules/lodash/internal/MapCache.js create mode 100644 node_modules/lodash/internal/SetCache.js create mode 100644 node_modules/lodash/internal/arrayCopy.js create mode 100644 node_modules/lodash/internal/arrayEach.js create mode 100644 node_modules/lodash/internal/arrayEachRight.js create mode 100644 node_modules/lodash/internal/arrayEvery.js create mode 100644 node_modules/lodash/internal/arrayExtremum.js create mode 100644 node_modules/lodash/internal/arrayFilter.js create mode 100644 node_modules/lodash/internal/arrayMap.js create mode 100644 node_modules/lodash/internal/arrayReduce.js create mode 100644 node_modules/lodash/internal/arrayReduceRight.js create mode 100644 node_modules/lodash/internal/arraySome.js create mode 100644 node_modules/lodash/internal/arraySum.js create mode 100644 node_modules/lodash/internal/assignDefaults.js create mode 100644 node_modules/lodash/internal/assignOwnDefaults.js create mode 100644 node_modules/lodash/internal/assignWith.js create mode 100644 node_modules/lodash/internal/baseAssign.js create mode 100644 node_modules/lodash/internal/baseAt.js create mode 100644 node_modules/lodash/internal/baseCallback.js create mode 100644 node_modules/lodash/internal/baseClone.js create mode 100644 node_modules/lodash/internal/baseCompareAscending.js create mode 100644 node_modules/lodash/internal/baseCopy.js create mode 100644 node_modules/lodash/internal/baseCreate.js create mode 100644 node_modules/lodash/internal/baseDelay.js create mode 100644 node_modules/lodash/internal/baseDifference.js create mode 100644 node_modules/lodash/internal/baseEach.js create mode 100644 node_modules/lodash/internal/baseEachRight.js create mode 100644 node_modules/lodash/internal/baseEvery.js create mode 100644 node_modules/lodash/internal/baseExtremum.js create mode 100644 node_modules/lodash/internal/baseFill.js create mode 100644 node_modules/lodash/internal/baseFilter.js create mode 100644 node_modules/lodash/internal/baseFind.js create mode 100644 node_modules/lodash/internal/baseFindIndex.js create mode 100644 node_modules/lodash/internal/baseFlatten.js create mode 100644 node_modules/lodash/internal/baseFor.js create mode 100644 node_modules/lodash/internal/baseForIn.js create mode 100644 node_modules/lodash/internal/baseForOwn.js create mode 100644 node_modules/lodash/internal/baseForOwnRight.js create mode 100644 node_modules/lodash/internal/baseForRight.js create mode 100644 node_modules/lodash/internal/baseFunctions.js create mode 100644 node_modules/lodash/internal/baseGet.js create mode 100644 node_modules/lodash/internal/baseIndexOf.js create mode 100644 node_modules/lodash/internal/baseIsEqual.js create mode 100644 node_modules/lodash/internal/baseIsEqualDeep.js create mode 100644 node_modules/lodash/internal/baseIsFunction.js create mode 100644 node_modules/lodash/internal/baseIsMatch.js create mode 100644 node_modules/lodash/internal/baseLodash.js create mode 100644 node_modules/lodash/internal/baseMap.js create mode 100644 node_modules/lodash/internal/baseMatches.js create mode 100644 node_modules/lodash/internal/baseMatchesProperty.js create mode 100644 node_modules/lodash/internal/baseMerge.js create mode 100644 node_modules/lodash/internal/baseMergeDeep.js create mode 100644 node_modules/lodash/internal/baseProperty.js create mode 100644 node_modules/lodash/internal/basePropertyDeep.js create mode 100644 node_modules/lodash/internal/basePullAt.js create mode 100644 node_modules/lodash/internal/baseRandom.js create mode 100644 node_modules/lodash/internal/baseReduce.js create mode 100644 node_modules/lodash/internal/baseSetData.js create mode 100644 node_modules/lodash/internal/baseSlice.js create mode 100644 node_modules/lodash/internal/baseSome.js create mode 100644 node_modules/lodash/internal/baseSortBy.js create mode 100644 node_modules/lodash/internal/baseSortByOrder.js create mode 100644 node_modules/lodash/internal/baseSum.js create mode 100644 node_modules/lodash/internal/baseToString.js create mode 100644 node_modules/lodash/internal/baseUniq.js create mode 100644 node_modules/lodash/internal/baseValues.js create mode 100644 node_modules/lodash/internal/baseWhile.js create mode 100644 node_modules/lodash/internal/baseWrapperValue.js create mode 100644 node_modules/lodash/internal/binaryIndex.js create mode 100644 node_modules/lodash/internal/binaryIndexBy.js create mode 100644 node_modules/lodash/internal/bindCallback.js create mode 100644 node_modules/lodash/internal/bufferClone.js create mode 100644 node_modules/lodash/internal/cacheIndexOf.js create mode 100644 node_modules/lodash/internal/cachePush.js create mode 100644 node_modules/lodash/internal/charsLeftIndex.js create mode 100644 node_modules/lodash/internal/charsRightIndex.js create mode 100644 node_modules/lodash/internal/compareAscending.js create mode 100644 node_modules/lodash/internal/compareMultiple.js create mode 100644 node_modules/lodash/internal/composeArgs.js create mode 100644 node_modules/lodash/internal/composeArgsRight.js create mode 100644 node_modules/lodash/internal/createAggregator.js create mode 100644 node_modules/lodash/internal/createAssigner.js create mode 100644 node_modules/lodash/internal/createBaseEach.js create mode 100644 node_modules/lodash/internal/createBaseFor.js create mode 100644 node_modules/lodash/internal/createBindWrapper.js create mode 100644 node_modules/lodash/internal/createCache.js create mode 100644 node_modules/lodash/internal/createCompounder.js create mode 100644 node_modules/lodash/internal/createCtorWrapper.js create mode 100644 node_modules/lodash/internal/createCurry.js create mode 100644 node_modules/lodash/internal/createExtremum.js create mode 100644 node_modules/lodash/internal/createFind.js create mode 100644 node_modules/lodash/internal/createFindIndex.js create mode 100644 node_modules/lodash/internal/createFindKey.js create mode 100644 node_modules/lodash/internal/createFlow.js create mode 100644 node_modules/lodash/internal/createForEach.js create mode 100644 node_modules/lodash/internal/createForIn.js create mode 100644 node_modules/lodash/internal/createForOwn.js create mode 100644 node_modules/lodash/internal/createHybridWrapper.js create mode 100644 node_modules/lodash/internal/createObjectMapper.js create mode 100644 node_modules/lodash/internal/createPadDir.js create mode 100644 node_modules/lodash/internal/createPadding.js create mode 100644 node_modules/lodash/internal/createPartial.js create mode 100644 node_modules/lodash/internal/createPartialWrapper.js create mode 100644 node_modules/lodash/internal/createReduce.js create mode 100644 node_modules/lodash/internal/createSortedIndex.js create mode 100644 node_modules/lodash/internal/createWrapper.js create mode 100644 node_modules/lodash/internal/deburrLetter.js create mode 100644 node_modules/lodash/internal/equalArrays.js create mode 100644 node_modules/lodash/internal/equalByTag.js create mode 100644 node_modules/lodash/internal/equalObjects.js create mode 100644 node_modules/lodash/internal/escapeHtmlChar.js create mode 100644 node_modules/lodash/internal/escapeStringChar.js create mode 100644 node_modules/lodash/internal/getData.js create mode 100644 node_modules/lodash/internal/getFuncName.js create mode 100644 node_modules/lodash/internal/getLength.js create mode 100644 node_modules/lodash/internal/getMatchData.js create mode 100644 node_modules/lodash/internal/getNative.js create mode 100644 node_modules/lodash/internal/getView.js create mode 100644 node_modules/lodash/internal/indexOfNaN.js create mode 100644 node_modules/lodash/internal/initCloneArray.js create mode 100644 node_modules/lodash/internal/initCloneByTag.js create mode 100644 node_modules/lodash/internal/initCloneObject.js create mode 100644 node_modules/lodash/internal/invokePath.js create mode 100644 node_modules/lodash/internal/isArrayLike.js create mode 100644 node_modules/lodash/internal/isIndex.js create mode 100644 node_modules/lodash/internal/isIterateeCall.js create mode 100644 node_modules/lodash/internal/isKey.js create mode 100644 node_modules/lodash/internal/isLaziable.js create mode 100644 node_modules/lodash/internal/isLength.js create mode 100644 node_modules/lodash/internal/isObjectLike.js create mode 100644 node_modules/lodash/internal/isSpace.js create mode 100644 node_modules/lodash/internal/isStrictComparable.js create mode 100644 node_modules/lodash/internal/lazyClone.js create mode 100644 node_modules/lodash/internal/lazyReverse.js create mode 100644 node_modules/lodash/internal/lazyValue.js create mode 100644 node_modules/lodash/internal/mapDelete.js create mode 100644 node_modules/lodash/internal/mapGet.js create mode 100644 node_modules/lodash/internal/mapHas.js create mode 100644 node_modules/lodash/internal/mapSet.js create mode 100644 node_modules/lodash/internal/mergeData.js create mode 100644 node_modules/lodash/internal/metaMap.js create mode 100644 node_modules/lodash/internal/pickByArray.js create mode 100644 node_modules/lodash/internal/pickByCallback.js create mode 100644 node_modules/lodash/internal/reEscape.js create mode 100644 node_modules/lodash/internal/reEvaluate.js create mode 100644 node_modules/lodash/internal/reInterpolate.js create mode 100644 node_modules/lodash/internal/realNames.js create mode 100644 node_modules/lodash/internal/reorder.js create mode 100644 node_modules/lodash/internal/replaceHolders.js create mode 100644 node_modules/lodash/internal/setData.js create mode 100644 node_modules/lodash/internal/shimIsPlainObject.js create mode 100644 node_modules/lodash/internal/shimKeys.js create mode 100644 node_modules/lodash/internal/sortedUniq.js create mode 100644 node_modules/lodash/internal/toIterable.js create mode 100644 node_modules/lodash/internal/toObject.js create mode 100644 node_modules/lodash/internal/toPath.js create mode 100644 node_modules/lodash/internal/trimmedLeftIndex.js create mode 100644 node_modules/lodash/internal/trimmedRightIndex.js create mode 100644 node_modules/lodash/internal/unescapeHtmlChar.js create mode 100644 node_modules/lodash/internal/wrapperClone.js create mode 100644 node_modules/lodash/lang.js create mode 100644 node_modules/lodash/lang/clone.js create mode 100644 node_modules/lodash/lang/cloneDeep.js create mode 100644 node_modules/lodash/lang/eq.js create mode 100644 node_modules/lodash/lang/gt.js create mode 100644 node_modules/lodash/lang/gte.js create mode 100644 node_modules/lodash/lang/isArguments.js create mode 100644 node_modules/lodash/lang/isArray.js create mode 100644 node_modules/lodash/lang/isBoolean.js create mode 100644 node_modules/lodash/lang/isDate.js create mode 100644 node_modules/lodash/lang/isElement.js create mode 100644 node_modules/lodash/lang/isEmpty.js create mode 100644 node_modules/lodash/lang/isEqual.js create mode 100644 node_modules/lodash/lang/isError.js create mode 100644 node_modules/lodash/lang/isFinite.js create mode 100644 node_modules/lodash/lang/isFunction.js create mode 100644 node_modules/lodash/lang/isMatch.js create mode 100644 node_modules/lodash/lang/isNaN.js create mode 100644 node_modules/lodash/lang/isNative.js create mode 100644 node_modules/lodash/lang/isNull.js create mode 100644 node_modules/lodash/lang/isNumber.js create mode 100644 node_modules/lodash/lang/isObject.js create mode 100644 node_modules/lodash/lang/isPlainObject.js create mode 100644 node_modules/lodash/lang/isRegExp.js create mode 100644 node_modules/lodash/lang/isString.js create mode 100644 node_modules/lodash/lang/isTypedArray.js create mode 100644 node_modules/lodash/lang/isUndefined.js create mode 100644 node_modules/lodash/lang/lt.js create mode 100644 node_modules/lodash/lang/lte.js create mode 100644 node_modules/lodash/lang/toArray.js create mode 100644 node_modules/lodash/lang/toPlainObject.js create mode 100644 node_modules/lodash/math.js create mode 100644 node_modules/lodash/math/add.js create mode 100644 node_modules/lodash/math/max.js create mode 100644 node_modules/lodash/math/min.js create mode 100644 node_modules/lodash/math/sum.js create mode 100644 node_modules/lodash/number.js create mode 100644 node_modules/lodash/number/inRange.js create mode 100644 node_modules/lodash/number/random.js create mode 100644 node_modules/lodash/object.js create mode 100644 node_modules/lodash/object/assign.js create mode 100644 node_modules/lodash/object/create.js create mode 100644 node_modules/lodash/object/defaults.js create mode 100644 node_modules/lodash/object/extend.js create mode 100644 node_modules/lodash/object/findKey.js create mode 100644 node_modules/lodash/object/findLastKey.js create mode 100644 node_modules/lodash/object/forIn.js create mode 100644 node_modules/lodash/object/forInRight.js create mode 100644 node_modules/lodash/object/forOwn.js create mode 100644 node_modules/lodash/object/forOwnRight.js create mode 100644 node_modules/lodash/object/functions.js create mode 100644 node_modules/lodash/object/get.js create mode 100644 node_modules/lodash/object/has.js create mode 100644 node_modules/lodash/object/invert.js create mode 100644 node_modules/lodash/object/keys.js create mode 100644 node_modules/lodash/object/keysIn.js create mode 100644 node_modules/lodash/object/mapKeys.js create mode 100644 node_modules/lodash/object/mapValues.js create mode 100644 node_modules/lodash/object/merge.js create mode 100644 node_modules/lodash/object/methods.js create mode 100644 node_modules/lodash/object/omit.js create mode 100644 node_modules/lodash/object/pairs.js create mode 100644 node_modules/lodash/object/pick.js create mode 100644 node_modules/lodash/object/result.js create mode 100644 node_modules/lodash/object/set.js create mode 100644 node_modules/lodash/object/transform.js create mode 100644 node_modules/lodash/object/values.js create mode 100644 node_modules/lodash/object/valuesIn.js create mode 100644 node_modules/lodash/package.json create mode 100644 node_modules/lodash/string.js create mode 100644 node_modules/lodash/string/camelCase.js create mode 100644 node_modules/lodash/string/capitalize.js create mode 100644 node_modules/lodash/string/deburr.js create mode 100644 node_modules/lodash/string/endsWith.js create mode 100644 node_modules/lodash/string/escape.js create mode 100644 node_modules/lodash/string/escapeRegExp.js create mode 100644 node_modules/lodash/string/kebabCase.js create mode 100644 node_modules/lodash/string/pad.js create mode 100644 node_modules/lodash/string/padLeft.js create mode 100644 node_modules/lodash/string/padRight.js create mode 100644 node_modules/lodash/string/parseInt.js create mode 100644 node_modules/lodash/string/repeat.js create mode 100644 node_modules/lodash/string/snakeCase.js create mode 100644 node_modules/lodash/string/startCase.js create mode 100644 node_modules/lodash/string/startsWith.js create mode 100644 node_modules/lodash/string/template.js create mode 100644 node_modules/lodash/string/templateSettings.js create mode 100644 node_modules/lodash/string/trim.js create mode 100644 node_modules/lodash/string/trimLeft.js create mode 100644 node_modules/lodash/string/trimRight.js create mode 100644 node_modules/lodash/string/trunc.js create mode 100644 node_modules/lodash/string/unescape.js create mode 100644 node_modules/lodash/string/words.js create mode 100644 node_modules/lodash/support.js create mode 100644 node_modules/lodash/utility.js create mode 100644 node_modules/lodash/utility/attempt.js create mode 100644 node_modules/lodash/utility/callback.js create mode 100644 node_modules/lodash/utility/constant.js create mode 100644 node_modules/lodash/utility/identity.js create mode 100644 node_modules/lodash/utility/iteratee.js create mode 100644 node_modules/lodash/utility/matches.js create mode 100644 node_modules/lodash/utility/matchesProperty.js create mode 100644 node_modules/lodash/utility/method.js create mode 100644 node_modules/lodash/utility/methodOf.js create mode 100644 node_modules/lodash/utility/mixin.js create mode 100644 node_modules/lodash/utility/noop.js create mode 100644 node_modules/lodash/utility/property.js create mode 100644 node_modules/lodash/utility/propertyOf.js create mode 100644 node_modules/lodash/utility/range.js create mode 100644 node_modules/lodash/utility/times.js create mode 100644 node_modules/lodash/utility/uniqueId.js create mode 100644 node_modules/mongoose/.npmignore create mode 100644 node_modules/mongoose/.travis.yml create mode 100644 node_modules/mongoose/CONTRIBUTING.md create mode 100644 node_modules/mongoose/History.md create mode 100644 node_modules/mongoose/README.md create mode 100755 node_modules/mongoose/contRun.sh create mode 100644 node_modules/mongoose/examples/README.md create mode 100644 node_modules/mongoose/examples/aggregate/aggregate.js create mode 100644 node_modules/mongoose/examples/aggregate/package.json create mode 100644 node_modules/mongoose/examples/aggregate/person.js create mode 100644 node_modules/mongoose/examples/doc-methods.js create mode 100644 node_modules/mongoose/examples/express/README.md create mode 100644 node_modules/mongoose/examples/express/connection-sharing/README.md create mode 100644 node_modules/mongoose/examples/express/connection-sharing/app.js create mode 100644 node_modules/mongoose/examples/express/connection-sharing/modelA.js create mode 100644 node_modules/mongoose/examples/express/connection-sharing/package.json create mode 100644 node_modules/mongoose/examples/express/connection-sharing/routes.js create mode 100644 node_modules/mongoose/examples/geospatial/geoJSONSchema.js create mode 100644 node_modules/mongoose/examples/geospatial/geoJSONexample.js create mode 100644 node_modules/mongoose/examples/geospatial/geospatial.js create mode 100644 node_modules/mongoose/examples/geospatial/package.json create mode 100644 node_modules/mongoose/examples/geospatial/person.js create mode 100644 node_modules/mongoose/examples/globalschemas/gs_example.js create mode 100644 node_modules/mongoose/examples/globalschemas/person.js create mode 100644 node_modules/mongoose/examples/lean/lean.js create mode 100644 node_modules/mongoose/examples/lean/package.json create mode 100644 node_modules/mongoose/examples/lean/person.js create mode 100644 node_modules/mongoose/examples/mapreduce/mapreduce.js create mode 100644 node_modules/mongoose/examples/mapreduce/package.json create mode 100644 node_modules/mongoose/examples/mapreduce/person.js create mode 100644 node_modules/mongoose/examples/population/population-across-three-collections.js create mode 100644 node_modules/mongoose/examples/population/population-basic.js create mode 100644 node_modules/mongoose/examples/population/population-of-existing-doc.js create mode 100644 node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js create mode 100644 node_modules/mongoose/examples/population/population-options.js create mode 100644 node_modules/mongoose/examples/population/population-plain-objects.js create mode 100644 node_modules/mongoose/examples/promises/package.json create mode 100644 node_modules/mongoose/examples/promises/person.js create mode 100644 node_modules/mongoose/examples/promises/promise.js create mode 100644 node_modules/mongoose/examples/querybuilder/package.json create mode 100644 node_modules/mongoose/examples/querybuilder/person.js create mode 100644 node_modules/mongoose/examples/querybuilder/querybuilder.js create mode 100644 node_modules/mongoose/examples/replicasets/package.json create mode 100644 node_modules/mongoose/examples/replicasets/person.js create mode 100644 node_modules/mongoose/examples/replicasets/replica-sets.js create mode 100644 node_modules/mongoose/examples/schema/schema.js create mode 100644 node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js create mode 100644 node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json create mode 100644 node_modules/mongoose/examples/statics/person.js create mode 100644 node_modules/mongoose/examples/statics/statics.js create mode 100644 node_modules/mongoose/index.js create mode 100644 node_modules/mongoose/lib/aggregate.js create mode 100644 node_modules/mongoose/lib/browser.js create mode 100644 node_modules/mongoose/lib/browserDocument.js create mode 100644 node_modules/mongoose/lib/cast.js create mode 100644 node_modules/mongoose/lib/collection.js create mode 100644 node_modules/mongoose/lib/connection.js create mode 100644 node_modules/mongoose/lib/connectionstate.js create mode 100644 node_modules/mongoose/lib/document.js create mode 100644 node_modules/mongoose/lib/document_provider.js create mode 100644 node_modules/mongoose/lib/drivers/SPEC.md create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js create mode 100644 node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js create mode 100644 node_modules/mongoose/lib/error.js create mode 100644 node_modules/mongoose/lib/error/browserMissingSchema.js create mode 100644 node_modules/mongoose/lib/error/cast.js create mode 100644 node_modules/mongoose/lib/error/divergentArray.js create mode 100644 node_modules/mongoose/lib/error/messages.js create mode 100644 node_modules/mongoose/lib/error/missingSchema.js create mode 100644 node_modules/mongoose/lib/error/overwriteModel.js create mode 100644 node_modules/mongoose/lib/error/validation.js create mode 100644 node_modules/mongoose/lib/error/validator.js create mode 100644 node_modules/mongoose/lib/error/version.js create mode 100644 node_modules/mongoose/lib/index.js create mode 100644 node_modules/mongoose/lib/internal.js create mode 100644 node_modules/mongoose/lib/model.js create mode 100644 node_modules/mongoose/lib/promise.js create mode 100644 node_modules/mongoose/lib/query.js create mode 100644 node_modules/mongoose/lib/queryhelpers.js create mode 100644 node_modules/mongoose/lib/querystream.js create mode 100644 node_modules/mongoose/lib/schema.js create mode 100644 node_modules/mongoose/lib/schema/array.js create mode 100644 node_modules/mongoose/lib/schema/boolean.js create mode 100644 node_modules/mongoose/lib/schema/buffer.js create mode 100644 node_modules/mongoose/lib/schema/date.js create mode 100644 node_modules/mongoose/lib/schema/documentarray.js create mode 100644 node_modules/mongoose/lib/schema/index.js create mode 100644 node_modules/mongoose/lib/schema/mixed.js create mode 100644 node_modules/mongoose/lib/schema/number.js create mode 100644 node_modules/mongoose/lib/schema/objectid.js create mode 100644 node_modules/mongoose/lib/schema/string.js create mode 100644 node_modules/mongoose/lib/schematype.js create mode 100644 node_modules/mongoose/lib/services/updateValidators.js create mode 100644 node_modules/mongoose/lib/statemachine.js create mode 100644 node_modules/mongoose/lib/types/array.js create mode 100644 node_modules/mongoose/lib/types/buffer.js create mode 100644 node_modules/mongoose/lib/types/documentarray.js create mode 100644 node_modules/mongoose/lib/types/embedded.js create mode 100644 node_modules/mongoose/lib/types/index.js create mode 100644 node_modules/mongoose/lib/types/objectid.js create mode 100644 node_modules/mongoose/lib/utils.js create mode 100644 node_modules/mongoose/lib/virtualtype.js create mode 100644 node_modules/mongoose/node_modules/async/.travis.yml create mode 100644 node_modules/mongoose/node_modules/async/LICENSE create mode 100644 node_modules/mongoose/node_modules/async/README.md create mode 100644 node_modules/mongoose/node_modules/async/component.json create mode 100755 node_modules/mongoose/node_modules/async/lib/async.js create mode 100644 node_modules/mongoose/node_modules/async/package.json create mode 100644 node_modules/mongoose/node_modules/bson/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/HISTORY create mode 100644 node_modules/mongoose/node_modules/bson/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/README.md create mode 100644 node_modules/mongoose/node_modules/bson/browser_build/bson.js create mode 100644 node_modules/mongoose/node_modules/bson/browser_build/package.json create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/binary.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/bson.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/bson_new.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/code.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/double.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/index.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/long.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/max_key.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/min_key.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/objectid.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/symbol.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/HISTORY create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/binding.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/bson.node.d create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/bson.node create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/linker.lock create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/obj.target/bson/ext/bson.o create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/binding.Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/bson.target.mk create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/config.gypi create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/gyp-mac-tool create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.cc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/wscript create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary_parser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/code.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/db_ref.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/double.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/long.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/max_key.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/min_key.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/objectid.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/symbol.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/timestamp.js create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/.bin/node-pre-gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/.dntrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/CHANGELOG.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/LICENSE.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/appveyor.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/include_dirs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_12_inl.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_pre_12_inl.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_new.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_string_bytes.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/CHANGELOG.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/appveyor.yml create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/bin/node-pre-gyp.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/build.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/clean.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/configure.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/info.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/install.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/node-pre-gyp.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/package.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/pre-binding.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish-maybe.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/rebuild.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reinstall.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reveal.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testbinary.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testpackage.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/unpublish.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/abi_crosswalk.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/compile.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/handle_gyp_opts.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/index.html create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/s3_setup.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/versioning.js create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/mkdirp create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/nopt create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rc create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rimraf create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/semver create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/LICENSE create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/cmd.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/usage.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/examples/pow.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/example/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/readme.markdown create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dash.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/default_bool.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dotted.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/long.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/short.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/whitespace.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/readme.markdown create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/chmod.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/clobber.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/mkdirp.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs_sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm_sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/race.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/rel.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return_sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/root.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask_sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/bin/nopt.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/examples/my-program.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/lib/nopt.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/CONTRIBUTING.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/abbrev.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/.npmrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/example.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/log.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/History.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/beep/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/clear/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/cursorPosition.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/progress/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/lib/ansi.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/lib/newlines.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/History.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/float.patch create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/float.patch create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/lib/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/build/build.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/component.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/tracker.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackergroup.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackerstream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md~ create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/example.png create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md~ create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/progress-bar.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/test/progress-bar.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/progress.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.APACHE2 create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.BSD create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.MIT create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/browser.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/lib/utils.js create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/.bin/strip-json-comments create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/index.spec.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/mocha.opts create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/ini.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/bar.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/fixtures/foo.ini create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/foo.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/example/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/readme.markdown create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/bool.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dash.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/default_bool.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dotted.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/long.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/num.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse_modified.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/short.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/whitespace.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/cli.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/strip-json-comments.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/ini.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/nested-env-vars.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.eslintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CHANGELOG.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CONTRIBUTING.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/disabled.appveyor.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/examples/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/auth.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/cookies.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/copy.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/getProxyFromURI.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/har.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/helpers.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/multipart.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/oauth.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/querystring.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/redirect.js create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/har-validator create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/uuid create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/LICENSE.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/bl.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/duplex.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/float.patch create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/build/build.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/component.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/passthrough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/readable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/transform.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/writable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/basic-test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/sauce.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/License create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/lib/combined_stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/License create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/License create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/lib/form_data.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/License create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/License create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/common.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-http-upload.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-auto-pause.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-pause.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-handle-source-errors.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-max-data-size.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-pipe-resumes.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-proxy-readable.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/run.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/bin/har-validator create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/changelog.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.min.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/any.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/assert.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/async.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bind.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bluebird.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/call_get.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/cancel.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/captured_trace.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/catch_filter.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/context.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/debuggability.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/direct_resolve.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/each.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/errors.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/es5.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/filter.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/finally.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/generators.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/join.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/map.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/method.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/nodeify.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/progress.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_array.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_resolver.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promisify.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/props.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/queue.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/race.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/reduce.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/schedule.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/settle.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/some.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/synchronous_inspection.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/thenables.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/timers.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/using.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/History.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/example.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/formats.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/example.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/is-property.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/LICENCE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/immutable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/mutable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/require.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/fixtures/cosmic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalItems.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalProperties.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/allOf.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/anyOf.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/bignum.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/default.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/definitions.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/dependencies.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/enum.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/format.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/items.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxItems.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxLength.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxProperties.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maximum.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minItems.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minLength.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minProperties.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minimum.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/multipleOf.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/not.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/nullAndFormat.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/oneOf.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/pattern.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/patternProperties.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/properties.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/ref.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/refRemote.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/required.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/type.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/uniqueItems.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/misc.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/error.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cache.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cacheEntry.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/content.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cookie.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/creator.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/entry.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/har.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/log.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/page.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/pageTimings.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/postData.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/record.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/request.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/response.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/timings.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.npmignore create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.travis.yml create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/LICENSE create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/Makefile create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/bower.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/component.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/example/usage.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/images/hawk.png create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/images/logo.png create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/lib/browser.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/lib/client.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/lib/crypto.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/lib/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/lib/server.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/lib/utils.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/.npmignore create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/CONTRIBUTING.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/LICENSE create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/images/boom.png create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/boom/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/.npmignore create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/.travis.yml create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/LICENSE create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/cryptiles/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/.npmignore create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/CONTRIBUTING.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/LICENSE create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/Makefile create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/images/hoek.png create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/lib/escape.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/escaper.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/ignore.txt create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/test1.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/test2.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/hoek/test/modules/test3.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/.npmignore create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/.travis.yml create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/LICENSE create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/Makefile create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/examples/offset.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/examples/time.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/node_modules/sntp/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/browser.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/client.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/crypto.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/index.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/message.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/readme.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/server.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/uri.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/test/utils.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/.dir-locals.el create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/http_signing.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/lib/parser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/lib/signer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/lib/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/lib/verify.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/errors.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/types.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/tst/ber/reader.test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/asn1/tst/ber/writer.test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/assert-plus/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/assert-plus/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/CHANGELOG create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/README create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/README.old create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/ctf.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/ctio.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/ctype.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/man/man3ctype/ctio.3ctype create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/tools/jsl.conf create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/ctype/tools/jsstyle create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/LICENSE.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/isstream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/isstream/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/CHANGELOG.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/stringify.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/test/mocha.opts create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/json-stringify-safe/test/stringify_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/HISTORY.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/HISTORY.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/db.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/node_modules/mime-db/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/mime-types/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/LICENSE.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.gnu create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark-native.c create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bin/uuid create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bower.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/component.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/compare_v1.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.html create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/uuid.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.eslintignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CHANGELOG.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CONTRIBUTING.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/bower.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/stringify.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/utils.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/stringify.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/utils.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/LICENSE.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/example.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/stringstream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.editorconfig create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/cookie.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/memstore.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/store.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/public-suffix.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/api_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_jar_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_sorting_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_json_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_string_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/date_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/domain_and_path_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/bsd-examples.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/examples.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/parser.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/lifetime_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/parsing_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/regression_test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/.jshintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/package.json create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/release.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/request.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/bin.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/common.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/glob.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/.eslintrc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/inflight.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/wrappy.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/minimatch.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/example.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/nested.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/order.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/pad.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/wrappy.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/once.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/test/once.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/rimraf.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/Makefile create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/bin/semver create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/foot.js.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/head.js.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js.gz create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js.gz create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/amd.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/big-numbers.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/clean.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/gtr.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/ltr.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/major-minor-patch.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/no-module.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/index.js create mode 120000 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/.bin/rimraf create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/Readme.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/debug.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/lib/debug.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/example/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/ignore.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/minimatch.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/foreach.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/bench.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/sigmund.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/brace-expand.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/caching.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/defaults.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/extglob-ending-with-state-char.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.ignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/00-setup.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/common.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/ignore-most.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/nested-ignores.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/unignore-child.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/zz-cleanup.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/filter-pipe.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/pipe.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/symlink-write.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/fstream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/abstract.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/collect.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/get-type.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/socket-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/fs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/polyfills.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/max-open.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/open.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/graceful-fs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/open.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/ulimit.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/once.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/test/once.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/duplex.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/float.patch create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/lib/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/util.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/build/build.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/component.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/passthrough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/readable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/transform.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/writable.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/AUTHORS create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/bin.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/rimraf.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/run.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/setup.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-async.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-sync.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/LICENCE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/extracter.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/packer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/buffer-entry.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/entry.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extract.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/global-header-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/header.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/pack.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENCE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/block-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/pause-resume.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/thorough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/two-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/tar.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/00-setup-fixtures.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/extract.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/fixtures.tgz create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/header.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/pack-no-proprietary.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/pack.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/zz-cleanup.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/LICENCE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/README.md create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/get-uid-gid.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/uid-number.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed-file.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed.tar create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed.tar.gz create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/bar.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/foo.txt create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/extracter.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/packer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/buffer-entry.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/entry-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/entry.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extract.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/global-header-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/header.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/pack.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENCE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/block-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/basic.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/pause-resume.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/thorough.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/two-stream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.travis.yml create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/filter-pipe.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/pipe.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/symlink-write.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/fstream.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/abstract.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/collect.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/get-type.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/socket-reader.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/writer.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/fs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/polyfills.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/max-open.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/open.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/tar.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/00-setup-fixtures.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/cb-never-called-1.0.1.tgz create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.tar create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/error-on-broken.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract-move.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/fixtures.tgz create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/header.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack-no-proprietary.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/parse.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/zz-cleanup.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/abi_crosswalk.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/clear_bucket.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/latest-by-abi.js create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test-node-webkit.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.bat create mode 100755 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.sh create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/app1.cc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/binding.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/app2.cc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/binding.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/include/foo.hpp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/lib/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/app3.cc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/binding.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/include/mylib/interface.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/mylib.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/src/implementation.cc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/app4.cpp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/binding.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/include/mylib/interface.h create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/mylib.gyp create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/src/implementation.cc create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/.npmignore create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/README.md create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/index.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/package.json create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/build.test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/mocha.opts create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/s3_setup.test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/versioning.test.js create mode 100644 node_modules/mongoose/node_modules/bson/node_modules/bson-ext/package.json create mode 100644 node_modules/mongoose/node_modules/bson/package.json create mode 100644 node_modules/mongoose/node_modules/bson/tools/gleak.js create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/.npmignore create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/Makefile create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/README.md create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/hooks.js create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/package.json create mode 100644 node_modules/mongoose/node_modules/hooks-fixed/test.js create mode 100644 node_modules/mongoose/node_modules/kareem/.npmignore create mode 100644 node_modules/mongoose/node_modules/kareem/.travis.yml create mode 100644 node_modules/mongoose/node_modules/kareem/LICENSE create mode 100644 node_modules/mongoose/node_modules/kareem/Makefile create mode 100644 node_modules/mongoose/node_modules/kareem/README.md create mode 100644 node_modules/mongoose/node_modules/kareem/docs.js create mode 100644 node_modules/mongoose/node_modules/kareem/gulpfile.js create mode 100644 node_modules/mongoose/node_modules/kareem/index.js create mode 100644 node_modules/mongoose/node_modules/kareem/package.json create mode 100644 node_modules/mongoose/node_modules/kareem/test/examples.test.js create mode 100644 node_modules/mongoose/node_modules/kareem/test/post.test.js create mode 100644 node_modules/mongoose/node_modules/kareem/test/pre.test.js create mode 100644 node_modules/mongoose/node_modules/kareem/test/wrap.test.js create mode 100644 node_modules/mongoose/node_modules/mongodb/.travis.yml create mode 100644 node_modules/mongoose/node_modules/mongodb/HISTORY.md create mode 100644 node_modules/mongoose/node_modules/mongodb/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb/Makefile create mode 100644 node_modules/mongoose/node_modules/mongodb/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/conf.json create mode 100644 node_modules/mongoose/node_modules/mongodb/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/admin.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/collection.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/db.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/mongos.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/read_preference.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/replset.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/server.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/topology_base.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/url_parser.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/utils.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.travis.yml create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Makefile create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d create mode 100755 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/linker.lock create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi create mode 100755 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/gyp-mac-tool create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js create mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js create mode 100644 node_modules/mongoose/node_modules/mongodb/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/t.js create mode 100644 node_modules/mongoose/node_modules/mongodb/t1.js create mode 100644 node_modules/mongoose/node_modules/mongodb/wercker.yml create mode 100644 node_modules/mongoose/node_modules/mpath/.npmignore create mode 100644 node_modules/mongoose/node_modules/mpath/.travis.yml create mode 100644 node_modules/mongoose/node_modules/mpath/History.md create mode 100644 node_modules/mongoose/node_modules/mpath/LICENSE create mode 100644 node_modules/mongoose/node_modules/mpath/Makefile create mode 100644 node_modules/mongoose/node_modules/mpath/README.md create mode 100644 node_modules/mongoose/node_modules/mpath/index.js create mode 100644 node_modules/mongoose/node_modules/mpath/lib/index.js create mode 100644 node_modules/mongoose/node_modules/mpath/package.json create mode 100644 node_modules/mongoose/node_modules/mpath/test/index.js create mode 100644 node_modules/mongoose/node_modules/mpromise/.npmignore create mode 100644 node_modules/mongoose/node_modules/mpromise/.travis.yml create mode 100644 node_modules/mongoose/node_modules/mpromise/History.md create mode 100644 node_modules/mongoose/node_modules/mpromise/LICENSE create mode 100644 node_modules/mongoose/node_modules/mpromise/README.md create mode 100644 node_modules/mongoose/node_modules/mpromise/lib/promise.js create mode 100644 node_modules/mongoose/node_modules/mpromise/package.json create mode 100644 node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js create mode 100644 node_modules/mongoose/node_modules/mpromise/test/promise.test.js create mode 100644 node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js create mode 100644 node_modules/mongoose/node_modules/mquery/.npmignore create mode 100644 node_modules/mongoose/node_modules/mquery/.travis.yml create mode 100644 node_modules/mongoose/node_modules/mquery/History.md create mode 100644 node_modules/mongoose/node_modules/mquery/LICENSE create mode 100644 node_modules/mongoose/node_modules/mquery/Makefile create mode 100644 node_modules/mongoose/node_modules/mquery/README.md create mode 100644 node_modules/mongoose/node_modules/mquery/lib/collection/collection.js create mode 100644 node_modules/mongoose/node_modules/mquery/lib/collection/index.js create mode 100644 node_modules/mongoose/node_modules/mquery/lib/collection/node.js create mode 100644 node_modules/mongoose/node_modules/mquery/lib/env.js create mode 100644 node_modules/mongoose/node_modules/mquery/lib/mquery.js create mode 100644 node_modules/mongoose/node_modules/mquery/lib/permissions.js create mode 100644 node_modules/mongoose/node_modules/mquery/lib/utils.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/schedule.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js create mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json create mode 100644 node_modules/mongoose/node_modules/mquery/package.json create mode 100644 node_modules/mongoose/node_modules/mquery/test/collection/browser.js create mode 100644 node_modules/mongoose/node_modules/mquery/test/collection/mongo.js create mode 100644 node_modules/mongoose/node_modules/mquery/test/collection/node.js create mode 100644 node_modules/mongoose/node_modules/mquery/test/env.js create mode 100644 node_modules/mongoose/node_modules/mquery/test/index.js create mode 100644 node_modules/mongoose/node_modules/mquery/test/utils.test.js create mode 100644 node_modules/mongoose/node_modules/ms/.npmignore create mode 100644 node_modules/mongoose/node_modules/ms/Makefile create mode 100644 node_modules/mongoose/node_modules/ms/README.md create mode 100644 node_modules/mongoose/node_modules/ms/ms.js create mode 100644 node_modules/mongoose/node_modules/ms/package.json create mode 100644 node_modules/mongoose/node_modules/ms/test/index.html create mode 100644 node_modules/mongoose/node_modules/ms/test/support/jquery.js create mode 100644 node_modules/mongoose/node_modules/ms/test/test.js create mode 100644 node_modules/mongoose/node_modules/muri/.npmignore create mode 100644 node_modules/mongoose/node_modules/muri/.travis.yml create mode 100644 node_modules/mongoose/node_modules/muri/History.md create mode 100644 node_modules/mongoose/node_modules/muri/LICENSE create mode 100644 node_modules/mongoose/node_modules/muri/Makefile create mode 100644 node_modules/mongoose/node_modules/muri/README.md create mode 100644 node_modules/mongoose/node_modules/muri/index.js create mode 100644 node_modules/mongoose/node_modules/muri/lib/index.js create mode 100644 node_modules/mongoose/node_modules/muri/package.json create mode 100644 node_modules/mongoose/node_modules/muri/strict.js create mode 100644 node_modules/mongoose/node_modules/muri/test/index.js create mode 100644 node_modules/mongoose/node_modules/regexp-clone/.npmignore create mode 100644 node_modules/mongoose/node_modules/regexp-clone/.travis.yml create mode 100644 node_modules/mongoose/node_modules/regexp-clone/History.md create mode 100644 node_modules/mongoose/node_modules/regexp-clone/LICENSE create mode 100644 node_modules/mongoose/node_modules/regexp-clone/Makefile create mode 100644 node_modules/mongoose/node_modules/regexp-clone/README.md create mode 100644 node_modules/mongoose/node_modules/regexp-clone/index.js create mode 100644 node_modules/mongoose/node_modules/regexp-clone/package.json create mode 100644 node_modules/mongoose/node_modules/regexp-clone/test/index.js create mode 100644 node_modules/mongoose/node_modules/sliced/.npmignore create mode 100644 node_modules/mongoose/node_modules/sliced/.travis.yml create mode 100644 node_modules/mongoose/node_modules/sliced/History.md create mode 100644 node_modules/mongoose/node_modules/sliced/LICENSE create mode 100644 node_modules/mongoose/node_modules/sliced/Makefile create mode 100644 node_modules/mongoose/node_modules/sliced/README.md create mode 100644 node_modules/mongoose/node_modules/sliced/bench.js create mode 100644 node_modules/mongoose/node_modules/sliced/component.json create mode 100644 node_modules/mongoose/node_modules/sliced/index.js create mode 100644 node_modules/mongoose/node_modules/sliced/lib/sliced.js create mode 100644 node_modules/mongoose/node_modules/sliced/package.json create mode 100644 node_modules/mongoose/node_modules/sliced/test/index.js create mode 100644 node_modules/mongoose/package.json create mode 100644 node_modules/mongoose/release-items.md create mode 100644 node_modules/mongoose/static.js create mode 100644 node_modules/mongoose/website.js create mode 100644 node_modules/path/LICENSE create mode 100644 node_modules/path/README.md create mode 100644 node_modules/path/package.json create mode 100644 node_modules/path/path.js create mode 100644 package.json diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..c0b8246 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,41 @@ +{ + "node": true, // Enable globals available when code is running inside of the NodeJS runtime environment. + "mocha": true, // Enable globals available when code is running inside of the Mocha tests. + "jasmine": true, // Enable globals available when code is running inside of the Jasmine tests. + "browser": true, // Standard browser globals e.g. `window`, `document`. + "esnext": true, // Allow ES.next specific features such as `const` and `let`. + "bitwise": false, // Prohibit bitwise operators (&, |, ^, etc.). + "camelcase": false, // Permit only camelcase for `var` and `object indexes`. + "curly": false, // Require {} for every new block or scope. + "eqeqeq": true, // Require triple equals i.e. `===`. + "immed": true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` + "latedef": "nofunc", // Prohibit variable use before definition except for function declaration. + "newcap": true, // Require capitalization of all constructor functions e.g. `new F()`. + "noarg": true, // Prohibit use of `arguments.caller` and `arguments.callee`. + "quotmark": "single", // Define quotes to string values. + "regexp": true, // Prohibit `.` and `[^...]` in regular expressions. + "undef": true, // Require all non-global variables be declared before they are used. + "unused": false, // Warn unused variables. + "strict": true, // Require `use strict` pragma in every file. + "trailing": true, // Prohibit trailing whitespaces. + "smarttabs": false, // Suppresses warnings about mixed tabs and spaces + "globals": { // Globals variables. + "angular": true, + "io": true, + "ApplicationConfiguration": true, + "Chart": true, + "moment": true, + "$": true, + "_": true, + "google": true + }, + "predef": [ // Extra globals. + "inject", + "by", + "browser", + "element" + ], + "indent": 4, // Specify indentation spacing + "devel": true, // Allow development statements e.g. `console.log();`. + "noempty": true // Prohibit use of empty blocks. +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6440950 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Sean Emmer + +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/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/index.js b/index.js new file mode 100644 index 0000000..e535b5a --- /dev/null +++ b/index.js @@ -0,0 +1,128 @@ +'use strict'; + +/** + * Module dependencies. + **/ +var _ = require('lodash'), + async = require('async'), + mongoose = require('mongoose'), + chalk = require('chalk'), + path = require('path'); + +function Seeder() { + this.connected = false; +} + +Seeder.prototype.connect = function(db, cb) { + var _this = this; + mongoose.connect(db, function(err) { + // Log Error + if (err) { + console.error(chalk.red('Could not connect to MongoDB!')); + console.log(err); + } else { + _this.connected = true; + console.log('Successfully initialized mongoose-seed'); + cb(); + } + }); +}; + +Seeder.prototype.loadModels = function(modelPaths) { + modelPaths.forEach(function(modelPath) { + require(path.resolve(modelPath)); + }); +}; + +Seeder.prototype.invalidModelCheck = function(models, cb) { + var invalidModels = []; + + models.forEach(function(model) { + if(_.indexOf(mongoose.modelNames(), model) === -1) { + invalidModels.push(model); + } + }); + + if (invalidModels.length) { + cb(new Error('Models not registered in Mongoose: ' + invalidModels)); + } else { + cb(); + } +}; + +Seeder.prototype.clearModels = function(models, cb) { + if(!this.connected) { + return new Error('Not connected to db, exiting function'); + } + + var modelNames = []; + + // Convert to array if not already + if (Array.isArray(models)) { + modelNames = models; + } else if (typeof(models) === 'string') { + modelNames.push(models); + } else { + console.error(chalk.red('Error: Invalid model type')); + return; + } + + // Confirm that all Models have been registered in Mongoose + var invalidModels = this.invalidModelCheck(modelNames, function(err) { + if (err) { + console.error(chalk.red('Error: ' + err.message)); + return; + } + + // Clear each model + async.each(modelNames, function(modelName, done) { + var Model = mongoose.model(modelName); + Model.remove({}, function(err) { + if (err) { + console.error(chalk.red('Error: ' + err.message)); + return; + } + console.log(modelName + 's collection cleared'); + done(); + }); + }, function(err) { + // Final async callback + if(err) { return; } + cb(); + }); + }); +}; + +Seeder.prototype.populateModels = function(seedData) { + if(!this.connected) { + return new Error('Not connected to db, exiting function'); + } + + var modelNames = _.unique(_.pluck(seedData,'model')); + + // Confirm that all Models have been registered in Mongoose + var invalidModels = this.invalidModelCheck(modelNames, function(err) { + if (err) { + console.error(chalk.red('Error: ' + err.message)); + return; + } + + // Populate each model + seedData.forEach(function(entry) { + var Model = mongoose.model(entry.model); + entry.documents.forEach(function(document, j) { + Model.create(document, function(err) { + if (err) { + console.error(chalk.red('Error creating document [' + j + '] of ' + entry.model + ' model')); + console.error(chalk.red('Error: ' + err.message)); + return; + } + console.log('Successfully created document [' + j + '] of ' + entry.model + ' model'); + }); + }); + }); + + }); +}; + +module.exports = new Seeder(); \ No newline at end of file diff --git a/node_modules/async/.jshintrc b/node_modules/async/.jshintrc new file mode 100644 index 0000000..7427dce --- /dev/null +++ b/node_modules/async/.jshintrc @@ -0,0 +1,25 @@ +{ + // Enforcing options + "eqeqeq": false, + "forin": true, + "indent": 4, + "noarg": true, + "undef": true, + "unused": 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/async/.travis.yml b/node_modules/async/.travis.yml new file mode 100644 index 0000000..0a62fca --- /dev/null +++ b/node_modules/async/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "iojs-v2.1.0" +after_success: npm run coveralls diff --git a/node_modules/async/CHANGELOG.md b/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..c182178 --- /dev/null +++ b/node_modules/async/CHANGELOG.md @@ -0,0 +1,51 @@ +# v1.2.0 + +New Features: + +- Added `timesLimit` (#743) +- `concurrency` can be changed in `async.queue` by setting `q.concurrency`. The concurrency will be reflected the next time a task it processed. (#747, #772) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. (#775, #777) + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. (#769) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array (#667). +- The callback is now optional for the composed results of `compose` and `seq`. (#618) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` (#768) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator (#622) +- `eachLimit` and other limit functions will stop iterating once an error occurs (#754) +- Always pass `null` in callbacks when there is no error (#439) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue (#668) +- `each` and family will properly handle an empty array (#578) +- `eachSeries` and family will finish if the underlying array is modified during execution (#557) +- `queue` will throw if a non-function is passed to `q.push()` (#593) +- Doc fixes (#629, #766) + + +# 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/async/LICENSE b/node_modules/async/LICENSE new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/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/async/README.md b/node_modules/async/README.md new file mode 100644 index 0000000..580d797 --- /dev/null +++ b/node_modules/async/README.md @@ -0,0 +1,1803 @@ +# 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) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) + +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 + + +### Synchronous iteration functions + +If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iterator. By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers. Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.nextTick` to start a new call stack on the next tick of the event loop. + +This can also arise by accident if you callback early in certain cases: + +```js +async.eachSeries(hugeArray, function iterator(item, callback) { + if (inCache(item)) { + callback(null, cache[item]); // if many items are cached, you'll overflow + } else { + doSomeIO(item, callback); + } +}, function done() { + //... +}); +``` + +Just change it to: + +```js +async.eachSeries(hugeArray, function iterator(item, callback) { + if (inCache(item)) { + async.setImmediate(function () { + callback(null, cache[item]); + }); + } else { + doSomeIO(item, callback); + //... +``` + +Async guards against synchronous functions in some, but not all, cases. If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync) Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral. + +If javascript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works. + + +### 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) +* [`timesLimit`](#timesLimit) + +### Utils + +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`ensureAsync`](#ensureAsync) +* [`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)` - *Optional* 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)` - *Optional* 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)` - *Optional* 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)` - *Optional* 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)` - *Optional* 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)` - *Optional* 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. **Note: this callback does not take an error as its first argument.** +* `callback(result)` - *Optional* 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. **Note: this callback does not take an error as its first argument.** + +__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)` - *Optional* 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)` - *Optional* 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. + + **Note: the callbacks do not take an error as their first argument.** +__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)` - *Optional* 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. + + **Note: the callbacks do not take an error as their first argument.** + +__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)` - *Optional* 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. If you want to handle errors from an individual task, pass a callback to `q.push()`. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. + +__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 [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) 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`. +* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue) + +__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, iterator, [callback]) + +Calls the `iterator` 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, iterator, [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. + + +### timesLimit(n, limit, iterator, [callback]) + +The same as [`times`](#times), except a maximum of `limit` iterators are run at a given time, similar to [`mapLimit`](#mapLimit). + + +## 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 + +--------------------------------------- + + +### ensureAsync(fn) + +Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. + +__Arguments__ + +* `fn` - an async function, one that expects a node-style callback as its last argument + +Returns a wrapped function with the exact same call signature as the function passed in. + +__Example__ + +```js +function sometimesAsync(arg, callback) { + if (cache[arg]) { + return callback(null, cache[arg]); // this would be synchronous!! + } else { + doSomeIO(arg, callback); // this IO would be asynchronous + } +} + +// this has a risk of stack overflows if many results are cached in a row +async.mapSeries(args, sometimesAsync, done); + +// this will defer sometimesAsync's callback if necessary, +// preventing stack overflows +async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + +``` + +--------------------------------------- + + +### 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/async/bower.json b/node_modules/async/bower.json new file mode 100644 index 0000000..9e4156d --- /dev/null +++ b/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/async/component.json b/node_modules/async/component.json new file mode 100644 index 0000000..c876b0a --- /dev/null +++ b/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/async/coverage/base.css b/node_modules/async/coverage/base.css new file mode 100644 index 0000000..7fb8827 --- /dev/null +++ b/node_modules/async/coverage/base.css @@ -0,0 +1,182 @@ +body, html { + margin:0; padding: 0; +} +body { + font-family: Helvetica Neue, Helvetica,Arial; + font-size: 10pt; +} +div.header, div.footer { + background: #eee; + padding: 1em; +} +div.header { + z-index: 100; + position: fixed; + top: 0; + border-bottom: 1px solid #666; + width: 100%; +} +div.footer { + border-top: 1px solid #666; +} +div.body { + margin-top: 10em; +} +div.meta { + font-size: 90%; + text-align: center; +} +h1, h2, h3 { + font-weight: normal; +} +h1 { + font-size: 12pt; +} +h2 { + font-size: 10pt; +} +pre { + font-family: Consolas, Menlo, Monaco, monospace; + margin: 0; + padding: 0; + line-height: 14px; + font-size: 14px; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} + +div.path { font-size: 110%; } +div.path a:link, div.path a:visited { color: #000; } +table.coverage { border-collapse: collapse; margin:0; padding: 0 } + +table.coverage td { + margin: 0; + padding: 0; + color: #111; + vertical-align: top; +} +table.coverage td.line-count { + width: 50px; + text-align: right; + padding-right: 5px; +} +table.coverage td.line-coverage { + color: #777 !important; + text-align: right; + border-left: 1px solid #666; + border-right: 1px solid #666; +} + +table.coverage td.text { +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 40px; +} +table.coverage td span.cline-neutral { + background: #eee; +} +table.coverage td span.cline-yes { + background: #b5d592; + color: #999; +} +table.coverage td span.cline-no { + background: #fc8c84; +} + +.cstat-yes { color: #111; } +.cstat-no { background: #fc8c84; color: #111; } +.fstat-no { background: #ffc520; color: #111 !important; } +.cbranch-no { background: yellow !important; color: #111; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +.missing-if-branch { + display: inline-block; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: black; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} + +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} + +.entity, .metric { font-weight: bold; } +.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } +.metric small { font-size: 80%; font-weight: normal; color: #666; } + +div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } +div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } +div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } +div.coverage-summary th.file { border-right: none !important; } +div.coverage-summary th.pic { border-left: none !important; text-align: right; } +div.coverage-summary th.pct { border-right: none !important; } +div.coverage-summary th.abs { border-left: none !important; text-align: right; } +div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } +div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } +div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; } +div.coverage-summary td.pic { min-width: 120px !important; } +div.coverage-summary a:link { text-decoration: none; color: #000; } +div.coverage-summary a:visited { text-decoration: none; color: #333; } +div.coverage-summary a:hover { text-decoration: underline; } +div.coverage-summary tfoot td { border-top: 1px solid #666; } + +div.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +div.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +div.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} + +.high { background: #b5d592 !important; } +.medium { background: #ffe87c !important; } +.low { background: #fc8c84 !important; } + +span.cover-fill, span.cover-empty { + display:inline-block; + border:1px solid #444; + background: white; + height: 12px; +} +span.cover-fill { + background: #ccc; + border-right: 1px solid #444; +} +span.cover-empty { + background: white; + border-left: none; +} +span.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } \ No newline at end of file diff --git a/node_modules/async/coverage/index.html b/node_modules/async/coverage/index.html new file mode 100644 index 0000000..0a8d4b7 --- /dev/null +++ b/node_modules/async/coverage/index.html @@ -0,0 +1,73 @@ + + + + Code coverage report for All files + + + + + + +
+

Code coverage report for All files

+

+ Statements: 94.88% (611 / 644)      + Branches: 86.91% (239 / 275)      + Functions: 95.41% (187 / 196)      + Lines: 94.85% (608 / 641)      + Ignored: none      +

+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
lib/94.88%(611 / 644)86.91%(239 / 275)95.41%(187 / 196)94.85%(608 / 641)
+
+
+
+ + + + + diff --git a/node_modules/async/coverage/lcov-report/base.css b/node_modules/async/coverage/lcov-report/base.css new file mode 100644 index 0000000..7fb8827 --- /dev/null +++ b/node_modules/async/coverage/lcov-report/base.css @@ -0,0 +1,182 @@ +body, html { + margin:0; padding: 0; +} +body { + font-family: Helvetica Neue, Helvetica,Arial; + font-size: 10pt; +} +div.header, div.footer { + background: #eee; + padding: 1em; +} +div.header { + z-index: 100; + position: fixed; + top: 0; + border-bottom: 1px solid #666; + width: 100%; +} +div.footer { + border-top: 1px solid #666; +} +div.body { + margin-top: 10em; +} +div.meta { + font-size: 90%; + text-align: center; +} +h1, h2, h3 { + font-weight: normal; +} +h1 { + font-size: 12pt; +} +h2 { + font-size: 10pt; +} +pre { + font-family: Consolas, Menlo, Monaco, monospace; + margin: 0; + padding: 0; + line-height: 14px; + font-size: 14px; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} + +div.path { font-size: 110%; } +div.path a:link, div.path a:visited { color: #000; } +table.coverage { border-collapse: collapse; margin:0; padding: 0 } + +table.coverage td { + margin: 0; + padding: 0; + color: #111; + vertical-align: top; +} +table.coverage td.line-count { + width: 50px; + text-align: right; + padding-right: 5px; +} +table.coverage td.line-coverage { + color: #777 !important; + text-align: right; + border-left: 1px solid #666; + border-right: 1px solid #666; +} + +table.coverage td.text { +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 40px; +} +table.coverage td span.cline-neutral { + background: #eee; +} +table.coverage td span.cline-yes { + background: #b5d592; + color: #999; +} +table.coverage td span.cline-no { + background: #fc8c84; +} + +.cstat-yes { color: #111; } +.cstat-no { background: #fc8c84; color: #111; } +.fstat-no { background: #ffc520; color: #111 !important; } +.cbranch-no { background: yellow !important; color: #111; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +.missing-if-branch { + display: inline-block; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: black; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} + +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} + +.entity, .metric { font-weight: bold; } +.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } +.metric small { font-size: 80%; font-weight: normal; color: #666; } + +div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } +div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } +div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } +div.coverage-summary th.file { border-right: none !important; } +div.coverage-summary th.pic { border-left: none !important; text-align: right; } +div.coverage-summary th.pct { border-right: none !important; } +div.coverage-summary th.abs { border-left: none !important; text-align: right; } +div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } +div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } +div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; } +div.coverage-summary td.pic { min-width: 120px !important; } +div.coverage-summary a:link { text-decoration: none; color: #000; } +div.coverage-summary a:visited { text-decoration: none; color: #333; } +div.coverage-summary a:hover { text-decoration: underline; } +div.coverage-summary tfoot td { border-top: 1px solid #666; } + +div.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +div.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +div.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} + +.high { background: #b5d592 !important; } +.medium { background: #ffe87c !important; } +.low { background: #fc8c84 !important; } + +span.cover-fill, span.cover-empty { + display:inline-block; + border:1px solid #444; + background: white; + height: 12px; +} +span.cover-fill { + background: #ccc; + border-right: 1px solid #444; +} +span.cover-empty { + background: white; + border-left: none; +} +span.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } \ No newline at end of file diff --git a/node_modules/async/coverage/lcov-report/index.html b/node_modules/async/coverage/lcov-report/index.html new file mode 100644 index 0000000..6660bfa --- /dev/null +++ b/node_modules/async/coverage/lcov-report/index.html @@ -0,0 +1,73 @@ + + + + Code coverage report for All files + + + + + + +
+

Code coverage report for All files

+

+ Statements: 94.13% (673 / 715)      + Branches: 85% (272 / 320)      + Functions: 94.2% (195 / 207)      + Lines: 94.36% (669 / 709)      + Ignored: none      +

+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
lib/94.13%(673 / 715)85%(272 / 320)94.2%(195 / 207)94.36%(669 / 709)
+
+
+ + + + + + diff --git a/node_modules/async/coverage/lcov-report/lib/async.js.html b/node_modules/async/coverage/lcov-report/lib/async.js.html new file mode 100644 index 0000000..951e4c2 --- /dev/null +++ b/node_modules/async/coverage/lcov-report/lib/async.js.html @@ -0,0 +1,3900 @@ + + + + Code coverage report for lib/async.js + + + + + + +
+

Code coverage report for lib/async.js

+

+ Statements: 94.13% (673 / 715)      + Branches: 85% (272 / 320)      + Functions: 94.2% (195 / 207)      + Lines: 94.36% (669 / 709)      + Ignored: none      +

+
All files » lib/ » async.js
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334 +335 +336 +337 +338 +339 +340 +341 +342 +343 +344 +345 +346 +347 +348 +349 +350 +351 +352 +353 +354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 +366 +367 +368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +378 +379 +380 +381 +382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 +422 +423 +424 +425 +426 +427 +428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467 +468 +469 +470 +471 +472 +473 +474 +475 +476 +477 +478 +479 +480 +481 +482 +483 +484 +485 +486 +487 +488 +489 +490 +491 +492 +493 +494 +495 +496 +497 +498 +499 +500 +501 +502 +503 +504 +505 +506 +507 +508 +509 +510 +511 +512 +513 +514 +515 +516 +517 +518 +519 +520 +521 +522 +523 +524 +525 +526 +527 +528 +529 +530 +531 +532 +533 +534 +535 +536 +537 +538 +539 +540 +541 +542 +543 +544 +545 +546 +547 +548 +549 +550 +551 +552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 +571 +572 +573 +574 +575 +576 +577 +578 +579 +580 +581 +582 +583 +584 +585 +586 +587 +588 +589 +590 +591 +592 +593 +594 +595 +596 +597 +598 +599 +600 +601 +602 +603 +604 +605 +606 +607 +608 +609 +610 +611 +612 +613 +614 +615 +616 +617 +618 +619 +620 +621 +622 +623 +624 +625 +626 +627 +628 +629 +630 +631 +632 +633 +634 +635 +636 +637 +638 +639 +640 +641 +642 +643 +644 +645 +646 +647 +648 +649 +650 +651 +652 +653 +654 +655 +656 +657 +658 +659 +660 +661 +662 +663 +664 +665 +666 +667 +668 +669 +670 +671 +672 +673 +674 +675 +676 +677 +678 +679 +680 +681 +682 +683 +684 +685 +686 +687 +688 +689 +690 +691 +692 +693 +694 +695 +696 +697 +698 +699 +700 +701 +702 +703 +704 +705 +706 +707 +708 +709 +710 +711 +712 +713 +714 +715 +716 +717 +718 +719 +720 +721 +722 +723 +724 +725 +726 +727 +728 +729 +730 +731 +732 +733 +734 +735 +736 +737 +738 +739 +740 +741 +742 +743 +744 +745 +746 +747 +748 +749 +750 +751 +752 +753 +754 +755 +756 +757 +758 +759 +760 +761 +762 +763 +764 +765 +766 +767 +768 +769 +770 +771 +772 +773 +774 +775 +776 +777 +778 +779 +780 +781 +782 +783 +784 +785 +786 +787 +788 +789 +790 +791 +792 +793 +794 +795 +796 +797 +798 +799 +800 +801 +802 +803 +804 +805 +806 +807 +808 +809 +810 +811 +812 +813 +814 +815 +816 +817 +818 +819 +820 +821 +822 +823 +824 +825 +826 +827 +828 +829 +830 +831 +832 +833 +834 +835 +836 +837 +838 +839 +840 +841 +842 +843 +844 +845 +846 +847 +848 +849 +850 +851 +852 +853 +854 +855 +856 +857 +858 +859 +860 +861 +862 +863 +864 +865 +866 +867 +868 +869 +870 +871 +872 +873 +874 +875 +876 +877 +878 +879 +880 +881 +882 +883 +884 +885 +886 +887 +888 +889 +890 +891 +892 +893 +894 +895 +896 +897 +898 +899 +900 +901 +902 +903 +904 +905 +906 +907 +908 +909 +910 +911 +912 +913 +914 +915 +916 +917 +918 +919 +920 +921 +922 +923 +924 +925 +926 +927 +928 +929 +930 +931 +932 +933 +934 +935 +936 +937 +938 +939 +940 +941 +942 +943 +944 +945 +946 +947 +948 +949 +950 +951 +952 +953 +954 +955 +956 +957 +958 +959 +960 +961 +962 +963 +964 +965 +966 +967 +968 +969 +970 +971 +972 +973 +974 +975 +976 +977 +978 +979 +980 +981 +982 +983 +984 +985 +986 +987 +988 +989 +990 +991 +992 +993 +994 +995 +996 +997 +998 +999 +1000 +1001 +1002 +1003 +1004 +1005 +1006 +1007 +1008 +1009 +1010 +1011 +1012 +1013 +1014 +1015 +1016 +1017 +1018 +1019 +1020 +1021 +1022 +1023 +1024 +1025 +1026 +1027 +1028 +1029 +1030 +1031 +1032 +1033 +1034 +1035 +1036 +1037 +1038 +1039 +1040 +1041 +1042 +1043 +1044 +1045 +1046 +1047 +1048 +1049 +1050 +1051 +1052 +1053 +1054 +1055 +1056 +1057 +1058 +1059 +1060 +1061 +1062 +1063 +1064 +1065 +1066 +1067 +1068 +1069 +1070 +1071 +1072 +1073 +1074 +1075 +1076 +1077 +1078 +1079 +1080 +1081 +1082 +1083 +1084 +1085 +1086 +1087 +1088 +1089 +1090 +1091 +1092 +1093 +1094 +1095 +1096 +1097 +1098 +1099 +1100 +1101 +1102 +1103 +1104 +1105 +1106 +1107 +1108 +1109 +1110 +1111 +1112 +1113 +1114 +1115 +1116 +1117 +1118 +1119 +1120 +1121 +1122 +1123 +1124 +1125 +1126 +1127 +1128 +1129 +1130 +1131 +1132 +1133 +1134 +1135 +1136 +1137 +1138 +1139 +1140 +1141 +1142 +1143 +1144 +1145 +1146 +1147 +1148 +1149 +1150 +1151 +1152 +1153 +1154 +1155 +1156 +1157 +1158 +1159 +1160 +1161 +1162 +1163 +1164 +1165 +1166 +1167 +1168 +1169 +1170 +1171 +1172 +1173 +1174 +1175 +1176 +1177 +1178 +1179 +1180 +1181 +1182 +1183 +1184 +1185 +1186 +1187 +1188 +1189 +1190 +1191 +1192 +1193 +1194 +1195 +1196 +1197 +1198 +1199 +1200 +1201 +1202 +1203 +1204 +1205 +1206 +1207 +1208 +1209 +1210 +1211 +1212 +1213 +1214 +1215 +1216 +1217 +1218 +1219 +1220 +1221 +1222 +1223 +1224 +1225 +1226 +1227 +1228 +1229 +1230 +1231 +1232 +1233 +1234 +1235 +1236 +1237 +1238 +1239 +1240 +1241 +1242 +1243 +1244 +1245 +1246 +1247 +1248 +1249 +1250 +1251 +1252 +1253 +1254 +1255 +1256 +1257 +1258 +1259 +1260 +1261 +1262 +1263 +1264 +1265 +1266 +1267 +1268 +1269 +1270 +1271 +1272 +1273 +1274 +1275 +1276 +1277 +1278 +1279 +1280 +1281 +1282 +1283 +1284 +1285 +1286  +  +  +  +  +  +  +1 +  +1 +1 +  +  +1 +  +1 +  +  +1 +1 +  +  +  +  +  +1 +1 +  +  +1 +  +  +  +  +1 +162 +162 +162 +158 +158 +  +  +  +  +  +1 +  +1 +  +  +  +1 +249 +  +  +249 +402 +  +  +  +1 +76 +  +  +  +76 +222 +  +76 +  +  +1 +54 +54 +  +54 +  +  +1 +4 +7 +  +  +  +1 +  +  +  +  +  +  +  +  +  +1 +237 +237 +237 +  +237 +148 +148 +  +237 +  +237 +360 +  +237 +  +  +  +  +  +  +  +1 +1 +1 +  +  +1 +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1 +1 +1 +  +219 +  +  +  +  +  +  +  +1 +37 +37 +3 +  +34 +34 +99 +  +1 +95 +14 +14 +  +  +81 +81 +27 +  +  +  +  +1 +  +1 +35 +35 +2 +  +33 +33 +79 +76 +10 +10 +  +  +66 +66 +20 +  +  +46 +  +  +  +  +33 +  +1 +  +  +1 +9 +9 +  +1 +  +1 +  +27 +22 +22 +5 +  +17 +17 +17 +17 +  +17 +77 +  +  +  +77 +81 +81 +81 +77 +6 +6 +6 +  +  +71 +71 +71 +11 +  +  +60 +  +  +  +  +  +  +  +  +  +  +1 +5 +5 +5 +5 +1 +  +4 +7 +7 +2 +2 +  +5 +5 +3 +  +  +  +  +  +  +1 +5 +5 +5 +5 +1 +  +4 +4 +6 +6 +6 +6 +1 +1 +  +  +5 +5 +3 +  +  +2 +  +  +  +2 +  +  +  +  +6 +  +4 +  +  +  +  +1 +9 +  +  +1 +  +9 +9 +9 +9 +9 +2 +  +7 +7 +7 +  +7 +20 +  +  +  +20 +22 +22 +22 +22 +20 +1 +1 +  +  +19 +19 +19 +6 +  +  +13 +  +  +  +  +  +  +  +  +  +1 +6 +25 +25 +  +  +1 +13 +12 +12 +  +  +1 +6 +20 +20 +  +  +  +  +1 +40 +142 +  +40 +1 +3 +3 +  +  +  +39 +39 +99 +97 +97 +  +  +39 +  +  +  +1 +1 +1 +7 +  +  +1 +13 +  +  +  +  +1 +10 +24 +24 +24 +  +  +10 +  +  +  +1 +  +1 +  +1 +1 +3 +  +1 +  +  +1 +  +1 +3 +3 +9 +  +3 +9 +9 +6 +  +9 +  +  +3 +3 +  +6 +  +  +  +1 +1 +  +1 +1 +  +1 +3 +3 +9 +  +3 +9 +9 +3 +  +9 +  +  +3 +  +  +3 +  +  +  +1 +1 +  +1 +5 +15 +15 +7 +7 +  +  +8 +  +  +  +  +  +  +1 +1 +  +1 +3 +9 +9 +2 +2 +  +9 +  +  +3 +  +  +  +1 +  +1 +3 +9 +9 +3 +3 +  +9 +  +  +3 +  +  +  +1 +  +1 +2 +6 +6 +  +  +  +6 +  +  +  +2 +  +  +  +2 +6 +6 +  +2 +6 +  +  +  +  +  +1 +13 +13 +13 +13 +1 +  +  +12 +  +12 +12 +27 +  +12 +13 +19 +13 +13 +  +  +  +12 +25 +25 +47 +  +  +  +12 +25 +7 +  +7 +  +7 +  +  +  +12 +34 +34 +28 +28 +27 +  +28 +3 +3 +1 +  +3 +3 +  +3 +  +  +25 +25 +  +  +34 +  +34 +34 +34 +23 +1 +  +22 +1 +  +  +32 +54 +54 +  +  +32 +17 +  +  +15 +22 +13 +13 +  +  +15 +  +  +  +  +1 +3 +3 +  +3 +2 +2 +2 +  +  +3 +3 +3 +13 +7 +7 +  +  +  +3 +13 +  +3 +3 +3 +  +  +  +3 +  +  +1 +8 +8 +1 +1 +  +7 +1 +  +6 +18 +19 +1 +1 +  +  +18 +18 +18 +12 +  +  +6 +  +18 +18 +  +  +  +  +6 +  +  +1 +13 +13 +11 +21 +21 +21 +21 +19 +  +21 +  +  +  +  +  +2 +2 +6 +6 +6 +4 +  +6 +6 +  +  +2 +  +  +  +  +1 +7 +  +  +1 +6 +  +  +1 +10 +10 +9 +18 +18 +18 +18 +17 +  +18 +  +  +  +  +  +1 +1 +3 +3 +3 +2 +  +3 +3 +  +  +1 +  +  +  +  +1 +9 +38 +25 +24 +  +25 +  +38 +46 +  +38 +  +9 +  +  +1 +6 +6 +6 +  +  +  +  +  +1 +3 +3 +9 +9 +9 +  +  +3 +  +  +1 +1 +  +1 +6 +5 +5 +  +  +5 +  +  +  +1 +  +  +  +1 +10 +10 +  +  +10 +10 +8 +  +  +2 +  +  +  +  +1 +6 +5 +5 +  +  +5 +  +  +  +1 +  +  +  +1 +10 +10 +  +  +10 +10 +8 +  +  +2 +  +  +  +  +1 +20 +3 +  +17 +1 +  +1 +45 +17 +  +45 +39 +  +45 +  +2 +2 +1 +  +  +  +43 +56 +  +  +  +  +56 +8 +  +48 +  +  +56 +2 +  +56 +  +  +  +19 +19 +  +  +  +  +  +  +  +  +37 +  +  +1 +1 +  +  +8 +  +  +132 +63 +63 +1 +  +63 +63 +63 +63 +31 +  +63 +9 +  +63 +  +63 +63 +  +  +  +37 +  +  +4 +  +  +7 +  +  +3 +3 +  +  +4 +3 +3 +  +  +3 +5 +  +  +  +19 +  +  +1 +  +1 +10 +  +  +1 +8 +  +8 +10 +10 +6 +  +4 +  +  +8 +  +  +1 +8 +2 +  +8 +8 +  +8 +  +  +  +  +  +  +  +8 +8 +  +  +  +  +  +8 +  +8 +  +  +8 +  +  +  +  +2 +  +  +2 +8 +  +  +  +2 +  +2 +  +  +1 +5 +  +  +5 +  +  +  +  +  +  +  +41 +40 +  +41 +44 +  +  +  +44 +44 +  +  +  +41 +  +  +62 +54 +33 +33 +33 +  +  +21 +  +  +  +21 +44 +  +  +21 +21 +21 +21 +  +21 +21 +44 +9 +  +  +  +21 +  +  +  +10 +  +  +  +  +  +5 +  +  +1 +2 +6 +6 +6 +6 +6 +2 +2 +  +  +4 +4 +8 +  +  +  +  +  +  +1 +1 +  +  +  +  +1 +7 +7 +7 +9 +  +7 +11 +11 +11 +11 +4 +4 +  +  +7 +1 +  +  +6 +6 +6 +6 +6 +6 +7 +  +  +  +  +7 +7 +7 +  +  +1 +2 +4 +  +  +  +1 +3 +3 +6 +  +3 +  +  +1 +2 +2 +10 +  +2 +  +  +1 +6 +6 +6 +6 +6 +6 +14 +14 +14 +14 +  +  +  +6 +  +  +  +  +1 +3 +  +  +1 +3 +3 +3 +3 +3 +9 +  +  +  +3 +2 +2 +  +  +1 +  +  +1 +1 +  +1 +1 +51 +1 +1 +  +  +  +50 +  +1 +  +  +  +1 +1 +  +  +  +  +  +  +  +  +  +  +  +  +  + 
/*!
+ * 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;
+ 
+    Iif (typeof window == 'object' && this === window) {
+        root = window;
+    }
+    else Eif (typeof global == 'object' && this === global) {
+        root = global;
+    }
+    else {
+        root = this;
+    }
+ 
+    Eif (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;
+    Eif (typeof setImmediate === 'function') {
+        _setImmediate = setImmediate;
+    }
+ 
+    Iif (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;
+        Eif (_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(null);
+        }
+        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(null);
+              }
+          }
+        }
+    };
+    async.forEach = async.each;
+ 
+    async.eachSeries = function (arr, iterator, callback) {
+        callback = callback || noop;
+        if (!arr.length) {
+            return callback(null);
+        }
+        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(null);
+                    }
+                    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(null);
+            }
+            var completed = 0;
+            var started = 0;
+            var running = 0;
+            var errored = false;
+ 
+            (function replenish () {
+                Iif (completed >= arr.length) {
+                    return callback(null);
+                }
+ 
+                while (running < limit && started < arr.length && !errored) {
+                    started += 1;
+                    running += 1;
+                    iterator(arr[started - 1], function (err) {
+                        if (err) {
+                            callback(err);
+                            errored = true;
+                            callback = noop;
+                        }
+                        else {
+                            completed += 1;
+                            running -= 1;
+                            if (completed >= arr.length) {
+                                callback(null);
+                            }
+                            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(null);
+        }
+        _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 {
+                        Iif (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(null);
+            }
+            var completed = 0;
+            var started = 0;
+            var running = 0;
+ 
+            (function replenish () {
+                Iif (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(null);
+                            }
+                            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 || null, 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) {
+                Iif (err) {
+                    callback(err);
+                }
+                else {
+                    callback(null, {value: x, criteria: criteria});
+                }
+            });
+        }, function (err, results) {
+            Iif (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(null);
+        }
+ 
+        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) {
+                Eif (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) {
+                Eif (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) {
+                Iif (err) {
+                    return callback(err);
+                }
+                async.whilst(test, iterator, callback);
+            });
+        }
+        else {
+            callback(null);
+        }
+    };
+ 
+    async.doWhilst = function (iterator, test, callback) {
+        iterator(function (err) {
+            Iif (err) {
+                return callback(err);
+            }
+            var args = _baseSlice(arguments, 1);
+            if (test.apply(null, args)) {
+                async.doWhilst(iterator, test, callback);
+            }
+            else {
+                callback(null);
+            }
+        });
+    };
+ 
+    async.until = function (test, iterator, callback) {
+        if (!test()) {
+            iterator(function (err) {
+                Iif (err) {
+                    return callback(err);
+                }
+                async.until(test, iterator, callback);
+            });
+        }
+        else {
+            callback(null);
+        }
+    };
+ 
+    async.doUntil = function (iterator, test, callback) {
+        iterator(function (err) {
+            Iif (err) {
+                return callback(err);
+            }
+            var args = _baseSlice(arguments, 1);
+            if (!test.apply(null, args)) {
+                async.doUntil(iterator, test, callback);
+            }
+            else {
+                callback(null);
+            }
+        });
+    };
+ 
+    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 () {
+                Iif (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;
+          }
+          Eif (!_isArray(data)) {
+              data = [data];
+          }
+          Iif(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);
+ 
+              Iif (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;
+                    Iif (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;
+                });
+ 
+                Iif(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);
+                Eif (typeof console !== 'undefined') {
+                    if (err) {
+                        Eif (console.error) {
+                            console.error(err);
+                        }
+                    }
+                    else Eif (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) {
+                Eif (callback) {
+                    return callback(err);
+                }
+                throw err;
+            }
+            fn(next);
+        }
+        next();
+    };
+ 
+    // Node.js
+    Eif (typeof module !== 'undefined' && module.exports) {
+        module.exports = async;
+    }
+    // AMD / RequireJS
+    else if (typeof define !== 'undefined' && define.amd) {
+        define([], function () {
+            return async;
+        });
+    }
+    // included directly via <script> tag
+    else {
+        root.async = async;
+    }
+ 
+}());
+ 
+ +
+ + + + + + diff --git a/node_modules/async/coverage/lcov-report/lib/index.html b/node_modules/async/coverage/lcov-report/lib/index.html new file mode 100644 index 0000000..2a4e913 --- /dev/null +++ b/node_modules/async/coverage/lcov-report/lib/index.html @@ -0,0 +1,73 @@ + + + + Code coverage report for lib/ + + + + + + +
+

Code coverage report for lib/

+

+ Statements: 94.13% (673 / 715)      + Branches: 85% (272 / 320)      + Functions: 94.2% (195 / 207)      + Lines: 94.36% (669 / 709)      + Ignored: none      +

+
All files » lib/
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
async.js94.13%(673 / 715)85%(272 / 320)94.2%(195 / 207)94.36%(669 / 709)
+
+
+ + + + + + diff --git a/node_modules/async/coverage/lcov-report/prettify.css b/node_modules/async/coverage/lcov-report/prettify.css new file mode 100644 index 0000000..b317a7c --- /dev/null +++ b/node_modules/async/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/node_modules/async/coverage/lcov-report/prettify.js b/node_modules/async/coverage/lcov-report/prettify.js new file mode 100644 index 0000000..ef51e03 --- /dev/null +++ b/node_modules/async/coverage/lcov-report/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/node_modules/async/coverage/lcov-report/sort-arrow-sprite.png b/node_modules/async/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..03f704a609c6fd0dbfdac63466a7d7c958b5cbf3 GIT binary patch literal 209 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qj#UE5hcO-X(i=}MX3yqDfvmM z3ZA)%>8U}fi7AzZCsS>Jii$m5978H@?Fn+^JD|Y9yzj{W`447Gxa{7*dM7nnnD-Lb z6^}Hx2)'; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + el = getNthColumn(i).querySelector('.sorter'); + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/node_modules/async/coverage/lcov.info b/node_modules/async/coverage/lcov.info new file mode 100644 index 0000000..00e08de --- /dev/null +++ b/node_modules/async/coverage/lcov.info @@ -0,0 +1,1452 @@ +TN: +SF:./lib/async.js +FN:8,(anonymous_1) +FN:11,(anonymous_2) +FN:30,(anonymous_3) +FN:35,only_once +FN:37,(anonymous_5) +FN:48,(anonymous_6) +FN:52,(anonymous_7) +FN:61,(anonymous_8) +FN:72,(anonymous_9) +FN:73,(anonymous_10) +FN:79,(anonymous_11) +FN:80,(anonymous_12) +FN:85,(anonymous_13) +FN:95,(anonymous_14) +FN:124,(anonymous_15) +FN:131,(anonymous_16) +FN:140,(anonymous_17) +FN:150,(anonymous_18) +FN:156,(anonymous_19) +FN:159,done +FN:174,(anonymous_21) +FN:180,(anonymous_22) +FN:181,(anonymous_23) +FN:202,(anonymous_24) +FN:208,(anonymous_25) +FN:210,(anonymous_26) +FN:220,replenish +FN:228,(anonymous_28) +FN:252,(anonymous_29) +FN:253,(anonymous_30) +FN:259,(anonymous_31) +FN:260,(anonymous_32) +FN:263,(anonymous_33) +FN:274,(anonymous_34) +FN:275,(anonymous_35) +FN:282,(anonymous_36) +FN:285,(anonymous_37) +FN:288,(anonymous_38) +FN:312,(anonymous_39) +FN:316,(anonymous_40) +FN:318,(anonymous_41) +FN:319,(anonymous_42) +FN:329,replenish +FN:338,(anonymous_44) +FN:341,(anonymous_45) +FN:360,(anonymous_46) +FN:361,(anonymous_47) +FN:366,(anonymous_48) +FN:367,(anonymous_49) +FN:372,(anonymous_50) +FN:373,(anonymous_51) +FN:380,(anonymous_52) +FN:381,(anonymous_53) +FN:385,(anonymous_54) +FN:386,(anonymous_55) +FN:392,(anonymous_56) +FN:393,(anonymous_57) +FN:397,(anonymous_58) +FN:404,(anonymous_59) +FN:408,(anonymous_60) +FN:414,(anonymous_61) +FN:415,(anonymous_62) +FN:416,(anonymous_63) +FN:420,(anonymous_64) +FN:429,(anonymous_65) +FN:430,(anonymous_66) +FN:438,(anonymous_67) +FN:440,(anonymous_68) +FN:443,(anonymous_69) +FN:444,(anonymous_70) +FN:450,(anonymous_71) +FN:451,(anonymous_72) +FN:453,(anonymous_73) +FN:464,(anonymous_74) +FN:466,(anonymous_75) +FN:469,(anonymous_76) +FN:470,(anonymous_77) +FN:476,(anonymous_78) +FN:477,(anonymous_79) +FN:479,(anonymous_80) +FN:487,(anonymous_81) +FN:488,(anonymous_82) +FN:489,(anonymous_83) +FN:498,(anonymous_84) +FN:505,(anonymous_85) +FN:506,(anonymous_86) +FN:507,(anonymous_87) +FN:514,(anonymous_88) +FN:521,(anonymous_89) +FN:522,(anonymous_90) +FN:523,(anonymous_91) +FN:530,(anonymous_92) +FN:537,(anonymous_93) +FN:538,(anonymous_94) +FN:539,(anonymous_95) +FN:547,(anonymous_96) +FN:552,(anonymous_97) +FN:556,(anonymous_98) +FN:563,(anonymous_99) +FN:574,(anonymous_100) +FN:577,(anonymous_101) +FN:585,(anonymous_102) +FN:587,(anonymous_103) +FN:592,(anonymous_104) +FN:602,(anonymous_105) +FN:604,(anonymous_106) +FN:611,(anonymous_107) +FN:636,(anonymous_108) +FN:637,(anonymous_109) +FN:645,(anonymous_110) +FN:656,(anonymous_111) +FN:667,(anonymous_112) +FN:668,(anonymous_113) +FN:669,(anonymous_114) +FN:670,(anonymous_115) +FN:678,(anonymous_116) +FN:687,(anonymous_117) +FN:696,(anonymous_118) +FN:697,(anonymous_119) +FN:711,(anonymous_120) +FN:720,(anonymous_121) +FN:723,(anonymous_122) +FN:725,(anonymous_123) +FN:737,(anonymous_124) +FN:738,(anonymous_125) +FN:746,(anonymous_126) +FN:752,(anonymous_127) +FN:756,(anonymous_128) +FN:760,(anonymous_129) +FN:763,(anonymous_130) +FN:765,(anonymous_131) +FN:777,(anonymous_132) +FN:778,(anonymous_133) +FN:786,(anonymous_134) +FN:792,(anonymous_135) +FN:793,(anonymous_136) +FN:794,(anonymous_137) +FN:800,(anonymous_138) +FN:808,(anonymous_139) +FN:810,(anonymous_140) +FN:817,(anonymous_141) +FN:819,(anonymous_142) +FN:820,(anonymous_143) +FN:824,(anonymous_144) +FN:831,(anonymous_145) +FN:833,(anonymous_146) +FN:845,(anonymous_147) +FN:846,(anonymous_148) +FN:860,(anonymous_149) +FN:862,(anonymous_150) +FN:874,(anonymous_151) +FN:875,(anonymous_152) +FN:889,(anonymous_153) +FN:896,_insert +FN:905,(anonymous_155) +FN:911,(anonymous_156) +FN:939,(anonymous_157) +FN:942,(anonymous_158) +FN:946,(anonymous_159) +FN:949,(anonymous_160) +FN:956,(anonymous_161) +FN:970,(anonymous_162) +FN:973,(anonymous_163) +FN:976,(anonymous_164) +FN:979,(anonymous_165) +FN:983,(anonymous_166) +FN:997,(anonymous_167) +FN:999,_compareTasks +FN:1003,_binarySearch +FN:1017,_insert +FN:1026,(anonymous_171) +FN:1032,(anonymous_172) +FN:1052,(anonymous_173) +FN:1062,(anonymous_174) +FN:1073,(anonymous_175) +FN:1077,(anonymous_176) +FN:1089,process +FN:1101,(anonymous_178) +FN:1107,(anonymous_179) +FN:1111,(anonymous_180) +FN:1120,(anonymous_181) +FN:1123,(anonymous_182) +FN:1130,(anonymous_183) +FN:1131,(anonymous_184) +FN:1133,(anonymous_185) +FN:1142,(anonymous_186) +FN:1156,(anonymous_187) +FN:1159,(anonymous_188) +FN:1162,(anonymous_189) +FN:1167,(anonymous_190) +FN:1176,(anonymous_191) +FN:1191,(anonymous_192) +FN:1192,(anonymous_193) +FN:1197,(anonymous_194) +FN:1205,(anonymous_195) +FN:1213,(anonymous_196) +FN:1215,(anonymous_197) +FN:1219,(anonymous_198) +FN:1220,(anonymous_199) +FN:1226,(anonymous_200) +FN:1232,(anonymous_201) +FN:1236,(anonymous_202) +FN:1237,(anonymous_203) +FN:1241,(anonymous_204) +FN:1257,(anonymous_205) +FN:1258,next +FN:1276,(anonymous_207) +FNF:207 +FNH:195 +FNDA:1,(anonymous_1) +FNDA:27,(anonymous_2) +FNDA:0,(anonymous_3) +FNDA:162,only_once +FNDA:162,(anonymous_5) +FNDA:0,(anonymous_6) +FNDA:249,(anonymous_7) +FNDA:76,(anonymous_8) +FNDA:54,(anonymous_9) +FNDA:54,(anonymous_10) +FNDA:4,(anonymous_11) +FNDA:7,(anonymous_12) +FNDA:0,(anonymous_13) +FNDA:237,(anonymous_14) +FNDA:0,(anonymous_15) +FNDA:0,(anonymous_16) +FNDA:219,(anonymous_17) +FNDA:37,(anonymous_18) +FNDA:99,(anonymous_19) +FNDA:95,done +FNDA:35,(anonymous_21) +FNDA:79,(anonymous_22) +FNDA:76,(anonymous_23) +FNDA:9,(anonymous_24) +FNDA:27,(anonymous_25) +FNDA:22,(anonymous_26) +FNDA:77,replenish +FNDA:77,(anonymous_28) +FNDA:5,(anonymous_29) +FNDA:1,(anonymous_30) +FNDA:7,(anonymous_31) +FNDA:7,(anonymous_32) +FNDA:1,(anonymous_33) +FNDA:5,(anonymous_34) +FNDA:1,(anonymous_35) +FNDA:6,(anonymous_36) +FNDA:6,(anonymous_37) +FNDA:0,(anonymous_38) +FNDA:9,(anonymous_39) +FNDA:9,(anonymous_40) +FNDA:9,(anonymous_41) +FNDA:1,(anonymous_42) +FNDA:20,replenish +FNDA:20,(anonymous_44) +FNDA:0,(anonymous_45) +FNDA:6,(anonymous_46) +FNDA:25,(anonymous_47) +FNDA:13,(anonymous_48) +FNDA:12,(anonymous_49) +FNDA:6,(anonymous_50) +FNDA:20,(anonymous_51) +FNDA:40,(anonymous_52) +FNDA:142,(anonymous_53) +FNDA:3,(anonymous_54) +FNDA:3,(anonymous_55) +FNDA:99,(anonymous_56) +FNDA:97,(anonymous_57) +FNDA:39,(anonymous_58) +FNDA:7,(anonymous_59) +FNDA:13,(anonymous_60) +FNDA:10,(anonymous_61) +FNDA:24,(anonymous_62) +FNDA:24,(anonymous_63) +FNDA:10,(anonymous_64) +FNDA:1,(anonymous_65) +FNDA:3,(anonymous_66) +FNDA:3,(anonymous_67) +FNDA:9,(anonymous_68) +FNDA:9,(anonymous_69) +FNDA:9,(anonymous_70) +FNDA:3,(anonymous_71) +FNDA:3,(anonymous_72) +FNDA:6,(anonymous_73) +FNDA:3,(anonymous_74) +FNDA:9,(anonymous_75) +FNDA:9,(anonymous_76) +FNDA:9,(anonymous_77) +FNDA:3,(anonymous_78) +FNDA:0,(anonymous_79) +FNDA:3,(anonymous_80) +FNDA:5,(anonymous_81) +FNDA:15,(anonymous_82) +FNDA:15,(anonymous_83) +FNDA:0,(anonymous_84) +FNDA:3,(anonymous_85) +FNDA:9,(anonymous_86) +FNDA:9,(anonymous_87) +FNDA:3,(anonymous_88) +FNDA:3,(anonymous_89) +FNDA:9,(anonymous_90) +FNDA:9,(anonymous_91) +FNDA:3,(anonymous_92) +FNDA:2,(anonymous_93) +FNDA:6,(anonymous_94) +FNDA:6,(anonymous_95) +FNDA:2,(anonymous_96) +FNDA:6,(anonymous_97) +FNDA:6,(anonymous_98) +FNDA:13,(anonymous_99) +FNDA:27,(anonymous_100) +FNDA:13,(anonymous_101) +FNDA:25,(anonymous_102) +FNDA:47,(anonymous_103) +FNDA:25,(anonymous_104) +FNDA:34,(anonymous_105) +FNDA:28,(anonymous_106) +FNDA:1,(anonymous_107) +FNDA:54,(anonymous_108) +FNDA:54,(anonymous_109) +FNDA:22,(anonymous_110) +FNDA:3,(anonymous_111) +FNDA:3,(anonymous_112) +FNDA:13,(anonymous_113) +FNDA:7,(anonymous_114) +FNDA:7,(anonymous_115) +FNDA:3,(anonymous_116) +FNDA:8,(anonymous_117) +FNDA:18,(anonymous_118) +FNDA:19,(anonymous_119) +FNDA:18,(anonymous_120) +FNDA:13,(anonymous_121) +FNDA:21,(anonymous_122) +FNDA:21,(anonymous_123) +FNDA:6,(anonymous_124) +FNDA:6,(anonymous_125) +FNDA:2,(anonymous_126) +FNDA:7,(anonymous_127) +FNDA:6,(anonymous_128) +FNDA:10,(anonymous_129) +FNDA:18,(anonymous_130) +FNDA:18,(anonymous_131) +FNDA:3,(anonymous_132) +FNDA:3,(anonymous_133) +FNDA:1,(anonymous_134) +FNDA:9,(anonymous_135) +FNDA:38,(anonymous_136) +FNDA:25,(anonymous_137) +FNDA:46,(anonymous_138) +FNDA:6,(anonymous_139) +FNDA:6,(anonymous_140) +FNDA:3,(anonymous_141) +FNDA:9,(anonymous_142) +FNDA:9,(anonymous_143) +FNDA:3,(anonymous_144) +FNDA:6,(anonymous_145) +FNDA:5,(anonymous_146) +FNDA:10,(anonymous_147) +FNDA:10,(anonymous_148) +FNDA:6,(anonymous_149) +FNDA:5,(anonymous_150) +FNDA:10,(anonymous_151) +FNDA:10,(anonymous_152) +FNDA:20,(anonymous_153) +FNDA:45,_insert +FNDA:2,(anonymous_155) +FNDA:56,(anonymous_156) +FNDA:37,(anonymous_157) +FNDA:1,(anonymous_158) +FNDA:8,(anonymous_159) +FNDA:132,(anonymous_160) +FNDA:63,(anonymous_161) +FNDA:37,(anonymous_162) +FNDA:4,(anonymous_163) +FNDA:7,(anonymous_164) +FNDA:3,(anonymous_165) +FNDA:4,(anonymous_166) +FNDA:2,(anonymous_167) +FNDA:10,_compareTasks +FNDA:8,_binarySearch +FNDA:8,_insert +FNDA:0,(anonymous_171) +FNDA:8,(anonymous_172) +FNDA:8,(anonymous_173) +FNDA:5,(anonymous_174) +FNDA:41,(anonymous_175) +FNDA:44,(anonymous_176) +FNDA:62,process +FNDA:44,(anonymous_178) +FNDA:21,(anonymous_179) +FNDA:44,(anonymous_180) +FNDA:10,(anonymous_181) +FNDA:0,(anonymous_182) +FNDA:2,(anonymous_183) +FNDA:6,(anonymous_184) +FNDA:6,(anonymous_185) +FNDA:8,(anonymous_186) +FNDA:7,(anonymous_187) +FNDA:9,(anonymous_188) +FNDA:11,(anonymous_189) +FNDA:4,(anonymous_190) +FNDA:6,(anonymous_191) +FNDA:2,(anonymous_192) +FNDA:4,(anonymous_193) +FNDA:3,(anonymous_194) +FNDA:2,(anonymous_195) +FNDA:6,(anonymous_196) +FNDA:6,(anonymous_197) +FNDA:14,(anonymous_198) +FNDA:14,(anonymous_199) +FNDA:6,(anonymous_200) +FNDA:3,(anonymous_201) +FNDA:3,(anonymous_202) +FNDA:3,(anonymous_203) +FNDA:9,(anonymous_204) +FNDA:1,(anonymous_205) +FNDA:51,next +FNDA:0,(anonymous_207) +DA:8,1 +DA:10,1 +DA:11,1 +DA:14,1 +DA:16,1 +DA:17,0 +DA:19,1 +DA:20,1 +DA:23,0 +DA:26,1 +DA:27,1 +DA:30,1 +DA:31,0 +DA:32,0 +DA:35,1 +DA:36,162 +DA:37,162 +DA:38,162 +DA:39,158 +DA:40,158 +DA:46,1 +DA:48,1 +DA:49,0 +DA:52,1 +DA:53,249 +DA:56,249 +DA:57,402 +DA:61,1 +DA:62,76 +DA:66,76 +DA:67,222 +DA:69,76 +DA:72,1 +DA:73,54 +DA:74,54 +DA:76,54 +DA:79,1 +DA:80,4 +DA:81,7 +DA:85,1 +DA:86,0 +DA:87,0 +DA:88,0 +DA:89,0 +DA:92,0 +DA:95,1 +DA:96,237 +DA:97,237 +DA:98,237 +DA:100,237 +DA:101,148 +DA:102,148 +DA:104,237 +DA:106,237 +DA:107,360 +DA:109,237 +DA:117,1 +DA:118,1 +DA:119,1 +DA:122,1 +DA:123,0 +DA:124,0 +DA:126,0 +DA:128,0 +DA:131,0 +DA:132,0 +DA:134,0 +DA:138,1 +DA:139,1 +DA:140,1 +DA:142,219 +DA:146,0 +DA:150,1 +DA:151,37 +DA:152,37 +DA:153,3 +DA:155,34 +DA:156,34 +DA:157,99 +DA:159,1 +DA:160,95 +DA:161,14 +DA:162,14 +DA:165,81 +DA:166,81 +DA:167,27 +DA:172,1 +DA:174,1 +DA:175,35 +DA:176,35 +DA:177,2 +DA:179,33 +DA:180,33 +DA:181,79 +DA:182,76 +DA:183,10 +DA:184,10 +DA:187,66 +DA:188,66 +DA:189,20 +DA:192,46 +DA:197,33 +DA:199,1 +DA:202,1 +DA:203,9 +DA:204,9 +DA:206,1 +DA:208,1 +DA:210,27 +DA:211,22 +DA:212,22 +DA:213,5 +DA:215,17 +DA:216,17 +DA:217,17 +DA:218,17 +DA:220,17 +DA:221,77 +DA:222,0 +DA:225,77 +DA:226,81 +DA:227,81 +DA:228,81 +DA:229,77 +DA:230,6 +DA:231,6 +DA:232,6 +DA:235,71 +DA:236,71 +DA:237,71 +DA:238,11 +DA:241,60 +DA:252,1 +DA:253,5 +DA:254,5 +DA:255,5 +DA:256,5 +DA:257,1 +DA:259,4 +DA:260,7 +DA:261,7 +DA:262,2 +DA:263,2 +DA:265,5 +DA:266,5 +DA:267,3 +DA:274,1 +DA:275,5 +DA:276,5 +DA:277,5 +DA:278,5 +DA:279,1 +DA:281,4 +DA:282,4 +DA:283,6 +DA:284,6 +DA:285,6 +DA:286,6 +DA:287,1 +DA:288,1 +DA:291,5 +DA:292,5 +DA:293,3 +DA:296,2 +DA:297,0 +DA:300,2 +DA:305,6 +DA:307,4 +DA:312,1 +DA:313,9 +DA:316,1 +DA:318,9 +DA:319,9 +DA:320,9 +DA:321,9 +DA:322,9 +DA:323,2 +DA:325,7 +DA:326,7 +DA:327,7 +DA:329,7 +DA:330,20 +DA:331,0 +DA:334,20 +DA:335,22 +DA:336,22 +DA:337,22 +DA:338,22 +DA:339,20 +DA:340,1 +DA:341,1 +DA:344,19 +DA:345,19 +DA:346,19 +DA:347,6 +DA:350,13 +DA:360,1 +DA:361,6 +DA:362,25 +DA:363,25 +DA:366,1 +DA:367,13 +DA:368,12 +DA:369,12 +DA:372,1 +DA:373,6 +DA:374,20 +DA:375,20 +DA:380,1 +DA:381,40 +DA:382,142 +DA:384,40 +DA:385,1 +DA:386,3 +DA:387,3 +DA:391,39 +DA:392,39 +DA:393,99 +DA:394,97 +DA:395,97 +DA:398,39 +DA:402,1 +DA:403,1 +DA:404,1 +DA:405,7 +DA:408,1 +DA:409,13 +DA:414,1 +DA:415,10 +DA:416,24 +DA:417,24 +DA:418,24 +DA:421,10 +DA:425,1 +DA:427,1 +DA:429,1 +DA:430,1 +DA:431,3 +DA:433,1 +DA:436,1 +DA:438,1 +DA:439,3 +DA:440,3 +DA:441,9 +DA:443,3 +DA:444,9 +DA:445,9 +DA:446,6 +DA:448,9 +DA:451,3 +DA:452,3 +DA:454,6 +DA:458,1 +DA:459,1 +DA:461,1 +DA:462,1 +DA:464,1 +DA:465,3 +DA:466,3 +DA:467,9 +DA:469,3 +DA:470,9 +DA:471,9 +DA:472,3 +DA:474,9 +DA:477,3 +DA:478,0 +DA:480,3 +DA:484,1 +DA:485,1 +DA:487,1 +DA:488,5 +DA:489,15 +DA:490,15 +DA:491,7 +DA:492,7 +DA:495,8 +DA:499,0 +DA:502,1 +DA:503,1 +DA:505,1 +DA:506,3 +DA:507,9 +DA:508,9 +DA:509,2 +DA:510,2 +DA:512,9 +DA:515,3 +DA:519,1 +DA:521,1 +DA:522,3 +DA:523,9 +DA:524,9 +DA:525,3 +DA:526,3 +DA:528,9 +DA:531,3 +DA:535,1 +DA:537,1 +DA:538,2 +DA:539,6 +DA:540,6 +DA:541,0 +DA:544,6 +DA:548,2 +DA:549,0 +DA:552,2 +DA:553,6 +DA:554,6 +DA:556,2 +DA:557,6 +DA:563,1 +DA:564,13 +DA:565,13 +DA:566,13 +DA:567,13 +DA:568,1 +DA:571,12 +DA:573,12 +DA:574,12 +DA:575,27 +DA:577,12 +DA:578,13 +DA:579,19 +DA:580,13 +DA:581,13 +DA:585,12 +DA:586,25 +DA:587,25 +DA:588,47 +DA:592,12 +DA:593,25 +DA:594,7 +DA:596,7 +DA:598,7 +DA:602,12 +DA:603,34 +DA:604,34 +DA:605,28 +DA:606,28 +DA:607,27 +DA:609,28 +DA:610,3 +DA:611,3 +DA:612,1 +DA:614,3 +DA:615,3 +DA:617,3 +DA:620,25 +DA:621,25 +DA:624,34 +DA:626,34 +DA:627,34 +DA:628,34 +DA:629,23 +DA:630,1 +DA:632,22 +DA:633,1 +DA:636,32 +DA:637,54 +DA:638,54 +DA:641,32 +DA:642,17 +DA:645,15 +DA:646,22 +DA:647,13 +DA:648,13 +DA:651,15 +DA:656,1 +DA:657,3 +DA:658,3 +DA:660,3 +DA:661,2 +DA:662,2 +DA:663,2 +DA:666,3 +DA:667,3 +DA:668,3 +DA:669,13 +DA:670,7 +DA:671,7 +DA:675,3 +DA:676,13 +DA:678,3 +DA:679,3 +DA:680,3 +DA:684,3 +DA:687,1 +DA:688,8 +DA:689,8 +DA:690,1 +DA:691,1 +DA:693,7 +DA:694,1 +DA:696,6 +DA:697,18 +DA:698,19 +DA:699,1 +DA:700,1 +DA:703,18 +DA:704,18 +DA:705,18 +DA:706,12 +DA:709,6 +DA:711,18 +DA:712,18 +DA:717,6 +DA:720,1 +DA:721,13 +DA:722,13 +DA:723,11 +DA:724,21 +DA:725,21 +DA:726,21 +DA:727,21 +DA:728,19 +DA:730,21 +DA:736,2 +DA:737,2 +DA:738,6 +DA:739,6 +DA:740,6 +DA:741,4 +DA:743,6 +DA:744,6 +DA:747,2 +DA:752,1 +DA:753,7 +DA:756,1 +DA:757,6 +DA:760,1 +DA:761,10 +DA:762,10 +DA:763,9 +DA:764,18 +DA:765,18 +DA:766,18 +DA:767,18 +DA:768,17 +DA:770,18 +DA:776,1 +DA:777,1 +DA:778,3 +DA:779,3 +DA:780,3 +DA:781,2 +DA:783,3 +DA:784,3 +DA:787,1 +DA:792,1 +DA:793,9 +DA:794,38 +DA:795,25 +DA:796,24 +DA:798,25 +DA:800,38 +DA:801,46 +DA:803,38 +DA:805,9 +DA:808,1 +DA:809,6 +DA:810,6 +DA:811,6 +DA:817,1 +DA:818,3 +DA:819,3 +DA:820,9 +DA:821,9 +DA:822,9 +DA:825,3 +DA:828,1 +DA:829,1 +DA:831,1 +DA:832,6 +DA:833,5 +DA:834,5 +DA:835,0 +DA:837,5 +DA:841,1 +DA:845,1 +DA:846,10 +DA:847,10 +DA:848,0 +DA:850,10 +DA:851,10 +DA:852,8 +DA:855,2 +DA:860,1 +DA:861,6 +DA:862,5 +DA:863,5 +DA:864,0 +DA:866,5 +DA:870,1 +DA:874,1 +DA:875,10 +DA:876,10 +DA:877,0 +DA:879,10 +DA:880,10 +DA:881,8 +DA:884,2 +DA:889,1 +DA:890,20 +DA:891,3 +DA:893,17 +DA:894,1 +DA:896,1 +DA:897,45 +DA:898,17 +DA:900,45 +DA:901,39 +DA:903,45 +DA:905,2 +DA:906,2 +DA:907,1 +DA:911,43 +DA:912,56 +DA:917,56 +DA:918,8 +DA:920,48 +DA:923,56 +DA:924,2 +DA:926,56 +DA:930,19 +DA:931,19 +DA:940,37 +DA:943,1 +DA:944,1 +DA:947,8 +DA:950,132 +DA:951,63 +DA:952,63 +DA:953,1 +DA:955,63 +DA:956,63 +DA:957,63 +DA:958,63 +DA:959,31 +DA:961,63 +DA:962,9 +DA:964,63 +DA:966,63 +DA:967,63 +DA:971,37 +DA:974,4 +DA:977,7 +DA:980,3 +DA:981,3 +DA:984,4 +DA:985,3 +DA:986,3 +DA:989,3 +DA:990,5 +DA:994,19 +DA:997,1 +DA:999,1 +DA:1000,10 +DA:1003,1 +DA:1004,8 +DA:1006,8 +DA:1007,10 +DA:1008,10 +DA:1009,6 +DA:1011,4 +DA:1014,8 +DA:1017,1 +DA:1018,8 +DA:1019,2 +DA:1021,8 +DA:1022,8 +DA:1024,8 +DA:1026,0 +DA:1027,0 +DA:1028,0 +DA:1032,8 +DA:1033,8 +DA:1039,8 +DA:1041,8 +DA:1042,0 +DA:1044,8 +DA:1049,2 +DA:1052,2 +DA:1053,8 +DA:1057,2 +DA:1059,2 +DA:1062,1 +DA:1063,5 +DA:1066,5 +DA:1074,41 +DA:1075,40 +DA:1077,41 +DA:1078,44 +DA:1082,44 +DA:1083,44 +DA:1084,0 +DA:1087,41 +DA:1090,62 +DA:1091,54 +DA:1092,33 +DA:1093,33 +DA:1094,33 +DA:1097,21 +DA:1101,21 +DA:1102,44 +DA:1105,21 +DA:1106,21 +DA:1107,21 +DA:1108,21 +DA:1110,21 +DA:1111,21 +DA:1112,44 +DA:1113,9 +DA:1117,21 +DA:1121,10 +DA:1124,0 +DA:1127,5 +DA:1130,1 +DA:1131,2 +DA:1132,6 +DA:1133,6 +DA:1134,6 +DA:1135,6 +DA:1136,6 +DA:1137,2 +DA:1138,2 +DA:1141,4 +DA:1142,4 +DA:1143,8 +DA:1150,1 +DA:1151,1 +DA:1156,1 +DA:1157,7 +DA:1158,7 +DA:1159,7 +DA:1160,9 +DA:1162,7 +DA:1163,11 +DA:1164,11 +DA:1165,11 +DA:1166,11 +DA:1167,4 +DA:1168,4 +DA:1171,7 +DA:1172,1 +DA:1175,6 +DA:1176,6 +DA:1177,6 +DA:1178,6 +DA:1179,6 +DA:1180,6 +DA:1181,7 +DA:1186,7 +DA:1187,7 +DA:1188,7 +DA:1191,1 +DA:1192,2 +DA:1193,4 +DA:1197,1 +DA:1198,3 +DA:1199,3 +DA:1200,6 +DA:1202,3 +DA:1205,1 +DA:1206,2 +DA:1207,2 +DA:1208,10 +DA:1210,2 +DA:1213,1 +DA:1214,6 +DA:1215,6 +DA:1216,6 +DA:1217,6 +DA:1218,6 +DA:1219,6 +DA:1220,14 +DA:1221,14 +DA:1222,14 +DA:1223,14 +DA:1227,6 +DA:1232,1 +DA:1233,3 +DA:1236,1 +DA:1237,3 +DA:1238,3 +DA:1239,3 +DA:1240,3 +DA:1241,3 +DA:1242,9 +DA:1246,3 +DA:1247,2 +DA:1248,2 +DA:1251,1 +DA:1254,1 +DA:1255,1 +DA:1257,1 +DA:1258,1 +DA:1259,51 +DA:1260,1 +DA:1261,1 +DA:1263,0 +DA:1265,50 +DA:1267,1 +DA:1271,1 +DA:1272,1 +DA:1275,0 +DA:1276,0 +DA:1277,0 +DA:1282,0 +LF:709 +LH:669 +BRDA:16,1,0,0 +BRDA:16,1,1,1 +BRDA:16,2,0,1 +BRDA:16,2,1,0 +BRDA:19,3,0,1 +BRDA:19,3,1,0 +BRDA:19,4,0,1 +BRDA:19,4,1,1 +BRDA:26,5,0,1 +BRDA:26,5,1,0 +BRDA:38,6,0,4 +BRDA:38,6,1,158 +BRDA:48,7,0,1 +BRDA:48,7,1,0 +BRDA:85,8,0,1 +BRDA:85,8,1,0 +BRDA:88,9,0,0 +BRDA:88,9,1,0 +BRDA:96,10,0,237 +BRDA:96,10,1,89 +BRDA:100,11,0,148 +BRDA:100,11,1,89 +BRDA:102,12,0,42 +BRDA:102,12,1,106 +BRDA:118,13,0,1 +BRDA:118,13,1,0 +BRDA:122,14,0,0 +BRDA:122,14,1,1 +BRDA:122,15,0,1 +BRDA:122,15,1,1 +BRDA:123,16,0,0 +BRDA:123,16,1,0 +BRDA:139,17,0,1 +BRDA:139,17,1,0 +BRDA:151,18,0,37 +BRDA:151,18,1,3 +BRDA:152,19,0,3 +BRDA:152,19,1,34 +BRDA:160,20,0,14 +BRDA:160,20,1,81 +BRDA:166,21,0,27 +BRDA:166,21,1,54 +BRDA:175,22,0,35 +BRDA:175,22,1,1 +BRDA:176,23,0,2 +BRDA:176,23,1,33 +BRDA:182,24,0,10 +BRDA:182,24,1,66 +BRDA:188,25,0,20 +BRDA:188,25,1,46 +BRDA:211,26,0,22 +BRDA:211,26,1,1 +BRDA:212,27,0,5 +BRDA:212,27,1,17 +BRDA:212,28,0,22 +BRDA:212,28,1,19 +BRDA:221,29,0,0 +BRDA:221,29,1,77 +BRDA:225,30,0,158 +BRDA:225,30,1,135 +BRDA:225,30,2,87 +BRDA:229,31,0,6 +BRDA:229,31,1,71 +BRDA:237,32,0,11 +BRDA:237,32,1,60 +BRDA:253,33,0,5 +BRDA:253,33,1,1 +BRDA:254,34,0,5 +BRDA:254,34,1,4 +BRDA:256,35,0,1 +BRDA:256,35,1,4 +BRDA:261,36,0,2 +BRDA:261,36,1,5 +BRDA:266,37,0,3 +BRDA:266,37,1,2 +BRDA:275,38,0,5 +BRDA:275,38,1,1 +BRDA:278,39,0,1 +BRDA:278,39,1,4 +BRDA:286,40,0,1 +BRDA:286,40,1,5 +BRDA:292,41,0,3 +BRDA:292,41,1,2 +BRDA:296,42,0,0 +BRDA:296,42,1,2 +BRDA:319,43,0,9 +BRDA:319,43,1,1 +BRDA:322,44,0,2 +BRDA:322,44,1,7 +BRDA:322,45,0,9 +BRDA:322,45,1,8 +BRDA:330,46,0,0 +BRDA:330,46,1,20 +BRDA:334,47,0,42 +BRDA:334,47,1,35 +BRDA:339,48,0,1 +BRDA:339,48,1,19 +BRDA:346,49,0,6 +BRDA:346,49,1,13 +BRDA:384,50,0,1 +BRDA:384,50,1,39 +BRDA:421,51,0,10 +BRDA:421,51,1,7 +BRDA:445,52,0,6 +BRDA:445,52,1,3 +BRDA:471,53,0,3 +BRDA:471,53,1,6 +BRDA:490,54,0,7 +BRDA:490,54,1,8 +BRDA:508,55,0,2 +BRDA:508,55,1,7 +BRDA:524,56,0,3 +BRDA:524,56,1,6 +BRDA:540,57,0,0 +BRDA:540,57,1,6 +BRDA:548,58,0,0 +BRDA:548,58,1,2 +BRDA:554,59,0,3 +BRDA:554,59,1,3 +BRDA:554,60,0,3 +BRDA:554,60,1,0 +BRDA:564,61,0,13 +BRDA:564,61,1,4 +BRDA:567,62,0,1 +BRDA:567,62,1,12 +BRDA:579,63,0,13 +BRDA:579,63,1,6 +BRDA:593,64,0,7 +BRDA:593,64,1,18 +BRDA:603,65,0,20 +BRDA:603,65,1,14 +BRDA:606,66,0,27 +BRDA:606,66,1,1 +BRDA:609,67,0,3 +BRDA:609,67,1,25 +BRDA:624,68,0,34 +BRDA:624,68,1,0 +BRDA:629,69,0,1 +BRDA:629,69,1,22 +BRDA:632,70,0,1 +BRDA:632,70,1,21 +BRDA:632,71,0,22 +BRDA:632,71,1,5 +BRDA:637,72,0,54 +BRDA:637,72,1,30 +BRDA:638,73,0,54 +BRDA:638,73,1,43 +BRDA:641,74,0,17 +BRDA:641,74,1,15 +BRDA:646,75,0,13 +BRDA:646,75,1,9 +BRDA:660,76,0,2 +BRDA:660,76,1,1 +BRDA:666,77,0,3 +BRDA:666,77,1,0 +BRDA:671,78,0,7 +BRDA:671,78,1,5 +BRDA:680,79,0,3 +BRDA:680,79,1,2 +BRDA:684,80,0,2 +BRDA:684,80,1,1 +BRDA:688,81,0,8 +BRDA:688,81,1,3 +BRDA:689,82,0,1 +BRDA:689,82,1,7 +BRDA:693,83,0,1 +BRDA:693,83,1,6 +BRDA:698,84,0,1 +BRDA:698,84,1,18 +BRDA:705,85,0,12 +BRDA:705,85,1,6 +BRDA:721,86,0,13 +BRDA:721,86,1,2 +BRDA:722,87,0,11 +BRDA:722,87,1,2 +BRDA:724,88,0,21 +BRDA:724,88,1,0 +BRDA:727,89,0,19 +BRDA:727,89,1,2 +BRDA:740,90,0,4 +BRDA:740,90,1,2 +BRDA:761,91,0,10 +BRDA:761,91,1,1 +BRDA:762,92,0,9 +BRDA:762,92,1,1 +BRDA:764,93,0,18 +BRDA:764,93,1,0 +BRDA:767,94,0,17 +BRDA:767,94,1,1 +BRDA:780,95,0,2 +BRDA:780,95,1,1 +BRDA:795,96,0,24 +BRDA:795,96,1,1 +BRDA:801,97,0,29 +BRDA:801,97,1,17 +BRDA:821,98,0,9 +BRDA:821,98,1,3 +BRDA:832,99,0,5 +BRDA:832,99,1,1 +BRDA:834,100,0,0 +BRDA:834,100,1,5 +BRDA:847,101,0,0 +BRDA:847,101,1,10 +BRDA:851,102,0,8 +BRDA:851,102,1,2 +BRDA:861,103,0,5 +BRDA:861,103,1,1 +BRDA:863,104,0,0 +BRDA:863,104,1,5 +BRDA:876,105,0,0 +BRDA:876,105,1,10 +BRDA:880,106,0,8 +BRDA:880,106,1,2 +BRDA:890,107,0,3 +BRDA:890,107,1,17 +BRDA:893,108,0,1 +BRDA:893,108,1,16 +BRDA:897,109,0,17 +BRDA:897,109,1,28 +BRDA:900,110,0,39 +BRDA:900,110,1,6 +BRDA:903,111,0,2 +BRDA:903,111,1,43 +BRDA:906,112,0,1 +BRDA:906,112,1,1 +BRDA:914,113,0,23 +BRDA:914,113,1,33 +BRDA:917,114,0,8 +BRDA:917,114,1,48 +BRDA:923,115,0,2 +BRDA:923,115,1,54 +BRDA:923,116,0,56 +BRDA:923,116,1,9 +BRDA:950,117,0,63 +BRDA:950,117,1,69 +BRDA:950,118,0,132 +BRDA:950,118,1,125 +BRDA:950,118,2,103 +BRDA:952,119,0,1 +BRDA:952,119,1,62 +BRDA:952,120,0,63 +BRDA:952,120,1,5 +BRDA:958,121,0,31 +BRDA:958,121,1,32 +BRDA:961,122,0,9 +BRDA:961,122,1,54 +BRDA:961,123,0,63 +BRDA:961,123,1,34 +BRDA:980,124,0,0 +BRDA:980,124,1,3 +BRDA:984,125,0,1 +BRDA:984,125,1,3 +BRDA:1008,126,0,6 +BRDA:1008,126,1,4 +BRDA:1018,127,0,2 +BRDA:1018,127,1,6 +BRDA:1021,128,0,8 +BRDA:1021,128,1,0 +BRDA:1024,129,0,0 +BRDA:1024,129,1,8 +BRDA:1027,130,0,0 +BRDA:1027,130,1,0 +BRDA:1036,131,0,8 +BRDA:1036,131,1,0 +BRDA:1041,132,0,0 +BRDA:1041,132,1,8 +BRDA:1041,133,0,8 +BRDA:1041,133,1,0 +BRDA:1074,134,0,40 +BRDA:1074,134,1,1 +BRDA:1080,135,0,9 +BRDA:1080,135,1,35 +BRDA:1083,136,0,0 +BRDA:1083,136,1,44 +BRDA:1083,137,0,44 +BRDA:1083,137,1,0 +BRDA:1090,138,0,8 +BRDA:1090,138,1,54 +BRDA:1091,139,0,33 +BRDA:1091,139,1,21 +BRDA:1092,140,0,3 +BRDA:1092,140,1,30 +BRDA:1092,141,0,33 +BRDA:1092,141,1,30 +BRDA:1097,142,0,21 +BRDA:1097,142,1,0 +BRDA:1105,143,0,0 +BRDA:1105,143,1,21 +BRDA:1112,144,0,9 +BRDA:1112,144,1,35 +BRDA:1135,145,0,6 +BRDA:1135,145,1,0 +BRDA:1136,146,0,2 +BRDA:1136,146,1,4 +BRDA:1137,147,0,2 +BRDA:1137,147,1,0 +BRDA:1141,148,0,4 +BRDA:1141,148,1,0 +BRDA:1159,149,0,7 +BRDA:1159,149,1,6 +BRDA:1166,150,0,4 +BRDA:1166,150,1,7 +BRDA:1171,151,0,1 +BRDA:1171,151,1,6 +BRDA:1193,152,0,4 +BRDA:1193,152,1,1 +BRDA:1246,153,0,2 +BRDA:1246,153,1,1 +BRDA:1259,154,0,1 +BRDA:1259,154,1,50 +BRDA:1260,155,0,1 +BRDA:1260,155,1,0 +BRDA:1271,156,0,1 +BRDA:1271,156,1,0 +BRDA:1271,157,0,1 +BRDA:1271,157,1,1 +BRDA:1275,158,0,0 +BRDA:1275,158,1,0 +BRDA:1275,159,0,0 +BRDA:1275,159,1,0 +BRF:320 +BRH:272 +end_of_record diff --git a/node_modules/async/coverage/lib/async.js.html b/node_modules/async/coverage/lib/async.js.html new file mode 100644 index 0000000..d1ba212 --- /dev/null +++ b/node_modules/async/coverage/lib/async.js.html @@ -0,0 +1,3597 @@ + + + + Code coverage report for lib/async.js + + + + + + +
+

Code coverage report for lib/async.js

+

+ Statements: 94.88% (611 / 644)      + Branches: 86.91% (239 / 275)      + Functions: 95.41% (187 / 196)      + Lines: 94.85% (608 / 641)      + Ignored: none      +

+
All files » lib/ » async.js
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334 +335 +336 +337 +338 +339 +340 +341 +342 +343 +344 +345 +346 +347 +348 +349 +350 +351 +352 +353 +354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 +366 +367 +368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +378 +379 +380 +381 +382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 +422 +423 +424 +425 +426 +427 +428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467 +468 +469 +470 +471 +472 +473 +474 +475 +476 +477 +478 +479 +480 +481 +482 +483 +484 +485 +486 +487 +488 +489 +490 +491 +492 +493 +494 +495 +496 +497 +498 +499 +500 +501 +502 +503 +504 +505 +506 +507 +508 +509 +510 +511 +512 +513 +514 +515 +516 +517 +518 +519 +520 +521 +522 +523 +524 +525 +526 +527 +528 +529 +530 +531 +532 +533 +534 +535 +536 +537 +538 +539 +540 +541 +542 +543 +544 +545 +546 +547 +548 +549 +550 +551 +552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 +571 +572 +573 +574 +575 +576 +577 +578 +579 +580 +581 +582 +583 +584 +585 +586 +587 +588 +589 +590 +591 +592 +593 +594 +595 +596 +597 +598 +599 +600 +601 +602 +603 +604 +605 +606 +607 +608 +609 +610 +611 +612 +613 +614 +615 +616 +617 +618 +619 +620 +621 +622 +623 +624 +625 +626 +627 +628 +629 +630 +631 +632 +633 +634 +635 +636 +637 +638 +639 +640 +641 +642 +643 +644 +645 +646 +647 +648 +649 +650 +651 +652 +653 +654 +655 +656 +657 +658 +659 +660 +661 +662 +663 +664 +665 +666 +667 +668 +669 +670 +671 +672 +673 +674 +675 +676 +677 +678 +679 +680 +681 +682 +683 +684 +685 +686 +687 +688 +689 +690 +691 +692 +693 +694 +695 +696 +697 +698 +699 +700 +701 +702 +703 +704 +705 +706 +707 +708 +709 +710 +711 +712 +713 +714 +715 +716 +717 +718 +719 +720 +721 +722 +723 +724 +725 +726 +727 +728 +729 +730 +731 +732 +733 +734 +735 +736 +737 +738 +739 +740 +741 +742 +743 +744 +745 +746 +747 +748 +749 +750 +751 +752 +753 +754 +755 +756 +757 +758 +759 +760 +761 +762 +763 +764 +765 +766 +767 +768 +769 +770 +771 +772 +773 +774 +775 +776 +777 +778 +779 +780 +781 +782 +783 +784 +785 +786 +787 +788 +789 +790 +791 +792 +793 +794 +795 +796 +797 +798 +799 +800 +801 +802 +803 +804 +805 +806 +807 +808 +809 +810 +811 +812 +813 +814 +815 +816 +817 +818 +819 +820 +821 +822 +823 +824 +825 +826 +827 +828 +829 +830 +831 +832 +833 +834 +835 +836 +837 +838 +839 +840 +841 +842 +843 +844 +845 +846 +847 +848 +849 +850 +851 +852 +853 +854 +855 +856 +857 +858 +859 +860 +861 +862 +863 +864 +865 +866 +867 +868 +869 +870 +871 +872 +873 +874 +875 +876 +877 +878 +879 +880 +881 +882 +883 +884 +885 +886 +887 +888 +889 +890 +891 +892 +893 +894 +895 +896 +897 +898 +899 +900 +901 +902 +903 +904 +905 +906 +907 +908 +909 +910 +911 +912 +913 +914 +915 +916 +917 +918 +919 +920 +921 +922 +923 +924 +925 +926 +927 +928 +929 +930 +931 +932 +933 +934 +935 +936 +937 +938 +939 +940 +941 +942 +943 +944 +945 +946 +947 +948 +949 +950 +951 +952 +953 +954 +955 +956 +957 +958 +959 +960 +961 +962 +963 +964 +965 +966 +967 +968 +969 +970 +971 +972 +973 +974 +975 +976 +977 +978 +979 +980 +981 +982 +983 +984 +985 +986 +987 +988 +989 +990 +991 +992 +993 +994 +995 +996 +997 +998 +999 +1000 +1001 +1002 +1003 +1004 +1005 +1006 +1007 +1008 +1009 +1010 +1011 +1012 +1013 +1014 +1015 +1016 +1017 +1018 +1019 +1020 +1021 +1022 +1023 +1024 +1025 +1026 +1027 +1028 +1029 +1030 +1031 +1032 +1033 +1034 +1035 +1036 +1037 +1038 +1039 +1040 +1041 +1042 +1043 +1044 +1045 +1046 +1047 +1048 +1049 +1050 +1051 +1052 +1053 +1054 +1055 +1056 +1057 +1058 +1059 +1060 +1061 +1062 +1063 +1064 +1065 +1066 +1067 +1068 +1069 +1070 +1071 +1072 +1073 +1074 +1075 +1076 +1077 +1078 +1079 +1080 +1081 +1082 +1083 +1084 +1085 +1086 +1087 +1088 +1089 +1090 +1091 +1092 +1093 +1094 +1095 +1096 +1097 +1098 +1099 +1100 +1101 +1102 +1103 +1104 +1105 +1106 +1107 +1108 +1109 +1110 +1111 +1112 +1113 +1114 +1115 +1116 +1117 +1118 +1119 +1120 +1121 +1122 +1123 +1124 +1125 +1126 +1127 +1128 +1129 +1130 +1131 +1132 +1133 +1134 +1135 +1136 +1137 +1138 +1139 +1140 +1141 +1142 +1143 +1144 +1145 +1146 +1147 +1148 +1149 +1150 +1151 +1152 +1153 +1154 +1155 +1156 +1157 +1158 +1159 +1160 +1161 +1162 +1163 +1164 +1165 +1166 +1167 +1168 +1169 +1170 +1171 +1172 +1173 +1174 +1175 +1176 +1177 +1178 +1179 +1180 +1181 +1182 +1183 +1184 +1185  +  +  +  +  +  +  +1 +  +1 +1 +  +  +1 +  +1 +  +  +1 +1 +  +  +  +  +  +1 +1 +  +  +1 +  +  +  +  +1 +200 +200 +200 +196 +196 +  +  +  +1 +168 +168 +176 +157 +157 +  +  +  +  +  +1 +  +1 +  +  +  +1 +138 +  +  +  +  +  +  +  +1 +39 +  +  +  +  +1 +328 +  +  +328 +480 +  +  +  +1 +104 +  +  +  +104 +148 +  +104 +  +  +1 +56 +54 +  +56 +  +  +1 +5 +11 +  +  +  +1 +  +  +  +  +  +  +  +  +  +1 +76 +76 +76 +76 +61 +61 +243 +243 +  +  +15 +15 +15 +53 +53 +  +  +  +  +1 +50259 +50259 +50259 +  +50259 +151 +151 +  +50259 +  +50259 +50299 +  +50259 +  +  +1 +19 +59 +  +  +  +  +  +  +  +  +1 +1 +1 +  +  +1 +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1 +1 +1 +  +50236 +  +  +  +  +  +  +  +1 +  +5 +  +  +1 +  +5 +  +  +  +1 +  +9 +  +  +1 +  +45 +45 +45 +45 +45 +6 +  +39 +109 +  +1 +105 +16 +  +  +89 +89 +31 +  +  +  +  +  +1 +  +44 +44 +44 +1 +123 +123 +123 +29 +  +94 +90 +11 +  +  +79 +20 +  +  +59 +  +  +  +94 +  +44 +  +  +  +  +1 +  +9 +  +  +1 +  +32 +32 +32 +32 +32 +3 +  +29 +29 +29 +  +29 +119 +12 +  +  +107 +173 +173 +71 +71 +17 +  +71 +  +102 +102 +97 +97 +7 +7 +  +  +90 +  +  +  +  +  +  +  +  +1 +5 +19 +  +  +1 +8 +8 +  +  +1 +5 +12 +  +  +  +1 +25 +25 +25 +69 +67 +67 +  +  +25 +  +  +  +1 +1 +1 +8 +  +  +1 +8 +  +  +  +  +1 +  +  +11 +26 +25 +25 +  +  +10 +  +  +  +1 +  +1 +3 +  +1 +  +  +1 +3 +3 +9 +  +3 +9 +9 +6 +  +9 +  +  +3 +3 +  +6 +  +  +  +  +1 +  +  +1 +  +  +1 +3 +3 +9 +  +3 +9 +9 +3 +  +9 +  +  +3 +  +  +3 +  +  +  +1 +1 +  +1 +5 +15 +15 +7 +7 +  +  +8 +  +  +  +  +  +  +1 +1 +  +1 +  +3 +9 +9 +2 +2 +  +9 +  +  +3 +  +  +  +1 +  +3 +9 +9 +3 +3 +  +9 +  +  +3 +  +  +  +1 +2 +6 +6 +  +  +  +6 +  +  +  +2 +  +  +  +2 +6 +  +  +  +  +  +1 +6 +6 +  +  +  +1 +14 +14 +14 +14 +1 +  +  +13 +  +13 +1 +28 +  +1 +13 +19 +13 +13 +  +  +  +1 +25 +25 +47 +  +  +  +13 +25 +7 +  +  +  +13 +36 +1 +30 +30 +29 +  +30 +5 +5 +1 +  +5 +5 +  +  +25 +25 +  +  +36 +  +36 +36 +36 +23 +1 +  +22 +1 +  +  +1 +56 +54 +  +  +34 +19 +  +  +15 +  +1 +22 +13 +13 +  +  +  +  +  +1 +3 +3 +  +3 +2 +2 +2 +  +  +3 +  +1 +1 +13 +7 +7 +  +  +  +  +3 +13 +  +3 +3 +3 +  +  +  +  +3 +  +  +1 +8 +8 +1 +1 +  +7 +1 +  +1 +18 +19 +1 +  +  +18 +18 +18 +12 +  +  +6 +  +18 +  +  +  +6 +  +  +1 +13 +13 +  +13 +27 +27 +27 +23 +  +27 +27 +  +  +13 +  +  +  +1 +7 +  +  +1 +6 +  +  +1 +10 +10 +  +10 +21 +21 +21 +19 +  +21 +21 +  +  +10 +  +  +  +1 +1 +1 +25 +24 +  +25 +  +38 +46 +  +38 +  +9 +  +  +1 +6 +6 +6 +  +  +  +  +  +1 +3 +3 +9 +9 +9 +  +  +3 +  +  +1 +1 +  +1 +6 +5 +5 +  +  +5 +  +  +  +1 +  +  +  +1 +10 +10 +  +  +10 +10 +8 +  +  +2 +  +  +  +  +1 +6 +5 +5 +  +  +5 +  +  +  +1 +  +  +  +1 +10 +10 +  +  +10 +10 +8 +  +  +2 +  +  +  +  +1 +27 +3 +  +24 +1 +  +1 +92 +1 +  +91 +91 +84 +  +91 +  +2 +2 +  +  +89 +105 +  +  +  +  +105 +8 +  +97 +  +  +105 +28 +  +105 +  +  +  +26 +26 +  +  +  +  +  +  +  +  +84 +  +  +1 +1 +  +  +8 +  +  +207 +89 +  +  +  +89 +112 +  +  +89 +30 +  +89 +89 +89 +  +  +1 +89 +89 +89 +112 +  +89 +27 +  +89 +  +  +  +50 +  +  +5 +  +  +9 +  +  +3 +  +  +4 +3 +3 +  +  +3 +5 +  +  +  +26 +  +  +1 +21 +63 +  +  +20 +  +  +1 +  +1 +10 +  +  +1 +8 +  +8 +10 +10 +6 +  +4 +  +  +8 +  +  +1 +8 +  +  +8 +8 +8 +  +8 +  +  +  +  +  +8 +8 +  +  +  +  +  +8 +  +8 +2 +  +8 +  +  +  +  +2 +  +  +2 +8 +  +  +  +2 +  +2 +  +  +1 +6 +  +  +1 +2 +6 +6 +6 +6 +6 +2 +2 +  +  +4 +4 +8 +  +  +  +  +  +  +1 +1 +  +  +  +  +1 +7 +7 +7 +9 +  +1 +11 +11 +11 +11 +4 +4 +  +  +7 +1 +  +  +6 +6 +6 +6 +6 +6 +7 +  +  +  +  +7 +7 +7 +  +  +1 +2 +4 +  +  +  +1 +3 +3 +6 +  +3 +  +  +1 +2 +2 +10 +  +2 +  +  +1 +7 +7 +7 +7 +  +7 +7 +6 +  +1 +  +  +7 +16 +15 +15 +15 +  +  +  +6 +  +  +  +  +1 +3 +  +  +  +1 +1 +3 +3 +3 +3 +9 +  +  +  +3 +2 +2 +  +  +1 +  +  +  +1 +2 +2 +  +1 +1 +1 +  +  +  +1 +2 +2 +1 +50052 +2 +  +50050 +  +2 +  +  +1 +24 +50072 +50072 +50072 +50070 +50070 +50017 +50017 +  +  +53 +  +  +50072 +50072 +50072 +  +  +  +1 +  +  +1 +1 +  +  +  +  +  +  +  +  +  +  +  +  +  + 
/*!
+ * async
+ * https://github.com/caolan/async
+ *
+ * Copyright 2010-2014 Caolan McMahon
+ * Released under the MIT license
+ */
+(function () {
+ 
+    var async = {};
+    function noop() {}
+ 
+    // global on the server, window in the browser
+    var root, previous_async;
+ 
+    Iif (typeof window == 'object' && this === window) {
+        root = window;
+    }
+    else Eif (typeof global == 'object' && this === global) {
+        root = global;
+    }
+    else {
+        root = this;
+    }
+ 
+    Eif (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(this, arguments);
+        };
+    }
+ 
+    function _once(fn) {
+        var called = false;
+        return function() {
+            if (called) return;
+            called = true;
+            fn.apply(this, arguments);
+        };
+    }
+ 
+    //// cross-browser compatiblity functions ////
+ 
+    var _toString = Object.prototype.toString;
+ 
+    var _isArray = Array.isArray || function (obj) {
+        return _toString.call(obj) === '[object Array]';
+    };
+ 
+    function _isArrayLike(arr) {
+        return _isArray(arr) || (
+            // has a positive integer length property
+            typeof arr.length === "number" &&
+            arr.length >= 0 &&
+            arr.length % 1 === 0
+        );
+    }
+ 
+    function _each(coll, iterator) {
+        return _isArrayLike(coll) ?
+            _arrayEach(coll, iterator) :
+            _forEachOf(coll, iterator);
+    }
+ 
+    function _arrayEach(arr, iterator) {
+      var index = -1,
+          length = arr.length;
+ 
+      while (++index < length) {
+        iterator(arr[index], index, arr);
+      }
+    }
+ 
+    function _map(arr, iterator) {
+      var index = -1,
+          length = arr.length,
+          result = Array(length);
+ 
+      while (++index < length) {
+        result[index] = iterator(arr[index], index, arr);
+      }
+      return result;
+    }
+ 
+    function _reduce(arr, iterator, memo) {
+        _arrayEach(arr, function (x, i, a) {
+            memo = iterator(memo, x, i, a);
+        });
+        return memo;
+    }
+ 
+    function _forEachOf(object, iterator) {
+        _arrayEach(_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;
+    };
+ 
+    function _keyIterator(coll) {
+        var i = -1;
+        var len;
+        var keys;
+        if (_isArrayLike(coll)) {
+            len = coll.length;
+            return function next() {
+                i++;
+                return i < len ? i : null;
+            };
+        } else {
+            keys = _keys(coll);
+            len = keys.length;
+            return function next() {
+                i++;
+                return i < len ? keys[i] : null;
+            };
+        }
+    }
+ 
+    function _baseSlice(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;
+    }
+ 
+    function _withoutIndex(iterator) {
+        return function (value, index, callback) {
+            return iterator(value, callback);
+        };
+    }
+ 
+    //// exported async module functions ////
+ 
+    //// nextTick implementation with browser-compatible fallback ////
+ 
+    // capture the global reference to guard against fakeTimer mocks
+    var _setImmediate;
+    Eif (typeof setImmediate === 'function') {
+        _setImmediate = setImmediate;
+    }
+ 
+    Iif (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;
+        Eif (_setImmediate) {
+            async.setImmediate = function (fn) {
+              // not a direct alias for IE10 compatibility
+              _setImmediate(fn);
+            };
+        }
+        else {
+            async.setImmediate = async.nextTick;
+        }
+    }
+ 
+    async.forEach =
+    async.each = function (arr, iterator, callback) {
+        return async.eachOf(arr, _withoutIndex(iterator), callback);
+    };
+ 
+    async.forEachSeries =
+    async.eachSeries = function (arr, iterator, callback) {
+        return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
+    };
+ 
+ 
+    async.forEachLimit =
+    async.eachLimit = function (arr, limit, iterator, callback) {
+        return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
+    };
+ 
+    async.forEachOf =
+    async.eachOf = function (object, iterator, callback) {
+        callback = _once(callback || noop);
+        object = object || [];
+        var size = object.length || _keys(object).length;
+        var completed = 0;
+        if (!size) {
+            return callback(null);
+        }
+        _each(object, function (value, key) {
+            iterator(object[key], key, only_once(done));
+        });
+        function done(err) {
+          if (err) {
+              callback(err);
+          }
+          else {
+              completed += 1;
+              if (completed >= size) {
+                  callback(null);
+              }
+          }
+        }
+    };
+ 
+    async.forEachOfSeries =
+    async.eachOfSeries = function (obj, iterator, callback) {
+        callback = _once(callback || noop);
+        obj = obj || [];
+        var nextKey = _keyIterator(obj);
+        function iterate() {
+            var sync = true;
+            var key = nextKey();
+            if (key === null) {
+                return callback(null);
+            }
+            iterator(obj[key], key, function (err) {
+                if (err) {
+                    callback(err);
+                }
+                else {
+                    if (sync) {
+                        async.nextTick(iterate);
+                    }
+                    else {
+                        iterate();
+                    }
+                }
+            });
+            sync = false;
+        }
+        iterate();
+    };
+ 
+ 
+ 
+    async.forEachOfLimit =
+    async.eachOfLimit = function (obj, limit, iterator, callback) {
+        _eachOfLimit(limit)(obj, iterator, callback);
+    };
+ 
+    function _eachOfLimit(limit) {
+ 
+        return function (obj, iterator, callback) {
+            callback = _once(callback || noop);
+            obj = obj || [];
+            var nextKey = _keyIterator(obj);
+            if (limit <= 0) {
+                return callback(null);
+            }
+            var done = false;
+            var running = 0;
+            var errored = false;
+ 
+            (function replenish () {
+                if (done && running <= 0) {
+                    return callback(null);
+                }
+ 
+                while (running < limit && !errored) {
+                    var key = nextKey();
+                    if (key === null) {
+                        done = true;
+                        if (running <= 0) {
+                            callback(null);
+                        }
+                        return;
+                    }
+                    running += 1;
+                    iterator(obj[key], key, function (err) {
+                        running -= 1;
+                        if (err) {
+                            callback(err);
+                            errored = true;
+                        }
+                        else {
+                            replenish();
+                        }
+                    });
+                }
+            })();
+        };
+    }
+ 
+ 
+    function doParallel(fn) {
+        return function (obj, iterator, callback) {
+            return fn(async.eachOf, obj, iterator, callback);
+        };
+    }
+    function doParallelLimit(limit, fn) {
+        return function (obj, iterator, callback) {
+            return fn(_eachOfLimit(limit), obj, iterator, callback);
+        };
+    }
+    function doSeries(fn) {
+        return function (obj, iterator, callback) {
+            return fn(async.eachOfSeries, obj, iterator, callback);
+        };
+    }
+ 
+    function _asyncMap(eachfn, arr, iterator, callback) {
+        callback = _once(callback || noop);
+        var results = [];
+        eachfn(arr, function (value, index, callback) {
+            iterator(value, function (err, v) {
+                results[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);
+    };
+ 
+    function _mapLimit(limit) {
+        return doParallelLimit(limit, _asyncMap);
+    }
+ 
+    // reduce only has a series version, as doing reduce in parallel won't
+    // work in many situations.
+    async.inject =
+    async.foldl =
+    async.reduce = function (arr, memo, iterator, callback) {
+        async.eachOfSeries(arr, function (x, i, callback) {
+            iterator(memo, x, function (err, v) {
+                memo = v;
+                callback(err);
+            });
+        }, function (err) {
+            callback(err || null, memo);
+        });
+    };
+ 
+    async.foldr =
+    async.reduceRight = function (arr, memo, iterator, callback) {
+        var reversed = _map(arr, function (x) {
+            return x;
+        }).reverse();
+        async.reduce(reversed, memo, iterator, callback);
+    };
+ 
+    function _filter(eachfn, arr, iterator, callback) {
+        var results = [];
+        arr = _map(arr, function (x, i) {
+            return {index: i, value: x};
+        });
+        eachfn(arr, function (x, index, callback) {
+            iterator(x.value, function (v) {
+                if (v) {
+                    results.push(x);
+                }
+                callback();
+            });
+        }, function () {
+            callback(_map(results.sort(function (a, b) {
+                return a.index - b.index;
+            }), function (x) {
+                return x.value;
+            }));
+        });
+    }
+ 
+    async.select =
+    async.filter = doParallel(_filter);
+ 
+    async.selectSeries =
+    async.filterSeries = doSeries(_filter);
+ 
+    function _reject(eachfn, arr, iterator, callback) {
+        var results = [];
+        arr = _map(arr, function (x, i) {
+            return {index: i, value: x};
+        });
+        eachfn(arr, function (x, index, callback) {
+            iterator(x.value, function (v) {
+                if (!v) {
+                    results.push(x);
+                }
+                callback();
+            });
+        }, function () {
+            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);
+ 
+    function _detect(eachfn, arr, iterator, main_callback) {
+        eachfn(arr, function (x, index, callback) {
+            iterator(x, function (result) {
+                if (result) {
+                    main_callback(x);
+                    main_callback = noop;
+                }
+                else {
+                    callback();
+                }
+            });
+        }, function () {
+            main_callback();
+        });
+    }
+    async.detect = doParallel(_detect);
+    async.detectSeries = doSeries(_detect);
+ 
+    async.any =
+    async.some = function (arr, iterator, main_callback) {
+        async.eachOf(arr, function (x, _, callback) {
+            iterator(x, function (v) {
+                if (v) {
+                    main_callback(true);
+                    main_callback = noop;
+                }
+                callback();
+            });
+        }, function () {
+            main_callback(false);
+        });
+    };
+ 
+    async.all =
+    async.every = function (arr, iterator, main_callback) {
+        async.eachOf(arr, function (x, _, callback) {
+            iterator(x, function (v) {
+                if (!v) {
+                    main_callback(false);
+                    main_callback = noop;
+                }
+                callback();
+            });
+        }, function () {
+            main_callback(true);
+        });
+    };
+ 
+    async.sortBy = function (arr, iterator, callback) {
+        async.map(arr, function (x, callback) {
+            iterator(x, function (err, criteria) {
+                Iif (err) {
+                    callback(err);
+                }
+                else {
+                    callback(null, {value: x, criteria: criteria});
+                }
+            });
+        }, function (err, results) {
+            Iif (err) {
+                return callback(err);
+            }
+            else {
+                callback(null, _map(results.sort(comparator), function (x) {
+                    return x.value;
+                }));
+            }
+ 
+        });
+ 
+        function comparator(left, right) {
+            var a = left.criteria, b = right.criteria;
+            return a < b ? -1 : a > b ? 1 : 0;
+        }
+    };
+ 
+    async.auto = function (tasks, callback) {
+        callback = _once(callback || noop);
+        var keys = _keys(tasks);
+        var remainingTasks = keys.length;
+        if (!remainingTasks) {
+            return callback(null);
+        }
+ 
+        var results = {};
+ 
+        var listeners = [];
+        function addListener(fn) {
+            listeners.unshift(fn);
+        }
+        function removeListener(fn) {
+            for (var i = 0; i < listeners.length; i += 1) {
+                if (listeners[i] === fn) {
+                    listeners.splice(i, 1);
+                    return;
+                }
+            }
+        }
+        function taskComplete() {
+            remainingTasks--;
+            _arrayEach(listeners.slice(0), function (fn) {
+                fn();
+            });
+        }
+ 
+        addListener(function () {
+            if (!remainingTasks) {
+                callback(null, results);
+            }
+        });
+ 
+        _arrayEach(keys, function (k) {
+            var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
+            function taskCallback(err) {
+                var args = _baseSlice(arguments, 1);
+                if (args.length <= 1) {
+                    args = args[0];
+                }
+                if (err) {
+                    var safeResults = {};
+                    _arrayEach(_keys(results), function(rkey) {
+                        safeResults[rkey] = results[rkey];
+                    });
+                    safeResults[k] = args;
+                    callback(err, safeResults);
+                }
+                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');
+                }
+            }
+            function ready() {
+                return _reduce(requires, function (a, x) {
+                    return (a && results.hasOwnProperty(x));
+                }, true) && !results.hasOwnProperty(k);
+            }
+            if (ready()) {
+                task[task.length - 1](taskCallback, results);
+            }
+            else {
+                addListener(listener);
+            }
+            function listener() {
+                if (ready()) {
+                    removeListener(listener);
+                    task[task.length - 1](taskCallback, results);
+                }
+            }
+        });
+    };
+ 
+    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;
+ 
+        function wrappedTask(wrappedCallback, wrappedResults) {
+            function retryAttempt(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 = _once(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();
+        }
+        function wrapIterator(iterator) {
+            return function (err) {
+                if (err) {
+                    callback.apply(null, arguments);
+                }
+                else {
+                    var args = _baseSlice(arguments, 1);
+                    var next = iterator.next();
+                    if (next) {
+                        args.push(wrapIterator(next));
+                    }
+                    else {
+                        args.push(callback);
+                    }
+                    ensureAsync(iterator).apply(null, args);
+                }
+            };
+        }
+        wrapIterator(async.iterator(tasks))();
+    };
+ 
+    function _parallel(eachfn, tasks, callback) {
+        callback = callback || noop;
+        var results = _isArrayLike(tasks) ? [] : {};
+ 
+        eachfn(tasks, function (task, key, callback) {
+            task(function (err) {
+                var args = _baseSlice(arguments, 1);
+                if (args.length <= 1) {
+                    args = args[0];
+                }
+                results[key] = args;
+                callback(err);
+            });
+        }, function (err) {
+            callback(err, results);
+        });
+    }
+ 
+    async.parallel = function (tasks, callback) {
+        _parallel(async.eachOf, tasks, callback);
+    };
+ 
+    async.parallelLimit = function(tasks, limit, callback) {
+        _parallel(_eachOfLimit(limit), tasks, callback);
+    };
+ 
+    async.series = function (tasks, callback) {
+        callback = callback || noop;
+        var results = _isArrayLike(tasks) ? [] : {};
+ 
+        async.eachOfSeries(tasks, function (task, key, callback) {
+            task(function (err) {
+                var args = _baseSlice(arguments, 1);
+                if (args.length <= 1) {
+                    args = args[0];
+                }
+                results[key] = args;
+                callback(err);
+            });
+        }, function (err) {
+            callback(err, results);
+        });
+    };
+ 
+    async.iterator = function (tasks) {
+        function makeCallback(index) {
+            function fn() {
+                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))
+            );
+        };
+    };
+ 
+    function _concat(eachfn, arr, fn, callback) {
+        var result = [];
+        eachfn(arr, function (x, index, cb) {
+            fn(x, function (err, y) {
+                result = result.concat(y || []);
+                cb(err);
+            });
+        }, function (err) {
+            callback(err, result);
+        });
+    }
+    async.concat = doParallel(_concat);
+    async.concatSeries = doSeries(_concat);
+ 
+    async.whilst = function (test, iterator, callback) {
+        if (test()) {
+            iterator(function (err) {
+                Iif (err) {
+                    return callback(err);
+                }
+                async.whilst(test, iterator, callback);
+            });
+        }
+        else {
+            callback(null);
+        }
+    };
+ 
+    async.doWhilst = function (iterator, test, callback) {
+        iterator(function (err) {
+            Iif (err) {
+                return callback(err);
+            }
+            var args = _baseSlice(arguments, 1);
+            if (test.apply(null, args)) {
+                async.doWhilst(iterator, test, callback);
+            }
+            else {
+                callback(null);
+            }
+        });
+    };
+ 
+    async.until = function (test, iterator, callback) {
+        if (!test()) {
+            iterator(function (err) {
+                Iif (err) {
+                    return callback(err);
+                }
+                async.until(test, iterator, callback);
+            });
+        }
+        else {
+            callback(null);
+        }
+    };
+ 
+    async.doUntil = function (iterator, test, callback) {
+        iterator(function (err) {
+            Iif (err) {
+                return callback(err);
+            }
+            var args = _baseSlice(arguments, 1);
+            if (!test.apply(null, args)) {
+                async.doUntil(iterator, test, callback);
+            }
+            else {
+                callback(null);
+            }
+        });
+    };
+ 
+    function _queue(worker, concurrency, payload) {
+        if (concurrency == null) {
+            concurrency = 1;
+        }
+        else if(concurrency === 0) {
+            throw new Error('Concurrency must not be zero');
+        }
+        function _insert(q, data, pos, callback) {
+            if (callback != null && typeof callback !== "function") {
+                throw new Error("task callback must be a function");
+            }
+            q.started = true;
+            if (!_isArray(data)) {
+                data = [data];
+            }
+            if(data.length === 0 && q.idle()) {
+                // call drain immediately if there are no tasks
+                return async.setImmediate(function() {
+                   q.drain();
+                });
+            }
+            _arrayEach(data, function(task) {
+                var item = {
+                    data: task,
+                    callback: callback || noop
+                };
+ 
+                if (pos) {
+                  q.tasks.unshift(item);
+                } else {
+                  q.tasks.push(item);
+                }
+ 
+                if (q.tasks.length === q.concurrency) {
+                    q.saturated();
+                }
+                async.setImmediate(q.process);
+            });
+        }
+ 
+        var workers = 0;
+        var q = {
+            tasks: [],
+            concurrency: concurrency,
+            saturated: noop,
+            empty: noop,
+            drain: noop,
+            started: false,
+            paused: false,
+            push: function (data, callback) {
+                _insert(q, data, false, callback);
+            },
+            kill: function () {
+                q.drain = noop;
+                q.tasks = [];
+            },
+            unshift: function (data, callback) {
+                _insert(q, data, true, callback);
+            },
+            process: function () {
+                if (!q.paused && workers < q.concurrency && q.tasks.length) {
+                    var tasks = payload ?
+                        q.tasks.splice(0, payload) :
+                        q.tasks.splice(0, q.tasks.length);
+ 
+                    var data = _map(tasks, function (task) {
+                        return task.data;
+                    });
+ 
+                    if (q.tasks.length === 0) {
+                        q.empty();
+                    }
+                    workers += 1;
+                    var cb = only_once(next);
+                    worker(data, cb);
+                }
+ 
+                function next() {
+                    workers -= 1;
+                    var args = arguments;
+                    _arrayEach(tasks, function (task) {
+                        task.callback.apply(task, args);
+                    });
+                    if (q.tasks.length + workers === 0) {
+                        q.drain();
+                    }
+                    q.process();
+                }
+            },
+            length: function () {
+                return q.tasks.length;
+            },
+            running: function () {
+                return workers;
+            },
+            idle: function() {
+                return q.tasks.length + workers === 0;
+            },
+            pause: function () {
+                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.queue = function (worker, concurrency) {
+        var q = _queue(function (items, cb) {
+            worker(items[0], cb);
+        }, concurrency, 1);
+ 
+        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) {
+            Iif (callback != null && typeof callback !== "function") {
+                throw new Error("task callback must be a function");
+            }
+            q.started = true;
+            Eif (!_isArray(data)) {
+                data = [data];
+            }
+            Iif(data.length === 0) {
+                // call drain immediately if there are no tasks
+                return async.setImmediate(function() {
+                    q.drain();
+                });
+            }
+            _arrayEach(data, function(task) {
+                var item = {
+                    data: task,
+                    priority: priority,
+                    callback: typeof callback === 'function' ? callback : noop
+                };
+ 
+                q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
+ 
+                if (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) {
+        return _queue(worker, 1, payload);
+    };
+ 
+    function _console_fn(name) {
+        return function (fn) {
+            var args = _baseSlice(arguments, 1);
+            fn.apply(null, args.concat([function (err) {
+                var args = _baseSlice(arguments, 1);
+                Eif (typeof console !== 'undefined') {
+                    if (err) {
+                        Eif (console.error) {
+                            console.error(err);
+                        }
+                    }
+                    else Eif (console[name]) {
+                        _arrayEach(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;
+        };
+        function memoized() {
+            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.slice(-1)[0];
+            if (typeof callback == 'function') {
+                args.pop();
+            } else {
+                callback = noop;
+            }
+ 
+            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));
+    };
+ 
+ 
+    function _applyEach(eachfn, fns /*args...*/) {
+        function go() {
+            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 = function (/*fns, args...*/) {
+        var args = _baseSlice(arguments);
+        return _applyEach.apply(null, [async.eachOf].concat(args));
+    };
+    async.applyEachSeries = function (/*fns, args...*/) {
+        var args = _baseSlice(arguments);
+        return _applyEach.apply(null, [async.eachOfSeries].concat(args));
+    };
+ 
+ 
+    async.forever = function (fn, callback) {
+        var done = only_once(callback || noop);
+        var task = ensureAsync(fn);
+        function next(err) {
+            if (err) {
+                return done(err);
+            }
+            task(next);
+        }
+        next();
+    };
+ 
+    function ensureAsync(fn) {
+        return function (/*...args, callback*/) {
+            var args = _baseSlice(arguments);
+            var callback = args.pop();
+            args.push(function () {
+                var innerArgs = arguments;
+                if (sync) {
+                    async.setImmediate(function () {
+                        callback.apply(null, innerArgs);
+                    });
+                } else {
+                    callback.apply(null, innerArgs);
+                }
+            });
+            var sync = true;
+            fn.apply(this, args);
+            sync = false;
+        };
+    }
+ 
+    async.ensureAsync = ensureAsync;
+ 
+    // Node.js
+    Eif (typeof module !== 'undefined' && module.exports) {
+        module.exports = async;
+    }
+    // AMD / RequireJS
+    else if (typeof define !== 'undefined' && define.amd) {
+        define([], function () {
+            return async;
+        });
+    }
+    // included directly via <script> tag
+    else {
+        root.async = async;
+    }
+ 
+}());
+ 
+ +
+ + + + + + diff --git a/node_modules/async/coverage/lib/index.html b/node_modules/async/coverage/lib/index.html new file mode 100644 index 0000000..c7eedeb --- /dev/null +++ b/node_modules/async/coverage/lib/index.html @@ -0,0 +1,73 @@ + + + + Code coverage report for lib/ + + + + + + +
+

Code coverage report for lib/

+

+ Statements: 94.88% (611 / 644)      + Branches: 86.91% (239 / 275)      + Functions: 95.41% (187 / 196)      + Lines: 94.85% (608 / 641)      + Ignored: none      +

+
All files » lib/
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
async.js94.88%(611 / 644)86.91%(239 / 275)95.41%(187 / 196)94.85%(608 / 641)
+
+
+ + + + + + diff --git a/node_modules/async/coverage/prettify.css b/node_modules/async/coverage/prettify.css new file mode 100644 index 0000000..b317a7c --- /dev/null +++ b/node_modules/async/coverage/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/node_modules/async/coverage/prettify.js b/node_modules/async/coverage/prettify.js new file mode 100644 index 0000000..ef51e03 --- /dev/null +++ b/node_modules/async/coverage/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/node_modules/async/coverage/sort-arrow-sprite.png b/node_modules/async/coverage/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..03f704a609c6fd0dbfdac63466a7d7c958b5cbf3 GIT binary patch literal 209 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qj#UE5hcO-X(i=}MX3yqDfvmM z3ZA)%>8U}fi7AzZCsS>Jii$m5978H@?Fn+^JD|Y9yzj{W`447Gxa{7*dM7nnnD-Lb z6^}Hx2)'; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + el = getNthColumn(i).querySelector('.sorter'); + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/node_modules/async/lib/async.js b/node_modules/async/lib/async.js new file mode 100644 index 0000000..bfc8bdd --- /dev/null +++ b/node_modules/async/lib/async.js @@ -0,0 +1,1187 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + function noop() {} + + // 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(this, arguments); + }; + } + + function _once(fn) { + var called = false; + return function() { + if (called) return; + called = true; + fn.apply(this, arguments); + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + function _isArrayLike(arr) { + return _isArray(arr) || ( + // has a positive integer length property + typeof arr.length === "number" && + arr.length >= 0 && + arr.length % 1 === 0 + ); + } + + function _each(coll, iterator) { + return _isArrayLike(coll) ? + _arrayEach(coll, iterator) : + _forEachOf(coll, iterator); + } + + function _arrayEach(arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + } + + function _map(arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + } + + function _range(count) { + return _map(Array(count), function (v, i) { return i; }); + } + + function _reduce(arr, iterator, memo) { + _arrayEach(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + } + + function _forEachOf(object, iterator) { + _arrayEach(_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; + }; + + function _keyIterator(coll) { + var i = -1; + var len; + var keys; + if (_isArrayLike(coll)) { + len = coll.length; + return function next() { + i++; + return i < len ? i : null; + }; + } else { + keys = _keys(coll); + len = keys.length; + return function next() { + i++; + return i < len ? keys[i] : null; + }; + } + } + + function _baseSlice(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; + } + + function _withoutIndex(iterator) { + return function (value, index, callback) { + return iterator(value, callback); + }; + } + + //// 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.forEach = + async.each = function (arr, iterator, callback) { + return async.eachOf(arr, _withoutIndex(iterator), callback); + }; + + async.forEachSeries = + async.eachSeries = function (arr, iterator, callback) { + return async.eachOfSeries(arr, _withoutIndex(iterator), callback); + }; + + + async.forEachLimit = + async.eachLimit = function (arr, limit, iterator, callback) { + return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); + }; + + async.forEachOf = + async.eachOf = function (object, iterator, callback) { + callback = _once(callback || noop); + object = object || []; + var size = _isArrayLike(object) ? object.length : _keys(object).length; + var completed = 0; + if (!size) { + return callback(null); + } + _each(object, function (value, key) { + iterator(object[key], key, only_once(done)); + }); + function done(err) { + if (err) { + callback(err); + } + else { + completed += 1; + if (completed >= size) { + callback(null); + } + } + } + }; + + async.forEachOfSeries = + async.eachOfSeries = function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + function iterate() { + var sync = true; + var key = nextKey(); + if (key === null) { + return callback(null); + } + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + } + else { + if (sync) { + async.nextTick(iterate); + } + else { + iterate(); + } + } + }); + sync = false; + } + iterate(); + }; + + + + async.forEachOfLimit = + async.eachOfLimit = function (obj, limit, iterator, callback) { + _eachOfLimit(limit)(obj, iterator, callback); + }; + + function _eachOfLimit(limit) { + + return function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + if (limit <= 0) { + return callback(null); + } + var done = false; + var running = 0; + var errored = false; + + (function replenish () { + if (done && running <= 0) { + return callback(null); + } + + while (running < limit && !errored) { + var key = nextKey(); + if (key === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iterator(obj[key], key, function (err) { + running -= 1; + if (err) { + callback(err); + errored = true; + } + else { + replenish(); + } + }); + } + })(); + }; + } + + + function doParallel(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOf, obj, iterator, callback); + }; + } + function doParallelLimit(limit, fn) { + return function (obj, iterator, callback) { + return fn(_eachOfLimit(limit), obj, iterator, callback); + }; + } + function doSeries(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOfSeries, obj, iterator, callback); + }; + } + + function _asyncMap(eachfn, arr, iterator, callback) { + callback = _once(callback || noop); + var results = []; + eachfn(arr, function (value, index, callback) { + iterator(value, function (err, v) { + results[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); + }; + + function _mapLimit(limit) { + return doParallelLimit(limit, _asyncMap); + } + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.inject = + async.foldl = + async.reduce = function (arr, memo, iterator, callback) { + async.eachOfSeries(arr, function (x, i, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err || null, memo); + }); + }; + + async.foldr = + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + + function _filter(eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, index, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function () { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + } + + async.select = + async.filter = doParallel(_filter); + + async.selectSeries = + async.filterSeries = doSeries(_filter); + + function _reject(eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, index, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function () { + 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); + + function _detect(eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, index, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = noop; + } + else { + callback(); + } + }); + }, function () { + main_callback(); + }); + } + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.any = + async.some = function (arr, iterator, main_callback) { + async.eachOf(arr, function (x, _, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = noop; + } + callback(); + }); + }, function () { + main_callback(false); + }); + }; + + async.all = + async.every = function (arr, iterator, main_callback) { + async.eachOf(arr, function (x, _, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = noop; + } + callback(); + }); + }, function () { + main_callback(true); + }); + }; + + 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 { + callback(null, _map(results.sort(comparator), function (x) { + return x.value; + })); + } + + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + }; + + async.auto = function (tasks, callback) { + callback = _once(callback || noop); + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(null); + } + + var results = {}; + + var listeners = []; + function addListener(fn) { + listeners.unshift(fn); + } + function removeListener(fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + } + function taskComplete() { + remainingTasks--; + _arrayEach(listeners.slice(0), function (fn) { + fn(); + }); + } + + addListener(function () { + if (!remainingTasks) { + callback(null, results); + } + }); + + _arrayEach(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + function taskCallback(err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _arrayEach(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + } + 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'); + } + } + function ready() { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + } + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + addListener(listener); + } + function listener() { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + } + }); + }; + + 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; + + function wrappedTask(wrappedCallback, wrappedResults) { + function retryAttempt(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 = _once(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(); + } + function wrapIterator(iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + } + else { + var args = _baseSlice(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + ensureAsync(iterator).apply(null, args); + } + }; + } + wrapIterator(async.iterator(tasks))(); + }; + + function _parallel(eachfn, tasks, callback) { + callback = callback || noop; + var results = _isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, function (task, key, callback) { + task(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[key] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + + async.parallel = function (tasks, callback) { + _parallel(async.eachOf, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || noop; + var results = _isArrayLike(tasks) ? [] : {}; + + async.eachOfSeries(tasks, function (task, key, callback) { + task(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[key] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + }; + + async.iterator = function (tasks) { + function makeCallback(index) { + function fn() { + 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)) + ); + }; + }; + + function _concat(eachfn, arr, fn, callback) { + var result = []; + eachfn(arr, function (x, index, cb) { + fn(x, function (err, y) { + result = result.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, result); + }); + } + 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(null); + } + }; + + 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(null); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(null); + } + }; + + 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(null); + } + }); + }; + + function _queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + callback: callback || noop + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + }); + async.setImmediate(q.process); + } + function _next(q, tasks) { + return function(){ + workers -= 1; + var args = arguments; + _arrayEach(tasks, function (task) { + task.callback.apply(task, args); + }); + if (q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: noop, + empty: noop, + drain: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = noop; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (!q.paused && workers < q.concurrency && q.tasks.length) { + while(workers < q.concurrency && q.tasks.length){ + var tasks = payload ? + q.tasks.splice(0, payload) : + q.tasks.splice(0, q.tasks.length); + + var data = _map(tasks, function (task) { + return task.data; + }); + + if (q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var cb = only_once(_next(q, tasks)); + worker(data, cb); + } + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + 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.queue = function (worker, concurrency) { + var q = _queue(function (items, cb) { + worker(items[0], cb); + }, concurrency, 1); + + 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 (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : noop + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (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) { + return _queue(worker, 1, payload); + }; + + function _console_fn(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]) { + _arrayEach(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; + }; + function memoized() { + 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); + }; + }; + + function _times(mapper) { + return function (count, iterator, callback) { + mapper(_range(count), iterator, callback); + }; + } + + async.times = _times(async.map); + async.timesSeries = _times(async.mapSeries); + async.timesLimit = function (count, limit, iterator, callback) { + return async.mapLimit(_range(count), limit, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return function () { + var that = this; + var args = _baseSlice(arguments); + + var callback = args.slice(-1)[0]; + if (typeof callback == 'function') { + args.pop(); + } else { + callback = noop; + } + + 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)); + }; + + + function _applyEach(eachfn, fns /*args...*/) { + function go() { + 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 = function (/*fns, args...*/) { + var args = _baseSlice(arguments); + return _applyEach.apply(null, [async.eachOf].concat(args)); + }; + async.applyEachSeries = function (/*fns, args...*/) { + var args = _baseSlice(arguments); + return _applyEach.apply(null, [async.eachOfSeries].concat(args)); + }; + + + async.forever = function (fn, callback) { + var done = only_once(callback || noop); + var task = ensureAsync(fn); + function next(err) { + if (err) { + return done(err); + } + task(next); + } + next(); + }; + + function ensureAsync(fn) { + return function (/*...args, callback*/) { + var args = _baseSlice(arguments); + var callback = args.pop(); + args.push(function () { + var innerArgs = arguments; + if (sync) { + async.setImmediate(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + var sync = true; + fn.apply(this, args); + sync = false; + }; + } + + async.ensureAsync = ensureAsync; + + // 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 + +``` + +## Documentation + +### Collections + +* [`each`](#each) +* [`eachSeries`](#eachSeries) +* [`eachLimit`](#eachLimit) +* [`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 occured, 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. + +__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 occured, 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 +}); +``` + +--------------------------------------- + + +### 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 this +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(err, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(err, 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 following function consumes the return value of the latter function. + +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) { + function handleError(err, data, callback) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } + else { + callback(data); + } + } + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + handleError, + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + }, + handleError, + function(cats) { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + )(req.session.user_id); + } +}); +``` + +--------------------------------------- + +### 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, iterator, 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 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 bar'); +}); + +// 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 successfull task. If all attemps 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) + +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. +* `callback` - The function to call `n` times. + +__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. + +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` - Tn 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/mongoose/node_modules/async/component.json b/node_modules/mongoose/node_modules/async/component.json new file mode 100644 index 0000000..bbb0115 --- /dev/null +++ b/node_modules/mongoose/node_modules/async/component.json @@ -0,0 +1,11 @@ +{ + "name": "async", + "repo": "caolan/async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "0.1.23", + "keywords": [], + "dependencies": {}, + "development": {}, + "main": "lib/async.js", + "scripts": [ "lib/async.js" ] +} diff --git a/node_modules/mongoose/node_modules/async/lib/async.js b/node_modules/mongoose/node_modules/async/lib/async.js new file mode 100755 index 0000000..01e8afc --- /dev/null +++ b/node_modules/mongoose/node_modules/async/lib/async.js @@ -0,0 +1,1123 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +/*jshint onevar: false, indent:4 */ +/*global setImmediate: false, setTimeout: false, console: false */ +(function () { + + var async = {}; + + // global on the server, window in the browser + var root, previous_async; + + 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) { + if (arr.forEach) { + return arr.forEach(iterator); + } + for (var i = 0; i < arr.length; i += 1) { + iterator(arr[i], i, arr); + } + }; + + var _map = function (arr, iterator) { + if (arr.map) { + return arr.map(iterator); + } + var results = []; + _each(arr, function (x, i, a) { + results.push(iterator(x, i, a)); + }); + return results; + }; + + var _reduce = function (arr, iterator, memo) { + if (arr.reduce) { + return arr.reduce(iterator, memo); + } + _each(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + }; + + var _keys = function (obj) { + if (Object.keys) { + return Object.keys(obj); + } + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + if (typeof process === 'undefined' || !(process.nextTick)) { + if (typeof setImmediate === 'function') { + 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 (typeof setImmediate !== 'undefined') { + 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 || function () {}; + 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 = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + } + } + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + 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 || function () {}; + 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 = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = Array.prototype.slice.call(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 = function () {}; + } + 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 = function () {}; + } + 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 = function () {}; + } + 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 || function () {}; + 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 = function () {}; + + theCallback(null, results); + } + }); + + _each(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = function (err) { + var args = Array.prototype.slice.call(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 = function () {}; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + 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 || function () {}; + 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 = function () {}; + } + else { + var args = Array.prototype.slice.call(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 || function () {}; + if (_isArray(tasks)) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(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 = Array.prototype.slice.call(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 || function () {}; + if (_isArray(tasks)) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(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 = Array.prototype.slice.call(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 = Array.prototype.slice.call(arguments, 1); + return function () { + return fn.apply( + null, args.concat(Array.prototype.slice.call(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 = Array.prototype.slice.call(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 = Array.prototype.slice.call(arguments, 1); + if (!test.apply(null, args)) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + 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; + q.process(); + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + 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 = Array.prototype.slice.call(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = Array.prototype.slice.call(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 = Array.prototype.slice.call(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] = 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 = Array.prototype.slice.call(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 = Array.prototype.slice.call(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 = Array.prototype.slice.call(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = Array.prototype.slice.call(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 \n\n```\n\n## Documentation\n\n### Collections\n\n* [`each`](#each)\n* [`eachSeries`](#eachSeries)\n* [`eachLimit`](#eachLimit)\n* [`map`](#map)\n* [`mapSeries`](#mapSeries)\n* [`mapLimit`](#mapLimit)\n* [`filter`](#filter)\n* [`filterSeries`](#filterSeries)\n* [`reject`](#reject)\n* [`rejectSeries`](#rejectSeries)\n* [`reduce`](#reduce)\n* [`reduceRight`](#reduceRight)\n* [`detect`](#detect)\n* [`detectSeries`](#detectSeries)\n* [`sortBy`](#sortBy)\n* [`some`](#some)\n* [`every`](#every)\n* [`concat`](#concat)\n* [`concatSeries`](#concatSeries)\n\n### Control Flow\n\n* [`series`](#seriestasks-callback)\n* [`parallel`](#parallel)\n* [`parallelLimit`](#parallellimittasks-limit-callback)\n* [`whilst`](#whilst)\n* [`doWhilst`](#doWhilst)\n* [`until`](#until)\n* [`doUntil`](#doUntil)\n* [`forever`](#forever)\n* [`waterfall`](#waterfall)\n* [`compose`](#compose)\n* [`seq`](#seq)\n* [`applyEach`](#applyEach)\n* [`applyEachSeries`](#applyEachSeries)\n* [`queue`](#queue)\n* [`priorityQueue`](#priorityQueue)\n* [`cargo`](#cargo)\n* [`auto`](#auto)\n* [`retry`](#retry)\n* [`iterator`](#iterator)\n* [`apply`](#apply)\n* [`nextTick`](#nextTick)\n* [`times`](#times)\n* [`timesSeries`](#timesSeries)\n\n### Utils\n\n* [`memoize`](#memoize)\n* [`unmemoize`](#unmemoize)\n* [`log`](#log)\n* [`dir`](#dir)\n* [`noConflict`](#noConflict)\n\n\n## Collections\n\n\n\n### each(arr, iterator, callback)\n\nApplies the function `iterator` to each item in `arr`, in parallel.\nThe `iterator` is called with an item from the list, and a callback for when it\nhas finished. If the `iterator` passes an error to its `callback`, the main\n`callback` (for the `each` function) is immediately called with the error.\n\nNote, that since this function applies `iterator` to each item in parallel,\nthere is no guarantee that the iterator functions will complete in order.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A function to apply to each item in `arr`.\n The iterator is passed a `callback(err)` which must be called once it has \n completed. If no error has occured, the `callback` should be run without \n arguments or with an explicit `null` argument.\n* `callback(err)` - A callback which is called when all `iterator` functions\n have finished, or an error occurs.\n\n__Examples__\n\n\n```js\n// assuming openFiles is an array of file names and saveFile is a function\n// to save the modified contents of that file:\n\nasync.each(openFiles, saveFile, function(err){\n // if any of the saves produced an error, err would equal that error\n});\n```\n\n```js\n// assuming openFiles is an array of file names \n\nasync.each(openFiles, function( file, callback) {\n \n // Perform operation on file here.\n console.log('Processing file ' + file);\n \n if( file.length > 32 ) {\n console.log('This file name is too long');\n callback('File name too long');\n } else {\n // Do work to process file here\n console.log('File processed');\n callback();\n }\n}, function(err){\n // if any of the file processing produced an error, err would equal that error\n if( err ) {\n // One of the iterations produced an error.\n // All processing will now stop.\n console.log('A file failed to process');\n } else {\n console.log('All files have been processed successfully');\n }\n});\n```\n\n---------------------------------------\n\n\n\n### eachSeries(arr, iterator, callback)\n\nThe same as [`each`](#each), only `iterator` is applied to each item in `arr` in\nseries. The next `iterator` is only called once the current one has completed. \nThis means the `iterator` functions will complete in order.\n\n\n---------------------------------------\n\n\n\n### eachLimit(arr, limit, iterator, callback)\n\nThe same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously \nrunning at any time.\n\nNote that the items in `arr` are not processed in batches, so there is no guarantee that \nthe first `limit` `iterator` functions will complete before any others are started.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `limit` - The maximum number of `iterator`s to run at any time.\n* `iterator(item, callback)` - A function to apply to each item in `arr`.\n The iterator is passed a `callback(err)` which must be called once it has \n completed. If no error has occured, the callback should be run without \n arguments or with an explicit `null` argument.\n* `callback(err)` - A callback which is called when all `iterator` functions\n have finished, or an error occurs.\n\n__Example__\n\n```js\n// Assume documents is an array of JSON objects and requestApi is a\n// function that interacts with a rate-limited REST api.\n\nasync.eachLimit(documents, 20, requestApi, function(err){\n // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n\n### map(arr, iterator, callback)\n\nProduces a new array of values by mapping each value in `arr` through\nthe `iterator` function. The `iterator` is called with an item from `arr` and a\ncallback for when it has finished processing. Each of these callback takes 2 arguments: \nan `error`, and the transformed item from `arr`. If `iterator` passes an error to this \ncallback, the main `callback` (for the `map` function) is immediately called with the error.\n\nNote, that since this function applies the `iterator` to each item in parallel,\nthere is no guarantee that the `iterator` functions will complete in order. \nHowever, the results array will be in the same order as the original `arr`.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A function to apply to each item in `arr`.\n The iterator is passed a `callback(err, transformed)` which must be called once \n it has completed with an error (which can be `null`) and a transformed item.\n* `callback(err, results)` - A callback which is called when all `iterator`\n functions have finished, or an error occurs. Results is an array of the\n transformed items from the `arr`.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n\n### mapSeries(arr, iterator, callback)\n\nThe same as [`map`](#map), only the `iterator` is applied to each item in `arr` in\nseries. The next `iterator` is only called once the current one has completed. \nThe results array will be in the same order as the original.\n\n\n---------------------------------------\n\n\n### mapLimit(arr, limit, iterator, callback)\n\nThe same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that \nthe first `limit` `iterator` functions will complete before any others are started.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `limit` - The maximum number of `iterator`s to run at any time.\n* `iterator(item, callback)` - A function to apply to each item in `arr`.\n The iterator is passed a `callback(err, transformed)` which must be called once \n it has completed with an error (which can be `null`) and a transformed item.\n* `callback(err, results)` - A callback which is called when all `iterator`\n calls have finished, or an error occurs. The result is an array of the\n transformed items from the original `arr`.\n\n__Example__\n\n```js\nasync.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){\n // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n\n\n### filter(arr, iterator, callback)\n\n__Alias:__ `select`\n\nReturns a new array of all the values in `arr` which pass an async truth test.\n_The callback for each `iterator` call only accepts a single argument of `true` or\n`false`; it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like `fs.exists`. This operation is\nperformed in parallel, but the results array will be in the same order as the\noriginal.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A truth test to apply to each item in `arr`.\n The `iterator` is passed a `callback(truthValue)`, which must be called with a \n boolean argument once it has completed.\n* `callback(results)` - A callback which is called after all the `iterator`\n functions have finished.\n\n__Example__\n\n```js\nasync.filter(['file1','file2','file3'], fs.exists, function(results){\n // results now equals an array of the existing files\n});\n```\n\n---------------------------------------\n\n\n\n### filterSeries(arr, iterator, callback)\n\n__Alias:__ `selectSeries`\n\nThe same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in\nseries. The next `iterator` is only called once the current one has completed. \nThe results array will be in the same order as the original.\n\n---------------------------------------\n\n\n### reject(arr, iterator, callback)\n\nThe opposite of [`filter`](#filter). Removes values that pass an `async` truth test.\n\n---------------------------------------\n\n\n### rejectSeries(arr, iterator, callback)\n\nThe same as [`reject`](#reject), only the `iterator` is applied to each item in `arr`\nin series.\n\n\n---------------------------------------\n\n\n### reduce(arr, memo, iterator, callback)\n\n__Aliases:__ `inject`, `foldl`\n\nReduces `arr` into a single value using an async `iterator` to return\neach successive step. `memo` is the initial state of the reduction. \nThis function only operates in series. \n\nFor performance reasons, it may make sense to split a call to this function into \na parallel map, and then use the normal `Array.prototype.reduce` on the results. \nThis function is for situations where each step in the reduction needs to be async; \nif you can get the data before reducing it, then it's probably a good idea to do so.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `memo` - The initial state of the reduction.\n* `iterator(memo, item, callback)` - A function applied to each item in the\n array to produce the next step in the reduction. The `iterator` is passed a\n `callback(err, reduction)` which accepts an optional error as its first \n argument, and the state of the reduction as the second. If an error is \n passed to the callback, the reduction is stopped and the main `callback` is \n immediately called with the error.\n* `callback(err, result)` - A callback which is called after all the `iterator`\n functions have finished. Result is the reduced value.\n\n__Example__\n\n```js\nasync.reduce([1,2,3], 0, function(memo, item, callback){\n // pointless async:\n process.nextTick(function(){\n callback(null, memo + item)\n });\n}, function(err, result){\n // result is now equal to the last value of memo, which is 6\n});\n```\n\n---------------------------------------\n\n\n### reduceRight(arr, memo, iterator, callback)\n\n__Alias:__ `foldr`\n\nSame as [`reduce`](#reduce), only operates on `arr` in reverse order.\n\n\n---------------------------------------\n\n\n### detect(arr, iterator, callback)\n\nReturns the first value in `arr` that passes an async truth test. The\n`iterator` is applied in parallel, meaning the first iterator to return `true` will\nfire the detect `callback` with that result. That means the result might not be\nthe first item in the original `arr` (in terms of order) that passes the test.\n\nIf order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A truth test to apply to each item in `arr`.\n The iterator is passed a `callback(truthValue)` which must be called with a \n boolean argument once it has completed.\n* `callback(result)` - A callback which is called as soon as any iterator returns\n `true`, or after all the `iterator` functions have finished. Result will be\n the first item in the array that passes the truth test (iterator) or the\n value `undefined` if none passed.\n\n__Example__\n\n```js\nasync.detect(['file1','file2','file3'], fs.exists, function(result){\n // result now equals the first file in the list that exists\n});\n```\n\n---------------------------------------\n\n\n### detectSeries(arr, iterator, callback)\n\nThe same as [`detect`](#detect), only the `iterator` is applied to each item in `arr`\nin series. This means the result is always the first in the original `arr` (in\nterms of array order) that passes the truth test.\n\n\n---------------------------------------\n\n\n### sortBy(arr, iterator, callback)\n\nSorts a list by the results of running each `arr` value through an async `iterator`.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A function to apply to each item in `arr`.\n The iterator is passed a `callback(err, sortValue)` which must be called once it\n has completed with an error (which can be `null`) and a value to use as the sort\n criteria.\n* `callback(err, results)` - A callback which is called after all the `iterator`\n functions have finished, or an error occurs. Results is the items from\n the original `arr` sorted by the values returned by the `iterator` calls.\n\n__Example__\n\n```js\nasync.sortBy(['file1','file2','file3'], function(file, callback){\n fs.stat(file, function(err, stats){\n callback(err, stats.mtime);\n });\n}, function(err, results){\n // results is now the original array of files sorted by\n // modified date\n});\n```\n\n__Sort Order__\n\nBy modifying the callback parameter the sorting order can be influenced:\n\n```js\n//ascending order\nasync.sortBy([1,9,3,5], function(x, callback){\n callback(err, x);\n}, function(err,result){\n //result callback\n} );\n\n//descending order\nasync.sortBy([1,9,3,5], function(x, callback){\n callback(err, x*-1); //<- x*-1 instead of x, turns the order around\n}, function(err,result){\n //result callback\n} );\n```\n\n---------------------------------------\n\n\n### some(arr, iterator, callback)\n\n__Alias:__ `any`\n\nReturns `true` if at least one element in the `arr` satisfies an async test.\n_The callback for each iterator call only accepts a single argument of `true` or\n`false`; it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like `fs.exists`. Once any iterator\ncall returns `true`, the main `callback` is immediately called.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A truth test to apply to each item in the array\n in parallel. The iterator is passed a callback(truthValue) which must be \n called with a boolean argument once it has completed.\n* `callback(result)` - A callback which is called as soon as any iterator returns\n `true`, or after all the iterator functions have finished. Result will be\n either `true` or `false` depending on the values of the async tests.\n\n__Example__\n\n```js\nasync.some(['file1','file2','file3'], fs.exists, function(result){\n // if result is true then at least one of the files exists\n});\n```\n\n---------------------------------------\n\n\n### every(arr, iterator, callback)\n\n__Alias:__ `all`\n\nReturns `true` if every element in `arr` satisfies an async test.\n_The callback for each `iterator` call only accepts a single argument of `true` or\n`false`; it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like `fs.exists`.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A truth test to apply to each item in the array\n in parallel. The iterator is passed a callback(truthValue) which must be \n called with a boolean argument once it has completed.\n* `callback(result)` - A callback which is called after all the `iterator`\n functions have finished. Result will be either `true` or `false` depending on\n the values of the async tests.\n\n__Example__\n\n```js\nasync.every(['file1','file2','file3'], fs.exists, function(result){\n // if result is true then every file exists\n});\n```\n\n---------------------------------------\n\n\n### concat(arr, iterator, callback)\n\nApplies `iterator` to each item in `arr`, concatenating the results. Returns the\nconcatenated list. The `iterator`s are called in parallel, and the results are\nconcatenated as they return. There is no guarantee that the results array will\nbe returned in the original order of `arr` passed to the `iterator` function.\n\n__Arguments__\n\n* `arr` - An array to iterate over.\n* `iterator(item, callback)` - A function to apply to each item in `arr`.\n The iterator is passed a `callback(err, results)` which must be called once it \n has completed with an error (which can be `null`) and an array of results.\n* `callback(err, results)` - A callback which is called after all the `iterator`\n functions have finished, or an error occurs. Results is an array containing\n the concatenated results of the `iterator` function.\n\n__Example__\n\n```js\nasync.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){\n // files is now a list of filenames that exist in the 3 directories\n});\n```\n\n---------------------------------------\n\n\n### concatSeries(arr, iterator, callback)\n\nSame as [`concat`](#concat), but executes in series instead of parallel.\n\n\n## Control Flow\n\n\n### series(tasks, [callback])\n\nRun the functions in the `tasks` array in series, each one running once the previous\nfunction has completed. If any functions in the series pass an error to its\ncallback, no more functions are run, and `callback` is immediately called with the value of the error. \nOtherwise, `callback` receives an array of results when `tasks` have completed.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function, and the results will be passed to the final `callback` as an object\ninstead of an array. This can be a more readable way of handling results from\n[`series`](#series).\n\n**Note** that while many implementations preserve the order of object properties, the\n[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) \nexplicitly states that\n\n> The mechanics and order of enumerating the properties is not specified.\n\nSo if you rely on the order in which your series of functions are executed, and want\nthis to work on all platforms, consider using an array. \n\n__Arguments__\n\n* `tasks` - An array or object containing functions to run, each function is passed\n a `callback(err, result)` it must call on completion with an error `err` (which can\n be `null`) and an optional `result` value.\n* `callback(err, results)` - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the `task` callbacks.\n\n__Example__\n\n```js\nasync.series([\n function(callback){\n // do some stuff ...\n callback(null, 'one');\n },\n function(callback){\n // do some more stuff ...\n callback(null, 'two');\n }\n],\n// optional callback\nfunction(err, results){\n // results is now equal to ['one', 'two']\n});\n\n\n// an example using an object instead of an array\nasync.series({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n }\n},\nfunction(err, results) {\n // results is now equal to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n\n### parallel(tasks, [callback])\n\nRun the `tasks` array of functions in parallel, without waiting until the previous\nfunction has completed. If any of the functions pass an error to its\ncallback, the main `callback` is immediately called with the value of the error.\nOnce the `tasks` have completed, the results are passed to the final `callback` as an\narray.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final `callback` as an object\ninstead of an array. This can be a more readable way of handling results from\n[`parallel`](#parallel).\n\n\n__Arguments__\n\n* `tasks` - An array or object containing functions to run. Each function is passed \n a `callback(err, result)` which it must call on completion with an error `err` \n (which can be `null`) and an optional `result` value.\n* `callback(err, results)` - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.parallel([\n function(callback){\n setTimeout(function(){\n callback(null, 'one');\n }, 200);\n },\n function(callback){\n setTimeout(function(){\n callback(null, 'two');\n }, 100);\n }\n],\n// optional callback\nfunction(err, results){\n // the results array will equal ['one','two'] even though\n // the second function had a shorter timeout.\n});\n\n\n// an example using an object instead of an array\nasync.parallel({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n }\n},\nfunction(err, results) {\n // results is now equals to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n\n### parallelLimit(tasks, limit, [callback])\n\nThe same as [`parallel`](#parallel), only `tasks` are executed in parallel \nwith a maximum of `limit` tasks executing at any time.\n\nNote that the `tasks` are not executed in batches, so there is no guarantee that \nthe first `limit` tasks will complete before any others are started.\n\n__Arguments__\n\n* `tasks` - An array or object containing functions to run, each function is passed \n a `callback(err, result)` it must call on completion with an error `err` (which can\n be `null`) and an optional `result` value.\n* `limit` - The maximum number of `tasks` to run at any time.\n* `callback(err, results)` - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the `task` callbacks.\n\n---------------------------------------\n\n\n### whilst(test, fn, callback)\n\nRepeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,\nor an error occurs.\n\n__Arguments__\n\n* `test()` - synchronous truth test to perform before each execution of `fn`.\n* `fn(callback)` - A function which is called each time `test` passes. The function is\n passed a `callback(err)`, which must be called once it has completed with an \n optional `err` argument.\n* `callback(err)` - A callback which is called after the test fails and repeated\n execution of `fn` has stopped.\n\n__Example__\n\n```js\nvar count = 0;\n\nasync.whilst(\n function () { return count < 5; },\n function (callback) {\n count++;\n setTimeout(callback, 1000);\n },\n function (err) {\n // 5 seconds have passed\n }\n);\n```\n\n---------------------------------------\n\n\n### doWhilst(fn, test, callback)\n\nThe post-check version of [`whilst`](#whilst). To reflect the difference in \nthe order of operations, the arguments `test` and `fn` are switched. \n\n`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n\n---------------------------------------\n\n\n### until(test, fn, callback)\n\nRepeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,\nor an error occurs.\n\nThe inverse of [`whilst`](#whilst).\n\n---------------------------------------\n\n\n### doUntil(fn, test, callback)\n\nLike [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.\n\n---------------------------------------\n\n\n### forever(fn, errback)\n\nCalls the asynchronous function `fn` with a callback parameter that allows it to\ncall itself again, in series, indefinitely.\n\nIf an error is passed to the callback then `errback` is called with the\nerror, and execution stops, otherwise it will never be called.\n\n```js\nasync.forever(\n function(next) {\n // next is suitable for passing to things that need a callback(err [, whatever]);\n // it will result in this function being called again.\n },\n function(err) {\n // if next is called with a value in its first parameter, it will appear\n // in here as 'err', and execution will stop.\n }\n);\n```\n\n---------------------------------------\n\n\n### waterfall(tasks, [callback])\n\nRuns the `tasks` array of functions in series, each passing their results to the next in\nthe array. However, if any of the `tasks` pass an error to their own callback, the\nnext function is not executed, and the main `callback` is immediately called with\nthe error.\n\n__Arguments__\n\n* `tasks` - An array of functions to run, each function is passed a \n `callback(err, result1, result2, ...)` it must call on completion. The first\n argument is an error (which can be `null`) and any further arguments will be \n passed as arguments in order to the next task.\n* `callback(err, [results])` - An optional callback to run once all the functions\n have completed. This will be passed the results of the last task's callback.\n\n\n\n__Example__\n\n```js\nasync.waterfall([\n function(callback){\n callback(null, 'one', 'two');\n },\n function(arg1, arg2, callback){\n // arg1 now equals 'one' and arg2 now equals 'two'\n callback(null, 'three');\n },\n function(arg1, callback){\n // arg1 now equals 'three'\n callback(null, 'done');\n }\n], function (err, result) {\n // result now equals 'done' \n});\n```\n\n---------------------------------------\n\n### compose(fn1, fn2...)\n\nCreates a function which is a composition of the passed asynchronous\nfunctions. Each function consumes the return value of the function that\nfollows. Composing functions `f()`, `g()`, and `h()` would produce the result of\n`f(g(h()))`, only this version uses callbacks to obtain the return values.\n\nEach function is executed with the `this` binding of the composed function.\n\n__Arguments__\n\n* `functions...` - the asynchronous functions to compose\n\n\n__Example__\n\n```js\nfunction add1(n, callback) {\n setTimeout(function () {\n callback(null, n + 1);\n }, 10);\n}\n\nfunction mul3(n, callback) {\n setTimeout(function () {\n callback(null, n * 3);\n }, 10);\n}\n\nvar add1mul3 = async.compose(mul3, add1);\n\nadd1mul3(4, function (err, result) {\n // result now equals 15\n});\n```\n\n---------------------------------------\n\n### seq(fn1, fn2...)\n\nVersion of the compose function that is more natural to read.\nEach following function consumes the return value of the latter function. \n\nEach function is executed with the `this` binding of the composed function.\n\n__Arguments__\n\n* functions... - the asynchronous functions to compose\n\n\n__Example__\n\n```js\n// Requires lodash (or underscore), express3 and dresende's orm2.\n// Part of an app, that fetches cats of the logged user.\n// This example uses `seq` function to avoid overnesting and error \n// handling clutter.\napp.get('/cats', function(request, response) {\n function handleError(err, data, callback) {\n if (err) {\n console.error(err);\n response.json({ status: 'error', message: err.message });\n }\n else {\n callback(data);\n }\n }\n var User = request.models.User;\n async.seq(\n _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))\n handleError,\n function(user, fn) {\n user.getCats(fn); // 'getCats' has signature (callback(err, data))\n },\n handleError,\n function(cats) {\n response.json({ status: 'ok', message: 'Cats found', data: cats });\n }\n )(req.session.user_id);\n }\n});\n```\n\n---------------------------------------\n\n### applyEach(fns, args..., callback)\n\nApplies the provided arguments to each function in the array, calling \n`callback` after all functions have completed. If you only provide the first\nargument, then it will return a function which lets you pass in the\narguments as if it were a single function call.\n\n__Arguments__\n\n* `fns` - the asynchronous functions to all call with the same arguments\n* `args...` - any number of separate arguments to pass to the function\n* `callback` - the final argument should be the callback, called when all\n functions have completed processing\n\n\n__Example__\n\n```js\nasync.applyEach([enableSearch, updateSchema], 'bucket', callback);\n\n// partial application example:\nasync.each(\n buckets,\n async.applyEach([enableSearch, updateSchema]),\n callback\n);\n```\n\n---------------------------------------\n\n\n### applyEachSeries(arr, iterator, callback)\n\nThe same as [`applyEach`](#applyEach) only the functions are applied in series.\n\n---------------------------------------\n\n\n### queue(worker, concurrency)\n\nCreates a `queue` object with the specified `concurrency`. Tasks added to the\n`queue` are processed in parallel (up to the `concurrency` limit). If all\n`worker`s are in progress, the task is queued until one becomes available. \nOnce a `worker` completes a `task`, that `task`'s callback is called.\n\n__Arguments__\n\n* `worker(task, callback)` - An asynchronous function for processing a queued\n task, which must call its `callback(err)` argument when finished, with an \n optional `error` as an argument.\n* `concurrency` - An `integer` for determining how many `worker` functions should be\n run in parallel.\n\n__Queue objects__\n\nThe `queue` object returned by this function has the following properties and\nmethods:\n\n* `length()` - a function returning the number of items waiting to be processed.\n* `started` - a function returning whether or not any items have been pushed and processed by the queue\n* `running()` - a function returning the number of items currently being processed.\n* `idle()` - a function returning false if there are items waiting or being processed, or true if not.\n* `concurrency` - an integer for determining how many `worker` functions should be\n run in parallel. This property can be changed after a `queue` is created to\n alter the concurrency on-the-fly.\n* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once \n the `worker` has finished processing the task. Instead of a single task, a `tasks` array\n can be submitted. The respective callback is used for every task in the list.\n* `unshift(task, [callback])` - add a new task to the front of the `queue`.\n* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, \n and further tasks will be queued.\n* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.\n* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.\n* `paused` - a boolean for determining whether the queue is in a paused state\n* `pause()` - a function that pauses the processing of tasks until `resume()` is called.\n* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.\n* `kill()` - a function that empties remaining tasks from the queue forcing it to go idle.\n\n__Example__\n\n```js\n// create a queue object with concurrency 2\n\nvar q = async.queue(function (task, callback) {\n console.log('hello ' + task.name);\n callback();\n}, 2);\n\n\n// assign a callback\nq.drain = function() {\n console.log('all items have been processed');\n}\n\n// add some items to the queue\n\nq.push({name: 'foo'}, function (err) {\n console.log('finished processing foo');\n});\nq.push({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n});\n\n// add some items to the queue (batch-wise)\n\nq.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {\n console.log('finished processing bar');\n});\n\n// add some items to the front of the queue\n\nq.unshift({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n});\n```\n\n\n---------------------------------------\n\n\n### priorityQueue(worker, concurrency)\n\nThe 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:\n\n* `push(task, priority, [callback])` - `priority` should be a number. If an array of\n `tasks` is given, all tasks will be assigned the same priority.\n* The `unshift` method was removed.\n\n---------------------------------------\n\n\n### cargo(worker, [payload])\n\nCreates a `cargo` object with the specified payload. Tasks added to the\ncargo will be processed altogether (up to the `payload` limit). If the\n`worker` is in progress, the task is queued until it becomes available. Once\nthe `worker` has completed some tasks, each callback of those tasks is called.\nCheck out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work.\n\nWhile [queue](#queue) passes only one task to one of a group of workers\nat a time, cargo passes an array of tasks to a single worker, repeating\nwhen the worker is finished.\n\n__Arguments__\n\n* `worker(tasks, callback)` - An asynchronous function for processing an array of\n queued tasks, which must call its `callback(err)` argument when finished, with \n an optional `err` argument.\n* `payload` - An optional `integer` for determining how many tasks should be\n processed per round; if omitted, the default is unlimited.\n\n__Cargo objects__\n\nThe `cargo` object returned by this function has the following properties and\nmethods:\n\n* `length()` - A function returning the number of items waiting to be processed.\n* `payload` - An `integer` for determining how many tasks should be\n process per round. This property can be changed after a `cargo` is created to\n alter the payload on-the-fly.\n* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called\n once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` \n can be submitted. The respective callback is used for every task in the list.\n* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.\n* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.\n* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.\n\n__Example__\n\n```js\n// create a cargo object with payload 2\n\nvar cargo = async.cargo(function (tasks, callback) {\n for(var i=0; i\n### auto(tasks, [callback])\n\nDetermines the best order for running the functions in `tasks`, based on their \nrequirements. Each function can optionally depend on other functions being completed \nfirst, and each function is run as soon as its requirements are satisfied. \n\nIf any of the functions pass an error to their callback, it will not \ncomplete (so any other functions depending on it will not run), and the main \n`callback` is immediately called with the error. Functions also receive an \nobject containing the results of functions which have completed so far.\n\nNote, all functions are called with a `results` object as a second argument, \nso it is unsafe to pass functions in the `tasks` object which cannot handle the\nextra argument. \n\nFor example, this snippet of code:\n\n```js\nasync.auto({\n readData: async.apply(fs.readFile, 'data.txt', 'utf-8')\n}, callback);\n```\n\nwill have the effect of calling `readFile` with the results object as the last\nargument, which will fail:\n\n```js\nfs.readFile('data.txt', 'utf-8', cb, {});\n```\n\nInstead, wrap the call to `readFile` in a function which does not forward the \n`results` object:\n\n```js\nasync.auto({\n readData: function(cb, results){\n fs.readFile('data.txt', 'utf-8', cb);\n }\n}, callback);\n```\n\n__Arguments__\n\n* `tasks` - An object. Each of its properties is either a function or an array of\n requirements, with the function itself the last item in the array. The object's key\n of a property serves as the name of the task defined by that property,\n i.e. can be used when specifying requirements for other tasks.\n The function receives two arguments: (1) a `callback(err, result)` which must be \n called when finished, passing an `error` (which can be `null`) and the result of \n the function's execution, and (2) a `results` object, containing the results of\n the previously executed functions.\n* `callback(err, results)` - An optional callback which is called when all the\n tasks have been completed. It receives the `err` argument if any `tasks` \n pass an error to their callback. Results are always returned; however, if \n an error occurs, no further `tasks` will be performed, and the results\n object will only contain partial results.\n\n\n__Example__\n\n```js\nasync.auto({\n get_data: function(callback){\n console.log('in get_data');\n // async code to get some data\n callback(null, 'data', 'converted to array');\n },\n make_folder: function(callback){\n console.log('in make_folder');\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n callback(null, 'folder');\n },\n write_file: ['get_data', 'make_folder', function(callback, results){\n console.log('in write_file', JSON.stringify(results));\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n callback(null, 'filename');\n }],\n email_link: ['write_file', function(callback, results){\n console.log('in email_link', JSON.stringify(results));\n // once the file is written let's email a link to it...\n // results.write_file contains the filename returned by write_file.\n callback(null, {'file':results.write_file, 'email':'user@example.com'});\n }]\n}, function(err, results) {\n console.log('err = ', err);\n console.log('results = ', results);\n});\n```\n\nThis is a fairly trivial example, but to do this using the basic parallel and\nseries functions would look like this:\n\n```js\nasync.parallel([\n function(callback){\n console.log('in get_data');\n // async code to get some data\n callback(null, 'data', 'converted to array');\n },\n function(callback){\n console.log('in make_folder');\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n callback(null, 'folder');\n }\n],\nfunction(err, results){\n async.series([\n function(callback){\n console.log('in write_file', JSON.stringify(results));\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n results.push('filename');\n callback(null);\n },\n function(callback){\n console.log('in email_link', JSON.stringify(results));\n // once the file is written let's email a link to it...\n callback(null, {'file':results.pop(), 'email':'user@example.com'});\n }\n ]);\n});\n```\n\nFor a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding\nnew tasks much easier (and the code more readable).\n\n\n---------------------------------------\n\n\n### retry([times = 5], task, [callback])\n\nAttempts to get a successful response from `task` no more than `times` times before\nreturning an error. If the task is successful, the `callback` will be passed the result\nof the successfull task. If all attemps fail, the callback will be passed the error and\nresult (if any) of the final attempt.\n\n__Arguments__\n\n* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5.\n* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`\n which must be called when finished, passing `err` (which can be `null`) and the `result` of \n the function's execution, and (2) a `results` object, containing the results of\n the previously executed functions (if nested inside another control flow).\n* `callback(err, results)` - An optional callback which is called when the\n task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.\n\nThe [`retry`](#retry) function can be used as a stand-alone control flow by passing a\ncallback, as shown below:\n\n```js\nasync.retry(3, apiMethod, function(err, result) {\n // do something with the result\n});\n```\n\nIt can also be embeded within other control flow functions to retry individual methods\nthat are not as reliable, like this:\n\n```js\nasync.auto({\n users: api.getUsers.bind(api),\n payments: async.retry(3, api.getPayments.bind(api))\n}, function(err, results) {\n // do something with the results\n});\n```\n\n\n---------------------------------------\n\n\n### iterator(tasks)\n\nCreates an iterator function which calls the next function in the `tasks` array,\nreturning a continuation to call the next one after that. It's also possible to\n“peek” at the next iterator with `iterator.next()`.\n\nThis function is used internally by the `async` module, but can be useful when\nyou want to manually control the flow of functions in series.\n\n__Arguments__\n\n* `tasks` - An array of functions to run.\n\n__Example__\n\n```js\nvar iterator = async.iterator([\n function(){ sys.p('one'); },\n function(){ sys.p('two'); },\n function(){ sys.p('three'); }\n]);\n\nnode> var iterator2 = iterator();\n'one'\nnode> var iterator3 = iterator2();\n'two'\nnode> iterator3();\n'three'\nnode> var nextfn = iterator2.next();\nnode> nextfn();\n'three'\n```\n\n---------------------------------------\n\n\n### apply(function, arguments..)\n\nCreates a continuation function with some arguments already applied. \n\nUseful as a shorthand when combined with other control flow functions. Any arguments\npassed to the returned function are added to the arguments originally passed\nto apply.\n\n__Arguments__\n\n* `function` - The function you want to eventually apply all arguments to.\n* `arguments...` - Any number of arguments to automatically apply when the\n continuation is called.\n\n__Example__\n\n```js\n// using apply\n\nasync.parallel([\n async.apply(fs.writeFile, 'testfile1', 'test1'),\n async.apply(fs.writeFile, 'testfile2', 'test2'),\n]);\n\n\n// the same process without using apply\n\nasync.parallel([\n function(callback){\n fs.writeFile('testfile1', 'test1', callback);\n },\n function(callback){\n fs.writeFile('testfile2', 'test2', callback);\n }\n]);\n```\n\nIt's possible to pass any number of additional arguments when calling the\ncontinuation:\n\n```js\nnode> var fn = async.apply(sys.puts, 'one');\nnode> fn('two', 'three');\none\ntwo\nthree\n```\n\n---------------------------------------\n\n\n### nextTick(callback)\n\nCalls `callback` on a later loop around the event loop. In Node.js this just\ncalls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`\nif available, otherwise `setTimeout(callback, 0)`, which means other higher priority\nevents may precede the execution of `callback`.\n\nThis is used internally for browser-compatibility purposes.\n\n__Arguments__\n\n* `callback` - The function to call on a later loop around the event loop.\n\n__Example__\n\n```js\nvar call_order = [];\nasync.nextTick(function(){\n call_order.push('two');\n // call_order now equals ['one','two']\n});\ncall_order.push('one')\n```\n\n\n### times(n, callback)\n\nCalls the `callback` function `n` times, and accumulates results in the same manner\nyou would use with [`map`](#map).\n\n__Arguments__\n\n* `n` - The number of times to run the function.\n* `callback` - The function to call `n` times.\n\n__Example__\n\n```js\n// Pretend this is some complicated async factory\nvar createUser = function(id, callback) {\n callback(null, {\n id: 'user' + id\n })\n}\n// generate 5 users\nasync.times(5, function(n, next){\n createUser(n, function(err, user) {\n next(err, user)\n })\n}, function(err, users) {\n // we should now have 5 users\n});\n```\n\n\n### timesSeries(n, callback)\n\nThe same as [`times`](#times), only the iterator is applied to each item in `arr` in\nseries. The next `iterator` is only called once the current one has completed. \nThe results array will be in the same order as the original.\n\n\n## Utils\n\n\n### memoize(fn, [hasher])\n\nCaches the results of an `async` function. When creating a hash to store function\nresults against, the callback is omitted from the hash and an optional hash\nfunction can be used.\n\nThe cache of results is exposed as the `memo` property of the function returned\nby `memoize`.\n\n__Arguments__\n\n* `fn` - The function to proxy and cache results from.\n* `hasher` - Tn optional function for generating a custom hash for storing\n results. It has all the arguments applied to it apart from the callback, and\n must be synchronous.\n\n__Example__\n\n```js\nvar slow_fn = function (name, callback) {\n // do something\n callback(null, result);\n};\nvar fn = async.memoize(slow_fn);\n\n// fn can now be used as if it were slow_fn\nfn('some name', function () {\n // callback\n});\n```\n\n\n### unmemoize(fn)\n\nUndoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized\nform. Handy for testing.\n\n__Arguments__\n\n* `fn` - the memoized function\n\n\n### log(function, arguments)\n\nLogs the result of an `async` function to the `console`. Only works in Node.js or\nin browsers that support `console.log` and `console.error` (such as FF and Chrome).\nIf multiple arguments are returned from the async function, `console.log` is\ncalled on each argument in order.\n\n__Arguments__\n\n* `function` - The function you want to eventually apply all arguments to.\n* `arguments...` - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n setTimeout(function(){\n callback(null, 'hello ' + name);\n }, 1000);\n};\n```\n```js\nnode> async.log(hello, 'world');\n'hello world'\n```\n\n---------------------------------------\n\n\n### dir(function, arguments)\n\nLogs the result of an `async` function to the `console` using `console.dir` to\ndisplay the properties of the resulting object. Only works in Node.js or\nin browsers that support `console.dir` and `console.error` (such as FF and Chrome).\nIf multiple arguments are returned from the async function, `console.dir` is\ncalled on each argument in order.\n\n__Arguments__\n\n* `function` - The function you want to eventually apply all arguments to.\n* `arguments...` - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n setTimeout(function(){\n callback(null, {hello: name});\n }, 1000);\n};\n```\n```js\nnode> async.dir(hello, 'world');\n{hello: 'world'}\n```\n\n---------------------------------------\n\n\n### noConflict()\n\nChanges the value of `async` back to its original value, returning a reference to the\n`async` object.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/caolan/async#readme", + "_id": "async@0.9.0", + "_shasum": "ac3613b1da9bed1b47510bb4651b8931e47146c7", + "_resolved": "https://registry.npmjs.org/async/-/async-0.9.0.tgz", + "_from": "async@0.9.0" +} diff --git a/node_modules/mongoose/node_modules/bson/.travis.yml b/node_modules/mongoose/node_modules/bson/.travis.yml new file mode 100644 index 0000000..1e8f317 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.10 # development version of 0.8, may be unstable + - 0.12 \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/HISTORY b/node_modules/mongoose/node_modules/bson/HISTORY new file mode 100644 index 0000000..60033b3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/HISTORY @@ -0,0 +1,42 @@ +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/LICENSE b/node_modules/mongoose/node_modules/bson/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/mongoose/node_modules/bson/README.md b/node_modules/mongoose/node_modules/bson/README.md new file mode 100644 index 0000000..5cac5b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/README.md @@ -0,0 +1,69 @@ +Javascript + C++ BSON parser +============================ + +This BSON parser is primarily meant to be used with the `mongodb` node.js driver. +However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. +The current build is located in the `browser_build/bson.js` file. + +A simple example of how to use BSON in the browser: + +```html + + + + + + + + +``` + +A simple example of how to use BSON in `node.js`: + +```javascript +var bson = require("bson"); +var BSON = bson.BSONPure.BSON; +var Long = bson.BSONPure.Long; + +var doc = {long: Long.fromNumber(100)} + +// Serialize a document +var data = BSON.serialize(doc, false, true, false); +console.log("data:", data); + +// Deserialize the resulting Buffer +var doc_2 = BSON.deserialize(data); +console.log("doc_2:", doc_2); +``` + +The API consists of two simple methods to serialize/deserialize objects to/from BSON format: + + * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** + * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports + + * BSON.deserialize(buffer, options, isArray) + * Options + * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * @param {TypedArray/Array} a TypedArray/Array containing the BSON data + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. diff --git a/node_modules/mongoose/node_modules/bson/browser_build/bson.js b/node_modules/mongoose/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..8e942dd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/browser_build/bson.js @@ -0,0 +1,4843 @@ +var bson = (function(){ + + var pkgmap = {}, + global = {}, + nativeRequire = typeof require != 'undefined' && require, + lib, ties, main, async; + + function exports(){ return main(); }; + + exports.main = exports; + exports.module = module; + exports.packages = pkgmap; + exports.pkg = pkg; + exports.require = function require(uri){ + return pkgmap.main.index.require(uri); + }; + + + ties = {}; + + aliases = {}; + + + return exports; + +function join() { + return normalize(Array.prototype.join.call(arguments, "/")); +}; + +function normalize(path) { + var ret = [], parts = path.split('/'), cur, prev; + + var i = 0, l = parts.length-1; + for (; i <= l; i++) { + cur = parts[i]; + + if (cur === "." && prev !== undefined) continue; + + if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { + ret.pop(); + prev = ret.slice(-1)[0]; + } else { + if (prev === ".") ret.pop(); + ret.push(cur); + prev = cur; + } + } + + return ret.join("/"); +}; + +function dirname(path) { + return path && path.substr(0, path.lastIndexOf("/")) || "."; +}; + +function findModule(workingModule, uri){ + var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), + moduleIndexId = join(moduleId, 'index'), + pkg = workingModule.pkg, + module; + + var i = pkg.modules.length, + id; + + while(i-->0){ + id = pkg.modules[i].id; + + if(id==moduleId || id == moduleIndexId){ + module = pkg.modules[i]; + break; + } + } + + return module; +} + +function newRequire(callingModule){ + function require(uri){ + var module, pkg; + + if(/^\./.test(uri)){ + module = findModule(callingModule, uri); + } else if ( ties && ties.hasOwnProperty( uri ) ) { + return ties[uri]; + } else if ( aliases && aliases.hasOwnProperty( uri ) ) { + return require(aliases[uri]); + } else { + pkg = pkgmap[uri]; + + if(!pkg && nativeRequire){ + try { + pkg = nativeRequire(uri); + } catch (nativeRequireError) {} + + if(pkg) return pkg; + } + + if(!pkg){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module = pkg.index; + } + + if(!module){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module.parent = callingModule; + return module.call(); + }; + + + return require; +} + + +function module(parent, id, wrapper){ + var mod = { pkg: parent, id: id, wrapper: wrapper }, + cached = false; + + mod.exports = {}; + mod.require = newRequire(mod); + + mod.call = function(){ + if(cached) { + return mod.exports; + } + + cached = true; + + global.require = mod.require; + + mod.wrapper(mod, mod.exports, global, global.require); + return mod.exports; + }; + + if(parent.mainModuleId == mod.id){ + parent.index = mod; + parent.parents.length === 0 && ( main = mod.call ); + } + + parent.modules.push(mod); +} + +function pkg(/* [ parentId ...], wrapper */){ + var wrapper = arguments[ arguments.length - 1 ], + parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), + ctx = wrapper(parents); + + + pkgmap[ctx.name] = ctx; + + arguments.length == 1 && ( pkgmap.main = ctx ); + + return function(modules){ + var id; + for(id in modules){ + module(ctx, id, modules[id]); + } + }; +} + + +}(this)); + +bson.pkg(function(parents){ + + return { + 'name' : 'bson', + 'mainModuleId' : 'bson', + 'modules' : [], + 'parents' : parents + }; + +})({ 'binary': function(module, exports, global, require, undefined){ + /** + * Module dependencies. + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +// Binary default subtype +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + * @api private + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + * @api private + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class Represents the Binary BSON type. + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Grid} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @param {Character} byte_value a single byte we wish to write. + * @api public + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. + * @param {Number} offset specify the binary of where to write the content. + * @api public + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, 'binary', offset); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @param {Number} position read from the given position in the Binary. + * @param {Number} length the number of bytes to read. + * @return {Buffer} + * @api public + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @return {String} + * @api public + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @return {Number} the length of the binary. + * @api public + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + * @api private + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + * @api private + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +exports.Binary = Binary; + + +}, + + + +'binary_parser': function(module, exports, global, require, undefined){ + /** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; + +}, + + + +'bson': function(module, exports, global, require, undefined){ + var Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser + , writeIEEE754 = require('./float_parser').writeIEEE754 + , readIEEE754 = require('./float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class Represents the BSON Parser + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + var startIndex = index; + + switch(typeof value) { + case 'string': + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] || true; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00) { i++ } + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +exports.Code = Code; +exports.Symbol = Symbol; +exports.BSON = BSON; +exports.DBRef = DBRef; +exports.Binary = Binary; +exports.ObjectID = ObjectID; +exports.Long = Long; +exports.Timestamp = Timestamp; +exports.Double = Double; +exports.MinKey = MinKey; +exports.MaxKey = MaxKey; + +}, + + + +'code': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Code type. + * + * @class Represents the BSON Code type. + * @param {String|Function} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + * @api private + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +exports.Code = Code; +}, + + + +'db_ref': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON DBRef type. + * + * @class Represents the BSON DBRef type. + * @param {String} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {String} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +exports.DBRef = DBRef; +}, + + + +'double': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Double type. + * + * @class Represents the BSON Double type. + * @param {Number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @return {Number} returns the wrapped double number. + * @api public + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + * @api private + */ +Double.prototype.toJSON = function() { + return this.value; +} + +exports.Double = Double; +}, + + + +'float_parser': function(module, exports, global, require, undefined){ + // Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; +}, + + + +'index': function(module, exports, global, require, undefined){ + try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('../../ext'); +} catch(err) { + // do nothing +} + +[ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + exports[i] = module[i]; + } +}); + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '../../ext' +].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +// Exports all the classes for the PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '././bson'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +}, + + + +'long': function(module, exports, global, require, undefined){ + // Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class Represents the BSON Long type. + * @param {Number} low the low (signed) 32 bits of the Long. + * @param {Number} high the high (signed) 32 bits of the Long. + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @api private + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @api private + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {Number} the value, assuming it is a 32-bit integer. + * @api public + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @return {Number} the closest floating-point representation to this value. + * @api public + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @return {String} the JSON representation. + * @api public + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @param {Number} [opt_radix] the radix in which the text should be written. + * @return {String} the textual representation of this value. + * @api public + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @return {Number} the high 32-bits as a signed value. + * @api public + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @return {Number} the low 32-bits as a signed value. + * @api public + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @return {Number} the low 32-bits as an unsigned value. + * @api public + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. + * @api public + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @return {Boolean} whether this value is zero. + * @api public + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @return {Boolean} whether this value is negative. + * @api public + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @return {Boolean} whether this value is odd. + * @api public + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long equals the other + * @api public + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long does not equal the other. + * @api public + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is less than the other. + * @api public + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is less than or equal to the other. + * @api public + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is greater than the other. + * @api public + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is greater than or equal to the other. + * @api public + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @param {Long} other Long to compare against. + * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + * @api public + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @return {Long} the negation of this value. + * @api public + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + * @api public + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + * @api public + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + * @api public + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + * @api public + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + * @api public + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @return {Long} the bitwise-NOT of this value. + * @api public + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + * @api public + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + * @api public + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + * @api public + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + * @api public + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + * @api public + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + * @api public + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @param {Number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @param {Number} value the number in question. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @param {Number} lowBits the low 32-bits. + * @param {Number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @param {String} str the textual representation of the Long. + * @param {Number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @api private + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @api private + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @api private + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +exports.Long = Long; +}, + + + +'max_key': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON MaxKey type. + * + * @class Represents the BSON MaxKey type. + * @return {MaxKey} + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +exports.MaxKey = MaxKey; +}, + + + +'min_key': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON MinKey type. + * + * @class Represents the BSON MinKey type. + * @return {MinKey} + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +exports.MinKey = MinKey; +}, + + + +'objectid': function(module, exports, global, require, undefined){ + /** + * Module dependencies. + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class Represents the BSON ObjectID type +* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @return {Object} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id, _hex) { + if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); + + this._bsontype = 'ObjectID'; + var __id = null; + + // Throw an error if it's not a valid setup + if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + // Generate id based on the input + if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if(checkForHexRegExp.test(id)) { + return ObjectID.createFromHexString(id); + } else { + throw new Error("Value passed in is not a valid 24 character hex string"); + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @return {String} return the 24 byte hex string representation. +* @api public +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @return {Number} returns next index value. +* @api private +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @return {Number} returns next index value. +* @api private +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {String} return the 12 byte id binary string. +* @api private +*/ +ObjectID.prototype.generate = function(time) { + if ('number' == typeof time) { + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + } else { + var unixTime = parseInt(Date.now()/1000,10); + var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + } + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @param {Object} otherID ObjectID instance to compare against. +* @return {Bool} the result of comparing two ObjectID's +* @api public +*/ +ObjectID.prototype.equals = function equals (otherID) { + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @return {Date} the generation date +* @api public +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +* @api private +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @param {Number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +* @api public +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +* @api public +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +exports.ObjectID = ObjectID; +exports.ObjectId = ObjectID; + +}, + + + +'symbol': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Symbol type. + * + * @class Represents the BSON Symbol type. + * @param {String} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @return {String} returns the wrapped string. + * @api public + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + * @api private + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + * @api private + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + * @api private + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +exports.Symbol = Symbol; +}, + + + +'timestamp': function(module, exports, global, require, undefined){ + // Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class Represents the BSON Timestamp type. + * @param {Number} low the low (signed) 32 bits of the Timestamp. + * @param {Number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @api private + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @api private + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {Number} the value, assuming it is a 32-bit integer. + * @api public + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @return {Number} the closest floating-point representation to this value. + * @api public + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @return {String} the JSON representation. + * @api public + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @param {Number} [opt_radix] the radix in which the text should be written. + * @return {String} the textual representation of this value. + * @api public + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @return {Number} the high 32-bits as a signed value. + * @api public + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @return {Number} the low 32-bits as a signed value. + * @api public + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @return {Number} the low 32-bits as an unsigned value. + * @api public + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. + * @api public + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @return {Boolean} whether this value is zero. + * @api public + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @return {Boolean} whether this value is negative. + * @api public + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @return {Boolean} whether this value is odd. + * @api public + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp equals the other + * @api public + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp does not equal the other. + * @api public + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is less than the other. + * @api public + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is less than or equal to the other. + * @api public + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is greater than the other. + * @api public + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is greater than or equal to the other. + * @api public + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + * @api public + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @return {Timestamp} the negation of this value. + * @api public + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + * @api public + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + * @api public + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + * @api public + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + * @api public + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + * @api public + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @return {Timestamp} the bitwise-NOT of this value. + * @api public + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + * @api public + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + * @api public + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + * @api public + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + * @api public + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + * @api public + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + * @api public + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @param {Number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @param {Number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @param {Number} lowBits the low 32-bits. + * @param {Number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @param {String} str the textual representation of the Timestamp. + * @param {Number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @api private + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @api private + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +exports.Timestamp = Timestamp; +}, + + }); + + +if(typeof module != 'undefined' && module.exports ){ + module.exports = bson; + + if( !module.parent ){ + bson(); + } +} + +if(typeof window != 'undefined' && typeof require == 'undefined'){ + window.require = bson.require; +} diff --git a/node_modules/mongoose/node_modules/bson/browser_build/package.json b/node_modules/mongoose/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..3ebb587 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../lib/bson/bson" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/binary.js b/node_modules/mongoose/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..5d0acfa --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * Module dependencies. + * @ignore + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, 'binary', offset); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + return this.buffer; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js b/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js new file mode 100644 index 0000000..d2fc811 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js @@ -0,0 +1,385 @@ +/** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/bson.js b/node_modules/mongoose/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..fc57600 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,1573 @@ +var Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser + , writeIEEE754 = require('./float_parser').writeIEEE754 + , readIEEE754 = require('./float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + var startIndex = index; + + switch(typeof value) { + case 'string': + // console.log("+++++++++++ index string:: " + index) + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // console.log("====== key :: " + name + " size ::" + size) + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // console.log("+++++++++++ index OBJECTID:: " + index) + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) + // console.log(buffer.toString('hex')) + // console.log(buffer.toString('ascii')) + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_UNDEFINED: + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +exports.Code = Code; +exports.Symbol = Symbol; +exports.BSON = BSON; +exports.DBRef = DBRef; +exports.Binary = Binary; +exports.ObjectID = ObjectID; +exports.Long = Long; +exports.Timestamp = Timestamp; +exports.Double = Double; +exports.MinKey = MinKey; +exports.MaxKey = MaxKey; diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/bson_new.js b/node_modules/mongoose/node_modules/bson/lib/bson/bson_new.js new file mode 100644 index 0000000..0b1b38d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/bson_new.js @@ -0,0 +1,776 @@ +var writeIEEE754 = require('./float_parser').writeIEEE754 + , Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser; + +// Max Document Buffer size +var buffer = new Buffer(1024 * 1024 * 16); + +var checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +var serializeString = function(key, value, index) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = Buffer.byteLength(value) + 1; + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + buffer.write(value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeNumber = function(key, value, index) { + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +} + +var serializeUndefined = function(key, value, index) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeBoolean = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +var serializeDate = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeRegExp = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + Buffer.byteLength(value.source); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeMinMax = function(key, value, index) { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeObjectId = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + for(var j = 0; j < 12; j++) { + buffer[index + j] = value.binId[j]; + } + + // Ajust index + index = index + 12; + return index; +} + +var serializeBuffer = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +} + +var serializeObject = function(key, value, index, checkKeys, depth) { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(value, checkKeys, index, depth + 1); + // Write size + var size = endIndex - index; + return endIndex; +} + +var serializeLong = function(key, value, index) { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeDouble = function(key, value, index) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +} + +var serializeCode = function(key, value, index, checkKeys, depth) { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); + var codeSize = Buffer.byteLength(functionString) + 1; + // Index adjustment + index = index + 4; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write string into buffer + buffer.write(functionString, index + 4, 'utf8'); + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(value.scope, checkKeys, index, depth + 1) + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = Buffer.byteLength(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(functionString, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +var serializeBinary = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +} + +var serializeSymbol = function(key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Calculate size + var size = Buffer.byteLength(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +var serializeDBRef = function(key, value, index, depth) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if(null != value.db) { + endIndex = serializeInto({ + '$ref': value.namespace + , '$id' : value.oid + , '$db' : value.db + }, false, index, depth + 1); + } else { + endIndex = serializeInto({ + '$ref': value.namespace + , '$id' : value.oid + }, false, index, depth + 1); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} + +var BSON = function() { + this.buffer = buffer; +} + +BSON.prototype.serialize = function serialize(object, checkKeys, index) { + var finishedBuffer = new Buffer(serializeInto(object, checkKeys, index || 0, 0)); + this.buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + return finishedBuffer; +} + +var serializeInto = function serializeInto(object, checkKeys, startingIndex, depth) { + startingIndex = startingIndex || 0; + + // Start place to serialize into + var index = startingIndex + 4; + var self = this; + + // Special case isArray + if(Array.isArray(object)) { + // Get object keys + for(var i = 0; i < object.length; i++) { + var key = "" + i; + var type = typeof object[i]; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + checkKey(key, !checkKeys); + } + + if(type == 'string') { + index = serializeString(key, object[i], index); + } else if(type == 'number') { + index = serializeNumber(key, object[i], index); + } else if(type == 'undefined') { + index = serializeUndefined(key, object[i], index); + } else if(type == 'boolean') { + index = serializeBoolean(key, object[i], index); + } else if(object[i] instanceof Date) { + index = serializeDate(key, object[i], index); + } else if(object[i] instanceof RegExp || Object.prototype.toString.call(object[i]) === '[object RegExp]') { + index = serializeRegExp(key, object[i], index); + } else if(object[i]['_bsontype'] == 'MinKey' || object[i]['_bsontype'] == 'MaxKey') { + index = serializeMinMax(key, object[i], index); + } else if(object[i]['_bsontype'] == 'ObjectID') { + index = serializeObjectId(key, object[i], index); + } else if(Buffer.isBuffer(object[i])) { + index = serializeBuffer(key, object[i], index); + } else if(type == 'object' && object[i]['_bsontype'] == null) { + index = serializeObject(key, object[i], index, checkKeys, depth); + } else if(object[i]['_bsontype'] == 'Long' || object[i]['_bsontype'] == 'Timestamp') { + index = serializeLong(key, object[i], index); + } else if(object[i]['_bsontype'] == 'Double') { + index = serializeDouble(key, object[i], index); + } else if(object[i]['_bsontype'] == 'Code') { + index = serializeCode(key, object[i], index, checkKeys, depth); + } else if(object[i]['_bsontype'] == 'Binary') { + index = serializeBinary(key, object[i], index); + } else if(object[i]['_bsontype'] == 'Symbol') { + index = serializeSymbol(key, object[i], index); + } else if(object[i]['_bsontype'] == 'DBRef') { + index = serializeDBRef(key, object[i], index, depth); + } + } + } else { + var keys = Object.keys(object); + for(var i = 0; i < keys.length; i++) { + var key = keys[i]; + var type = typeof object[key]; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + checkKey(key, !checkKeys); + } + + if(type == 'string') { + index = serializeString(key, object[key], index); + } else if(type == 'number') { + index = serializeNumber(key, object[key], index); + } else if(type == 'undefined') { + index = serializeUndefined(key, object[key], index); + } else if(type == 'boolean') { + index = serializeBoolean(key, object[key], index); + } else if(object[key] instanceof Date) { + index = serializeDate(key, object[key], index); + } else if(object[key] instanceof RegExp || Object.prototype.toString.call(object[key]) === '[object RegExp]') { + index = serializeRegExp(key, object[key], index); + } else if(object[key]['_bsontype'] == 'MinKey' || object[key]['_bsontype'] == 'MaxKey') { + index = serializeMinMax(key, object[key], index); + } else if(object[key]['_bsontype'] == 'ObjectID') { + index = serializeObjectId(key, object[key], index); + } else if(Buffer.isBuffer(object[key])) { + index = serializeBuffer(key, object[key], index); + } else if(type == 'object' && object[key]['_bsontype'] == null) { + index = serializeObject(key, object[key], index, checkKeys, depth); + } else if(object[key]['_bsontype'] == 'Long' || object[key]['_bsontype'] == 'Timestamp') { + index = serializeLong(key, object[key], index); + } else if(object[key]['_bsontype'] == 'Double') { + index = serializeDouble(key, object[key], index); + } else if(object[key]['_bsontype'] == 'Code') { + index = serializeCode(key, object[key], index, checkKeys, depth); + } else if(object[key]['_bsontype'] == 'Binary') { + index = serializeBinary(key, object[key], index); + } else if(object[key]['_bsontype'] == 'Symbol') { + index = serializeSymbol(key, object[key], index); + } else if(object[key]['_bsontype'] == 'DBRef') { + index = serializeDBRef(key, object[key], index, depth); + } + } + } + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +exports.BSON = BSON; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/code.js b/node_modules/mongoose/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +module.exports = Code; +module.exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js b/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +module.exports = DBRef; +module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/double.js b/node_modules/mongoose/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +} + +module.exports = Double; +module.exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js b/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..6fca392 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,121 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/index.js b/node_modules/mongoose/node_modules/bson/lib/bson/index.js new file mode 100644 index 0000000..04a7ef4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/index.js @@ -0,0 +1,81 @@ +try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('bson-ext'); +} catch(err) { + // do nothing +} + +[ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + exports[i] = module[i]; + } +}); + +// Exports all the classes for the PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '././bson'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + ].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + + // Catch error and return no classes found + try { + classes['BSON'] = require('bson-ext') + } catch(err) { + return exports.pure(); + } + + // Return classes list + return classes; +} diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/long.js b/node_modules/mongoose/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js b/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js b/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js b/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..1d4894a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,274 @@ +/** + * Module dependencies. + * @ignore + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + if(!(this instanceof ObjectID)) return new ObjectID(id); + if((id instanceof ObjectID)) return id; + + this._bsontype = 'ObjectID'; + var __id = null; + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if(!valid && id != null){ + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if(valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {string} return the 12 byte id binary string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' != typeof time) { + time = parseInt(Date.now()/1000,10); + } + + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals (otherID) { + if(otherID == null) return false; + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if(id == null) return false; + + if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) { + return false; + } else { + // Check specifically for hex correctness + if(typeof id == 'string' && id.length == 24) return checkForHexRegExp.test(id); + return true; + } +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js b/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +module.exports = Symbol; +module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js b/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/.npmignore new file mode 100644 index 0000000..8de3cca --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/.npmignore @@ -0,0 +1,38 @@ +.travis.yml +appveyor.yml +test.bat +build/ +test/ +.vagrant/ + +# Users Environment Variables +.lock-wscript + +.DS_Store +*.swp +*.seed +.project +.settings +./data +node_modules/ + +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/HISTORY b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/HISTORY new file mode 100644 index 0000000..a550203 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/HISTORY @@ -0,0 +1,31 @@ +0.1.7 2015-05-15 +---------------- +- Attempt node-pre-gyp otherwise fallback to node-gyp or just fail. + +0.1.6 2015-05-07 +---------------- +- Updated to use bundled node-pre-gyp as install method. + +0.1.5 2015-05-07 +---------------- +- Updated npmignore to remove any non-needed artifacts. + +0.1.4 2015-05-05 +---------------- +- Updated nan.h dependency to 1.8.x. + +0.1.3 2015-04-23 +---------------- +- Windows only prebuilt support (Issue #6, https://github.com/imlucas) + +0.1.2 2015-04-20 +---------------- +- Removed pre-packaged binaries from build. + +0.1.1 2015-04-20 +---------------- +- Merged node-pre-gyp support (Issue #1, https://github.com/imlucas) + +0.1.0 2015-03-26 +---------------- +- First pusht to npm, cleanup of project and left only c++ and test harnesses. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/Makefile new file mode 100644 index 0000000..2ca5592 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/Makefile @@ -0,0 +1,16 @@ +NODE = node +NPM = npm +NODEUNIT = node_modules/nodeunit/bin/nodeunit + +all: clean node_gyp + +test: clean node_gyp + npm test + +node_gyp: clean + node-gyp configure build + +clean: + node-gyp clean + +.PHONY: all diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/README.md new file mode 100644 index 0000000..8086853 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/README.md @@ -0,0 +1,37 @@ +# bson-ext + +[![linux build status](https://secure.travis-ci.org/imlucas/bson-ext.png)](http://travis-ci.org/imlucas/bson-ext) +[![windows build status](https://ci.appveyor.com/api/projects/status/github/imlucas/bson-ext)](https://ci.appveyor.com/project/imlucas/bson-ext) + +This module contains the BSON [native addon](https://nodejs.org/api/addons.html) +only and is not meant to be used in isolation from the [bson](http://npm.im/bson) +NPM module. It lives in it's own module so it can be an optional +dependency for the [bson](http://npm.im/bson) module. + +## Testing + +``` +npm test +``` + +## Prebuilt Binaries + +Have you ever seen this message in your console? + +``` +js-bson: Failed to load c++ bson extension, using pure JS version +``` + +We are experimenting with [node-pre-gyp](http://npm.im/node-pre-gyp) to publish +and install prebuilt binaries. This means you don't need the full toolchain installed +and configured correctly to use this module and you'll never have to see this +message again. Currently, prebuilt binaries will only be used for Windows, +as it is the most problematic platform for this issue. This will also allow us +more time to evaluate the costs and benefits of prebuilt support on OSX and Linux. + +If you are interested in prebuilt binary support on OSX or Linux, please +[join the discussion on this issue](https://github.com/christkv/bson-ext/issues/6)! + +## License + +Apache 2 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/binding.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/binding.gyp new file mode 100644 index 0000000..91ca717 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/binding.gyp @@ -0,0 +1,30 @@ +{ + 'targets': [ + { + 'win_delay_load_hook': 'true', + 'target_name': 'bson', + 'sources': [ 'ext/bson.cc' ], + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions' ], + 'include_dirs': [ '> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef + +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_objc = CXX($(TOOLSET)) $@ +cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< + +quiet_cmd_objcxx = CXX($(TOOLSET)) $@ +cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# Commands for precompiled header files. +quiet_cmd_pch_c = CXX($(TOOLSET)) $@ +cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ +cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_m = CXX($(TOOLSET)) $@ +cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< +quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ +cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# gyp-mac-tool is written next to the root Makefile by gyp. +# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd +# already. +quiet_cmd_mac_tool = MACTOOL $(4) $< +cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" + +quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ +cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) + +quiet_cmd_infoplist = INFOPLIST $@ +cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" + +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = rm -rf "$@" && cp -af "$<" "$@" + +quiet_cmd_alink = LIBTOOL-STATIC $@ +cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) + +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) + + +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' + +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain ? instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds until one fails. +define do_postbuilds + @E=0;\ + for p in $(POSTBUILDS); do\ + eval $$p;\ + E=$$?;\ + if [ $$E -ne 0 ]; then\ + break;\ + fi;\ + done;\ + if [ $$E -ne 0 ]; then\ + rm -rf "$@";\ + exit $$E;\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains ? for +# spaces already and dirx strips the ? characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word 2,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "all" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: all +all: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +TOOLSET := target +# Suffix rules, putting all outputs into $(obj). +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + + +ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ + $(findstring $(join ^,$(prefix)),\ + $(join ^,bson.target.mk)))),) + include bson.target.mk +endif + +quiet_cmd_regen_makefile = ACTION Regenerating $@ +cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/SEmmer/Developer/node_projects/mongoose-seed/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/SEmmer/.node-gyp/0.12.0/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/SEmmer/.node-gyp/0.12.0" "-Dmodule_root_dir=/Users/SEmmer/Developer/node_projects/mongoose-seed/node_modules/mongoose/node_modules/bson/node_modules/bson-ext" binding.gyp +Makefile: $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../.node-gyp/0.12.0/common.gypi + $(call do_cmd,regen_makefile) + +# "all" is a concatenation of the "all" targets from all the included +# sub-makefiles. This is just here to clarify. +all: + +# Add in dependency-tracking rules. $(all_deps) is the list of every single +# target in our tree. Only consider the ones with .d (dependency) info: +d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) +ifneq ($(d_files),) + include $(d_files) +endif diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/bson.node.d b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/bson.node.d new file mode 100644 index 0000000..b3465a6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/bson.node.d @@ -0,0 +1 @@ +cmd_Release/bson.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -bundle -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -o Release/bson.node Release/obj.target/bson/ext/bson.o -undefined dynamic_lookup diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d new file mode 100644 index 0000000..9560f26 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d @@ -0,0 +1,38 @@ +cmd_Release/obj.target/bson/ext/bson.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/Users/SEmmer/.node-gyp/0.12.0/src -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include -I../node_modules/nan -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc +Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_version.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h ../ext/bson.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h \ + ../node_modules/nan/nan.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h +../ext/bson.cc: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_version.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h: +/Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h: +../ext/bson.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h: +../node_modules/nan/nan.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/bson.node b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/bson.node new file mode 100755 index 0000000000000000000000000000000000000000..6f18ce5db3d119d7b6ac298f62fcbcb4838c2c9b GIT binary patch literal 63500 zcmeFadwf*I`9FR_5{TRqyy6926f`Ij0t5ppCXm2J0t5j?1w%*{5)DaAb^$G5FbT3O zt5|P%En019t1Y&Qh@erB#Y-((s#vX{RXc0cQniYR=KFp>GiP)5B%t=w&*zWdkMqi0 zo_Q|w%ro~nXD5H!|H*e&Lw_KU>e(<7p}Otuwdf&{Ja8t%v(n+o+2Gs z2JTK`Jgf(29_%Z<;nE(ntUG}4zlu6M-Llv{Z4qB1PL~OHCTQj%JlNCxN6Y#I$a;ig z8|2R+=|ni@v%k|%XS{yRxg}5Tto`)b$v^w3AJWp`tmLki)wQdP>ui&xm42L1j#w8f zBT!eHQCTsYuFhXpde&Kkh7UrQshABk9u7}&eAZ@EZ$cd3lxynzzIlU2ADZt(lrWx; zBV^s6OedQK6N%oHX4S%O=YId!%}~qkF+PgBj>aoFjHahOSK0i&v3)1YJ|AA zHJU4M8Z|WshD%Q8=I;vh@P>VRF3+7|?E4Q0Drku0c*8x?QMQ)e1{g)4n*oXdWWtcJ z-YeeVU)5DG0L$bJp5sLw!lik`dA)!h*SmgEuU0G2Y33G490tB;a-a(9{}nY1Y|;Y1 zkMBSrj_<&?HXoZ?7jI}RYHD1H3DYDD=XH|oy$Kg1VO($Txnp}T=u(dc-c3~bBSf}z zflh1UWv{Vi&y3y$14~UwEB6$J7NivhKlcXT^oB1@@CJ)TZv6<$pX?p6rS>22=AWlh zOW4*Iqb+Pxb+gb0zJup&Xs%)1ABi2hjVxk18WL#L35d6xoEO~t)sBQM>SaLER?wJ& zZ>on3VQ?4vfd~Bn`jamoc|_FiVv5T@Cx|0)KAUp3w5j%q=k)D|%%% zH@@aS%iH>FW^?^>J5txb*08^8UB9cEyJ~@xTf=#2J67}pLE~$Izj<3S5#pcV~ZV;oUGp^d_U9cJ{QnJ#8hsGIlP z33~%wWPHKc(gI6ME_z(^2fNCYRuoEB3B>| zMQ=h_5ZqP}%IlX_5Gw4~8~wU&eqQSOZ@ghIM$E!~X#mm-ga1%P(1R_5WeG52VY+B)4bq*btRz87Yc)4!R+4PbLv!P z?98?HMr57ZbQb6eLMQc8{i$InltR8Qy-hFpdwN5eRC(k~s=f`P)JupqHm5djL(amq zm$*=f=Wg*#$!$z4B$~fY7@pA#?Q_{VBbLjhnqh-5+^8AS+U4-`HimS~&@2oyg<*Vl zW~;Lh0iljySYP*aBD7c8x*||bo0hQ*7UrfMfg=lpd-e1*BX_15LLa1I!aa6eZAO@n z5P2pCGW4i7>g#rGVCl#EfX)rR9{iWgrDtD?EDA#T(iE0{{T-0kjcWLM$#s*$xvdTR zdZpfQ8aQXk{RV6=2AmFCQ0 z7yLIQ3upbZt-Qe()uer`tp)L2y}<73??Jw!tE-KGTW)7x!rY>2F;=uJx1sr+Ei1YJ zLo$mQ>RlL~l{_IhmyN$BDYxOfPJy1G>B%Va5iD{+aI0#9u;5!zzcBbAC#lVV3lcDD z2lMMyIRK#YFkMg9QFWr!c>Z#lqkw6l@#*pAD7j3S&?f4mNwBFpm1N<~DbR`oK?Crr zC)3P$e=0?`;b#gzhHl}Ao|MG?*Q)wqP=Hdaneh&igvNW~Ggg-(HOR)e`f0RlD;feT z?V!hiNoknZQX3o4PSs5m5Z;__RN4zp^%I@1suSUL3t6SNQDht4bCLs9BWH9eL`ie< zrk>fZJ*l%qUIcAT+L`(ln4@oF^ijQZ?uxCCBO`PFmZFV8dTE2%_`+DOOo?_wt~AIE zXfoaqmJu&{8{WexwqHiE$r!~h>b7)$1KV+rPyt4b~L<{(DG7;?Q>SE8V&vOGrw$WqVKBXw94uX2_x#C z(^)k$*P#M2{+yyxnI0NH*g2LA01d`)8B3ss)lzb>3||GME5lz%22JJC@=sB}BN!T= zjq>>hb!8bYwc`+kzcuW#IMQBVCXWJCawip*U+oFiYkmoGlIg;HLyVrfn zstC?p!zS~opz_zUnCWCgCB+vs2a4!+x+eN}G*sPHQTdX;`dp*2t@yi+sV5;O`T*L$ zp$vOL3C%(^SQF^cOKpyEJz}`VX+@gV13H1d_-2DUOXIdv$p)r{#uvqRrn@h;m28fV zGD_x!Jm^Z2cW64SX@^c&0aSc?}j+|!!6@&Q)j)wIbToh^#A4`QQl z>_;c)&b07mujzvGfDkO^X0?}@hyG9x0c1}l*hYFDLCoMfMI{1^-T;w-Vfjt(2QpZR zpE-LZZKduNrncUA2Dv6ukp_*)3x23-byVvXY~tQXmFYC-KGk49m9S}{X=`H$hQ{}f zx8LQ{M0amkc34ldL8}u{L3-A2648Bs=hsp-uUbNj6&}jqQHn=z7N??}< z;daAafOc04_c&YtxHB=|+zpq6k?eZ7hvCk^xa8Oa{J<6Atj`a=BJ2}il))&9UUS+j z!lGQR!M;(?qe$G+Mbsq3IDUl2V9POHR)Bf=sq3-l^kT_7o^zmwg)jI5*#@6S6jjbO z-R)m-pZgV7cwEt4NE@}usBPvJ(JWw69P>Er{fmk?dx!QKD{#kOR1o~GATpM_VJkN> zmK$A&O}=q4f`(>Hy`2lfOL}L1xp6Q$mwFsksrF9+E}TWFSc9Vhpq)h2%S=U|cpG6s zFj5eDdILo@wffW4D5gc0F@X=Z+kR*Yws+J3As3XopCZCpm&6OMV=4qU2qgtKiwp|> z;35&s1U^o|JBSJ{Yeus2YQc%|f=@7l&x{G)E;1;1r54NtK2E_4v|ystKM{w<>&oLy z@hnrJ@vA~fjdzF)3LeU|$TBAIaSA?J$OWZtr-*RYW$}W`nF_%Rg_44Ii3|$<>tqqk z1U^o|&l43~MwB{V3+@^(IMoO~B_?=}$e`e*S}+s%I0aW~!F!Ob-bWl7Z=4%viuFu| z#@mFF8Y_`O!RbtkEMo#6r{JT6Tu>@R5#g-zc)>H73c>S)l7jb&3<~~JkqBl2AE)4r zLx7aT_l^lZl4+4; zOmGYScA{uZlnQ9U)$xMI8Nrvt1bbqFpCor=857)sAJl@0QYUG_$Hxo)6cjYYcS1>x z(_?~XX~9fz3m&fp6Q#CLL^x|J&g>kfxQ(e0{E$#mFb7&~<1S2#EMtOO@Mjam6hx^j zwO}4kIs~6*1Q*5xXU7EpmfVqLOmGXnQwt_a_0od-#0&mAD5&x0LP?EtVuGh>!Ax)q z&e4L2QX42Dob^&^oW?7d3c+^?B?K=iryY8z)pm1}wR z@$yC*c^Agy)o6LY)ADNE^6u60YE*A6Z$!MjkAS9r`-P19E!6UgwY-IHc@wm}g=#xF z!&!T0$CdXkrb6DYg^Y%*mjZI6>CUvsGA8hG4hUb3XQ>6Hs5X?-NRDyh>zH@MT&s6Zkj<=WD@4sm&A-&ibk( z&J;H>6@q^zloY&LWKeJd(;~~5z{e^0;|s+UM5!_@_@Q{g!;RpvF~Ms@1_iGrcVrn8 z_&5dMq6M!(vg)P3)3!%+#wV3mJFjd}@?8d>U zdKFa6>QRI^C!z`)B>Ftmd>rS(u_1A{8UPVI6#b{1XTGNjw8)#{sS=TjgH)b)oGJvH zsgW85sj5|S#pmBZi4HA)PTp|V zw>XD%lw~GTjh2gqKr~XT$3e?WnLt}EUPTp`AkCqoPs_XY*mxC}gNlYMM`%>6mMB$R z5uf=UN_42m4>mzn7EiSiR7S-&5v4k6-&pAPBq7mnE%kc`X%79K7uqcAq*Ix^} zv2VP7UQkiLbWutgVunPiUu}HOYbeoSzh?4=vkK#>u0^WR?@l3D+^ja_L%(YXLBG)X zll+Lu7V9k_ypiOQNZ>O8iAS2AvyG@=@@YUxS&-8mILeG!BBIi?Kz5!A5K}e##X*$J z<^NOoJ)-vyC% zQoLy&7i>gDCB%@mO*IQ4Iz!7Ciqai-H{%Uk7di}!H|B+*g(-MTJBu|#`AvBHa(`#+ z=Di8X`AzDtkADh-k4p`NHp^j9A8he6oAWb2Y3c3_$!TM2^8}7*m=0Pe1P`d&A#B8! z)P_~brj6k((c|SD=k`Dm?BAK=DI#Cj0!}Pcf|TJ|NMt77P!ZN=uWev+^LN7+0^Z=C zRCjPoz#A**5K+rVGrwm=jaSs`pcXa8kj<%vN2_r^$zy7G+-iul zkgbLXYIKUO#W|AtT=+C1G#N`lml_FiYD}`#*d)mgYou#6PKZ+jO*Y;dA}yvyI@Cyt z_N5w?PBm_>2U|N$7UVh&@;n&CAVb`m;Fz2BvWny}gA8_SBGO`-42C8t(L4CM;633p z2Dy28N1A++`kROL~gL4c<%V$spjRHkcX z-XeL-EYl$|P8pFFQ)W7pu@ayR502HDamvUF+TEA4;*@Cs1K)$+PwtNe--r(nIu^@4HjnA2q>b>3YAww7W<||Zymwevd(E&JpSAQW@crj-2ZR*?epv6`u zU|+LI5Lxd{jaz}-DAJKsQG!oQSut#^|_}{B%H*W|Z3FV};?oc(Fq?wtlW+ufV zW{bK+5LrFqGZ`S*h{oznh8YQ}n3+^F6SVZOUY3k!+Cwl4XO+i1qQB8WT>_&~k7`~}`Qx%eYG{$QX%iHR3j|@%RpTszCa1ftDVt!5q zU0Tw$Lb4p%crNlgj@q1Vvj|@dlAa}5Bb(_>Bk(S z@ri;;M?q0p%W20V@aE!Wbi=-cK(B((bt&riz+xacOQ&{9Z3>Z%7}~tCIj|(R;kvYh zCB;nhHbnNd%u=t5LW|c>;&&raGtY}kThwMjWNpBU1jhpOCc#EDR@cm3MuK`C?9p4$ zveC}GSPvnGS!%T8oZ86mSD1U!qG@Wj=GehJS1`}XB6W)@5Jc9h_&iS(Y(!&qo~IiL zYBKXYMe=OxWowbhUUn7I`B_fvOPo!xM`}|SBo~Hij?2ZTS`A-!T6C0c4mA#9ncC6` z-;6}07lOmuCJSS0dDAsm)f5H;^-V7<>5NyWDflu^H*vgynS})&*JW5IN_PzFRa!Gd zP6(aj4c*IBH5aO(qOn<_=B#ol9hZyOBPV>{f^)LoEk$Y+(c#4#XrnoJtESEt`Yo!z zAhL4fd(2mSVFzh~)i&y6B&f5AL!(js7+JcNjmaE4$QYznARXgQv;{4>0AKY*^+KE7 zYYl~dj0wGEHe=KKFdHIJdH9l)hyungAR?T+U*5s?_?B-l!+rSTdE*ckivyB$uTP*< zwA}QVR4oc+#99!dAQmk7HF z4TXr@P`=$c7N@A&K!DDXp;OU0ehS43Lcsh)FsV&Tk&xT47#+mNbm<^-)#IYr=D|kr zU(Z2Z+%F1lQFjV1>(7`{9ev~~!A3Mz*TwucA?iLzh`yJ^%<-j>-A_)4Q!g>KiEUNX zdmFr%#F~EDp?b$^$$Cq*O`S{iI*9@}{{()Enbg z?nK6_ib#}#6lQ28&_Hcm=y`p_=Kae_&0`b(@3wv2r)8NCeUZwzIp zSZ(ZWnXAswn(9sLHdP2^)lpKQEvlQ~vhpXz)yCgI!r}^67gsSUtWS&5Slp?Y#p4RH z5~46(p2^}S#)_+4s?HIr)W%k{L0#lzjBbr0ohLfm)WccOuTC`BqOKA|)~a~@&KGP% zW3_%>BSF=HJ^BQe8%@m|a2BVy6!;wo(Wa*2Wc6QAb` zf{kdb&U2>_;$Wq980#N-7KCQT)-4wU%MtZUq<1i)4nZ<@z!*{4rr%=|ohWQXEaD=b}>Lb{NV7Yt@W?SN2L2Tw19k9f91W=09FasfV zGD;!U)ch?L4hv3Je?dOjZqOk3@QddOU#cTSwJj}Ys3(AZ5`zJ|5HMJ-iskl`37u-X zCd6t~WkRs1iuXR4?r`Me?Tx%SAgkYC62Qd6vD$HLq9>mo5QSrmXfyVM{N}f1o6HJL zdccjSYVby{1}F2|bu2?3Rp|jQqKb&V$e^E$q3u(yOrnPx^j$VuuNsdb?l^;662r*? z?(0n8zR~4Yvxy5Q_mS7oJvfSYa{wMghNt)63H|mL@J)hE0X-zktkX31w{>7oAWkX(IHhi#Sp$`2oI{x98o8= z=~sp@kyE2lX^!d+tYZYq%z$b4!J}#SG7M+!!HXh?X`d5pL}RsS|0sm|r1Rf{VA>01 zCTKIsW!fYISfZquareZVWP(<-@eN_VA~ubrLOQ3BqdJ~OR!MTsag^O@NiQs@IRls? z?rp&_xk+eK=T#{JewndbU4|%U2}GyqRLVJMwUGv2ZRLh0ViSIRKo<*`xNud`y+iL})XMk{|qJLc+%wnA2s# zdWd6O-tx`a2$naEfbR`%&OxB}7h`3Aft+Gfqjbmc;|$boX{=iPyD9TQarki$G3QF@ zcVWvRW9V7;N^S`){H4rA>I1w|#8RP|gGCR-)lMd$jl3*~EWQ_Xw2}J+i?7Bc+)b`u z2_fEb>>P+;W8j3)aJ33atuJ9@z=*TZaEwOzarBVd$brFZY|uVAaI3q(i3x!i$Ao|% zc0I`#p!gz3-e~stJs=rl)#Gf7FK~(o{ux`9hHo%t7Gvn;b}Kv_nG zuoGbmG-a@>H%`+02sKtd#f}GYG6U5 z7HN?^;zdqGD&}rlqd%gJ&5tJdvsIC%eK$8Q`%~L!KS5Tk<*!MI@I+*?{8?H8TZ8V) z!(GrGXo!|0?YLuaNu4n=Iv4a!kjIgD9cIoB7WC7Q%mqE(YN{_m3bR+)ahQwIe^Db$ zx(h1QPZ>3D+BT-cs!N#wt6n3BtmEQ~HD0h0jn!7Y*ho-I!5)1Q^8l;QO1*KTRPfA{ z=w?I;gXRYodSDCQ%Yl>M*2A1(j+^z1dbe7sjc21>VGue0{MgsDD(89p(BT-SW5Kl_ zgU56h9OJ@;V$dz>6=WPgcsz&{Gk8n`k$M=gJ$URq0||FCK@T3c8=QI;i0CHd6a6O& zp_lH{IseU4m7v*ZmeL%YRth_RbenYDG&NC6XlBEhPwD4tw8|1h)}JqM>ZiI07H?Z6 z+)b_{g%HE?`P3mGW!1*cY{zKdB_k(<0x2yyXc<=O`p4Ob z&|5iOsLJhnfZ0K*9L1+nAb%w{rgxMd_OWa@MZ;UqZL`!WWSP4mwol*>e+q;DQolno zDlG*9G3jvzM8MhW!f@Vcs5F_qM%OPojkOj=4Wrg>z@g7GIf!RAs})eR1;3loRrZi6 z(j8LfE$T!_kFTh6GV+8y$2G-0(I4`cZskbmnBw$way&BOp66cf74T_z^cNib zu}GG~zs<B8g0#)`G`@cnT-J;6 z8CME6qOm&T1#Lpq&mbW>MKX2_(TNTP;!nJ?G_Ti`{4y%gSF+fmju%{3O}qjvAfc@V zs}=Z?NoMVJG8K3&S@+=Be&~9LvMnI{3ON8(IC6VT^V*%~%~PSk8p&ddS}nM&Q{ol4 zQm_$?)d~dKgs6KVAv)Quz~4b(E07dB^VOl+z2FmHkzRm&r5NnsB&AF_Y*$E9&Pq~-NWLu){ z5V88O@0q?(Y#9^KD3=H#YgN2rMS_iJthUVMMuJ)f_UK5rR(pZQ_|1NB@N?H7h=NUT zV-O)-LhQiOeYRR6bUX)=eiftJ<2qLyL7jq4JU1d?=fHK_nw|lWVAfi@)TKhPMco0V zF=(gb^xDz)DwwK^mxCy*ny=<*%I|Qz>!7@#jk2pm@hzf=j;L&e%O%^EE+%`)-QQFBN;mG zX|TfZFnl^AvLKSb^Tqj_(gDvG3&MG)U}%yP%G~-zr(i~FT0|X!!rri%wPQ^PewEtz z2P9{{gzN!2R%qtc7bBixy|wa}i=k&g5DK%6hld@H z_QBt3-G}^Ix14(~E35YP!jP`v&}OM&ERxhOK>#l4LJ5D$AAqm#@N4GpR0GqY@C2Hf z%cYx;r&%uXr+9h=^BfZ~8~#NqV~e^JTy53KMPUX~%%XD-h}1chYj*3!eUNav&WNY9 zeGN_(5^)1%>d8}`i-h*)t+LX%O6HN+tltZiErY1}VzKg;mcCNA`dsjHyl~UgJNMc^ zsJ@bmoW7IkH4v~sS4x4^BlYgI2;mv8@Al_yFL_P{R zbH%uB{Zf;@OUL&jkUi9VLXj~zA`-Pys8%@nF?l20qZorVdd}|wZ5%*? z*xT7jREIe`@5$(m*Q*5$`BoAJ|1@>7j2-&*??@?L{&p7iQ^a$FTk(V0C9^Z%@`e^~ zM{7P`2qG#Iro(WH)Ezv+_8=LJJhy)F5mul(N2g6l!9i=^f>vxQaI$?S7+RaXs|ynH zW&HYQVem6m&BQIaBi;_IA)T1J?HYu3dgFeiZ?Q>9!B523dBZvQm2rLwiqKnKF2_h( z?FA>W{JOQD1to&{o474r3A0Ekno$Z(gEw?qZF~T*1FEN4{v&w1iTcG897q;#XO|oc zahzA`7x$8q;afYTpkzZQgnTIlVShi|9TG^{h)$?45n|yBAXkctc?|{qun<2Xy&7q) zTSm;>l-e{Ov{DYacw|D#Hd%z=+MNmO25b)|xURvF<`qg_Fa|QE$#j_+9SvbptEN{b zUmC+Es{YK~bPZa-j6SR*D!0n;%57D414~tBpeeVG!NwN9V34-;wY+@oktji*AqX~J z5!bdphasen;v|idcC1^me?n+X3XU^ow{8!PNeP^UubEblrgHD7-}gqy-_Y8hGPPwK z8V*#r#|jDhJc(fAJY?K591Xr&YFjHn#8OnO+e5 zH@c%$UATkWJRFd84p5{I)+#>r&cY^vTzUNAI=>!%RK z#4<@K<{!@b0w=Ey%8hN5O(bBByH&c$Z8P?2j+y0An?mc9EmZz2avT8av($mjpQWC; zeNO5i+}aa@rl~8M;OFAwetdv8DJ7Ut&@e6~DLR8QYW$r+!?0k*!Dmjl{`KH!*mvE6 zQ^|(QHFm2{C0h(y;Q&S&d?ku}Lfi?WN6x>yV z>&C{Vq(uLMWO9^g5yw&lZej?ajkl@~kQn`gp*T-doJ@)%$a0FEi7rx#99F221TGmACt*;W z7Z0)vOm`f-Q2fQmh?!1c33@Q$P9(_ak6ZHe8O+mAndc9!1)CVdCRMC6T{u%4pE2-d znsEb9)t=LboeZ^x0;Rwtcu$6&C`5f z!gRA-eJUV+55|0WEfsiA65jFU@z+EQ)07;cnoMpj$c;rlGRlj^!- zQC`N>WLmpF6-J#u0fZD{TuNSWu&K6WT&j_>EhkCL{f#N^4G8maO&32`4B|D;U)38l zKtgd!w2#Rz(Qd2xz(l(sRgBYmq!@M$^pCgC(M0HDKc6Uw3w%ICCGim@%=*0MY$j*i zLiMk`$hoaB6j;u>yj%-X-yn4KYmu>3%h=vd#_dK1_)j$aPa%x{9pj*IjuX!DHStOp z3!8kJu?_^V>KH1FuX&-clqht|4rcZOzRu=_VDj^d0m6kl;U-}H6WG9eaM-CgJc8Zk zJ2)B??$=2a8ow|;!%s247%N>M8KyRlK--b36tDhwN?TP}Ljn)|G3J`9b+h|Rc0tUBY+Es*Y6psHan9 zQRyC|a_E+Q9jWvivKxbC7?lP<2*%sBJadk|i|xD!nxd7c???$>oDzQk<#IHkxxLlN zh&H~3d#J!w5W2M=e_-Fvs%IE((-PMT7*P+1I=U&ou1Qes+`G1GiXZf7D@BE2p9yx1 zUmOJTOwwM2-1YA>og@`HV!5B!k2f&M)HX=+%wL0|uR$;5s$?mWFuJcs(rS}bk0gA( zosu_TPi`=&U-TS&q0iEBCT&-`0_qlPGj~7*&MkKt6%t|Fl)~^;n9Rpua2=PjZOjo? zWK43uTHhS@pJZwEZ)h1Pe(#Qo|6%vG;$I0;s9C6QwHf>x zzlt(hRp_p{C?=Zc`|T_na)?fi6WxNJI*W26V-h?aNhokg_@l&O>9*I%XM00&cbE0i z(-|js?`e~d^F9fi>Ir_ti~iG{BSIuMp=&Zx$+HpIss-uppy$NIZ6Ze^0;#T>%%jf_vxkP>8 zBtiD(1Ry&BT&8c`1J!bakqM#7erRQj6Y`tzeZ-=EDSj_5G;YQ!egzIMuq1d}tAj-( zWS~=GyZAiHfPvUF)&3+vZ#Qy8NbZQ;fsHf>x|?J@VTajFJFjGFccy@|kOSP9Y!oBM zHYOtgIyWZg0!As+HMC_otH}c+w_U(AUbK^q$*G8-8wsh~BfA9eyd#9>rYKYtf*YcusXL3ARrQ8gxy z&tM+%-=pEiOryhnfKfRULW}yPsW(ypgl=lT0RNa4(S!VA(6DwtM|Ud-%>dW^Na=9d zzP^p?T+*OFWl46p9)gVJ!suSJ*9#Yxci*X3LBJWV62z3y_*NjhAQWDMtm9W`g>5|d zI(WJWPii9<8Q^P1z{6I&x{y0!j|EpjLlUMXQRhtx35B-1sP@8ALKXei*pSvhB@LrJ zuRsw%9xjD&*F1lRiZI;k2lzz%TR z1{ld)-}3iGL3X%QoM2S!9=%LUbS+@dZj-pgAyFZjtA?*3t{`;VE(GnS)z74r+rMY@ zYeDLCNa5<0jphMK!&31MMFH;R>!T2Wafnm=aKn8jxN$BhM%9&j1u!Vr9tbd};n-8l z^0^l5Z0nj%OF&+?k+fZ2`E7ZfhO!Q_^BX_$k3?(P+g{~oSO;haDbbg)sKa{mIvgZB)|=1W&pl?x z%glzjTwg^-v0O)*T!(;nUq>2`)4XErSJVpvMWP3&VCa_mjyR5q%dOOz+sij@4jfKRA7c>P9~9WpvxD{h1gQ?Ls_iAfqS9_6jt`h8gVaG1~r zDg_o}E?0$Y`q%~8O@D!?fj6}1JnyKl0Xd}9K#CS{susXSp-aHt;^^t)oy z`QmepZUSH2`blnM=liwfU!KJxB1f#F8WNMZgyPkprZruPD3(y()guPtptA>>OXu6y@UNb6P#8S#(6bI5dv$&`0e zr$X0s$2pto18K5uni+l3)?3~?sHXs;Da%W^XAy^zY}xA(MZW5EFt#mBc|~me!t^qB zOIp@mnA$JS9PiJts15gN86^3r$;>Zw{){sbgpWCY1;!w>s;ikAN!|z|K4y`-sF5x-pgE5)xAze@ZX@oUBRi$7odh2mc;KEL~H?Y~6)dhxFpzft^U;x89}h4?GQ zzft^E;{R0qTgAU!{MF*$CH_6)-zWYW@gETXLGgbf{#x;WEk3{gZ0-MB@z;s}d+{F= zf4%q{#NR0XCh?yZzghg}#NR6ZHu1NM|DyOWi~oxFJH&rY{GH;zF8(g@|0@35;=d#Q z9`WB3|9$a46kmz|k@z2r|Ec(U#s5tFFU0>+{C(o@7yp3x--&ObrMC9(Bz}_koyAWP zzpMD&#qTM8n)pYGf3*0=ir-uO6U0AB{FBA^h<~d1{lq_A{B-fp6n~)jgTx;!KKoB= z|6$?}7e8D4k>Z~xKEEPv?Vlt5Xz}yJA1l5WKK{GRqi0}Ab?cq{h@{UWj4#*mUopN& z#~)(6M#t}GyiCXMWqi7h-^qBPj^D<3j*j2V_%Iz0GoG&FLB>zgarx3PO~;oqJxRwG zGrn)N=yna`AM1F4@jW_zHRC&Vd>-T5b-aS{O*-yle4UP$F#e#9&t!bHj$g|7N*$lZ zc)gBKX56pi6BsYoaej>$ouT9Tj2G#6F5`JRE??1R>-Y$!57hB2#yvWo$@tMaem3JN zIzE8$19wQ-`!l{*$NMt=zK-`{e3y39O;jXM7A>4-1X@vj-L)bW2aK1;{>U2Jr!j(@_qSI47_pQqy=Fg{qv-(|d?j`RE3 zXm1^Vlkx64{ujnA9e3Ep& zbR7>eev*ziF`lO5OBqkn@x_eqyG^%$#y{5a0ONaf{A$K`>i9gyx9fNXG;1GpQ_`ZFz(gyDC6fL z-g%HV0e`{jhhEfRlIr&tyv zrvbOCGrR);YDmea63Y|}^41r`+yP(;Q~7)ZfIMkk;Pt?w={+RK^Uq|<;<9EmF@3-& zZ!?MFNezyct&b5Vd}V+XkR==ikC=W0PK8I&^5h%L3}U9jYge94R^l*{o~s#jVaI~~w*!)h1lZWrAskLDCAaWF(+!@dBVsAn_xr_q-ik9$8ghI9yRZP)O z5%UCq3>)*I!R#dFBzUn*&j!H4jY60(1Ku>7=V^m^nHZk3k!(MKzr&*qI!U_#&>Mg} zQf~B;YPs;<|9OiSxpRgh@aY+o=73)@5JQ6 zV=07Z0swqYp`S7UIIY*1>j6-4{xUV;ZUg*^z@zZeZL$vyrZZYj!e<8PN#HvG?aKE- z1IxD)c*pR;aikFLA=HW02q(ItrmT%{6>x$%4MifR6Ui z0Q0$?m}}w1`Y~z-U($Youjcr)-o2s$Rn3zOWJHe-BQ)m}l$kfOiei@&SOV7{l`5E@ zo2p(w3}=e52nCY?d8?5y9|lj1m^!=#WQpGbV7nGfH=vKVdHMk`dtS@B2mn6W)nr#2 z0I(h#IpVOAtS!K>WWOiyX8;r}7!F`v0m$>A0VGp40=yU3il%~*R{skH@T`&oqzG34 zparWDCSPlS5P>`4u|9rH;Bfs6k_VB=qv#2 zk%GAa0E>S&!sK5VU?YL&4Z!~`7i;zV2(ams=QxDPr@~_e3?*qqf${Lziv`1FVFmzs8UQfUn-M18Z-Czscm!Uo zZl3`_MPDc86?m??-EgcH7h8LC{U#41DR5bYs5hIuJe)k4bs=0r9=w=LR1%)nyYI0Q zPhg{gsdOnRj0Tsd_3qc}>#f9z1TN7@Ix-zVK4tt4j;%_bE$|n^3C0UF^X3Pg3H+68 zhk0|bWZp6{u=ugO^Dnw+(nTXZ{p-3~V@oP3ePtehwWp-Avbway@AFJ8udQB?YoM|z z{@RMFx%mrAeKr1y>MH9h-!)+L%nQ`{Jyq3yPib|PzoeqdQx&MJ^vu4-@2hJ^Qs*zJ z^?Mdn_{%+K^gE*++Lmy}pfjuq6?JvU&f}{p^Hk6AlvS4o=J~4po_Qs;SNUo^XUrIU zhBcLEcn@hIdgoq7K|G3 zS^T8O;>S1qYNe`Vp0BQ^q||2ts77LGb(znqE3Jl9e>L;73ahK;T9am92}2a*S)(he zN@}mM#*i#;^hFRg<(hf3t1GR%>cH$upEb1t0{tcPYS134#`~_ZCX_5>Afif3DoX>E zXsBA;6j5wG!=u&&2v2Lh?teV>DdDVU& z6|Y0()Yb-S{2o@k2X?M2nd|eMXE%ILC2OjKQK7WFq}HR`fLKGCk!{ZsX)3y|*?KuJ zlz41QnnnP)+4gD=3YzNF8Xe4ph{_PG@^A z*VHpfW#R+T>#Hk$B~=|JwqgJGbLdE^SpKod%$Oo5FAIvI%&87=l+sP$zg6HLu1@7O zo-0e{m(-QkR-kog6W4j_0yQ<&wHUoRY7_H(^Qvq0=-O6+u_AO-W!6+w?xD&UZy{>W z=5Q#E4r_d-HI~+-RV(KEI5%L7^80EXW_7omfu`dOL{Id0C^U}3p{Qi_Z7oWAwx@c&uXYZ`ar6@1Q~UOfjVX?jr|S_Sy{yDvGGL%*qD)Ka6&xc` zc29hA+oWYr#+WIqJ&y4cB4kQRul3ahD*bgGh{V8&I>a0Y+$8Dh>D98FD5)GUz>H*e z9mj?|GmceMVJfJ?y1{Kuh&#UoY zlRltb`X#=StB{P0>WV$1JcBJJjKPv|c1h_~7KNQXN+ZudA6T8BR~*F zmqP}d*PwAe|HWKLqz~|bVSe_=k%d@%R-VV0ZXlyZj-2RQkX}(&&AEP{Cr;!53lpu? zKY+3`-O@RoJ*uDzeY~oqa%_dKvTO|2fhd)zJ7`dbZ=pYfbKaoRQj4K=2{{i^{v}$8 zj!2wk!J?Wgb#98WtB`|v!so$Z%VoVfJ$W*MgarKcwK^pLW;nSdA#rl{8p|4t9m-Y^ z@F?J&06aW|E04j}9jpDV*i+}=fM))wSmIxYv!8*MRfKR3PA1FhacDi#vdWiQ*0S?) zsB=AN@^RAB2z{_g+}ec0CggtW4VLx!rJxPsaDIkmZ9@3POq>TJ9F9D*S729$JiB8r z{jimUnAH{K=>(mQconFhCRi!>|H299C0fa!C0YqM$xhs!WOW*pY$dKrwvui|!E;ir z#0OHXB>bz;&fXKOgo|+YF&w*%oOG-6#b;U89&C_#qw@(DSQh@vPvVwwR+rF-JTFEb7Xm#2;-s+q_!AiP&y47j>bStsvrB>2`*;Yd5QY(2_DU4_( zOzzb!DFHU5spYYENeS0pWF;(2OGxY9C1n+`{eWfNB>jY+V7In%&n8c9&$MNo#`Nes zx`9O(x;%tO8#)KL-LJDHziVDC0vD}d)AOyHr<5{NjE|ws>!+)uG1o&?@l+} z_=e6aMWRMf?pC;882WSE^adu~$8hU^0Nv3j|29K+`61+;2fF=+jypzq?D80pHsq6V zZBe0ExXa!5au;pendPN!n~a>tNsK3D=m**Ww!CrLKBVPWOQRQS^cbOrXVV#&bZ>+1 z3PX3?7mhV8&tub^yx4ite_AnK6?-;rgH=QX5%e@G6y_e{6BqA=4 zU5*J2T~>Au$7*^QkcBAE$Jc54G7cJeQZ9L4C)j*N@qDzy`;a~B22FM-eY&Il-DT(= z6zTA6xfjOErT(;U&*fTfC({5@?r`Zd*3teUfBQ3Bt=4zL&dZJx;bh`IG z&Bq%=_@uny;w#j4VLp7H_c}g0<+H-B*Bd_63AX(^(2uV`(toANy5T&GPs+LKd--VJ z1HaW|{PbA(Zi#*`-^<|p>@iLDj;-feEr;Y|eU{-UY4s*e_L9!7tzDV^MZ2v8-QcG+ z-4kxQ4(z-M^cxI4-xSJY+p7cmm8ko-j2=@BdCIttURzu&*(8v0Nfmyyh z&<%e^i{YuAJhmPNWcm2z?CFN?Jd>Vslq-M7cykZr4l(ovhCY_RqaX17(NsgX?jUrw zecv{8WyW49e{j{GnXgEH5(nyMTjiia@m)5C*J{BM#z24&>zZf4})&Ip~JFGKejy69_(Z*t+}`r>%9~c za^2R^v-jsZ)$?FSSd6a=b^1LfTx-I|OxSF~mrc0KgzuYhuL%#BFvSe$N1M=N!ht5t zHesF#i%dAfgykmmo3P%5D^0lCgb$iQ_j@;f)eMJAkX!dWIP zH(`wl7n-o%gv(91%7m*;xW~S$J9H; zglQ)1Z9#)Jz^SZ~7RCR}C0)h1kH!nGz`XTl98Y&PL`6YenKE)yz*sOrvp zOt>&fzO?LIj*#iI47{%2(J9%BpH0}AkexlF>-vPe%d+RpZcKVOb@qb^*B{;W{UcT! zd3)y-sVlqxw);D&FC|PpzUQ?Y5|(x9ecpxZ65j9h`LSn@U7xU`*KZTL4muA#OTSYt zlbH6dN8p540G@-_qCNUnO(O+#u?E2_G+)BuF!P^n z_-`=$Hf;0T=iG#;zY``uzc=8+9}=+qHvAG`XMKL)f+?>b+Z;sJo{7#ts&4$0y@Z0dsfEy)e?b-62^-F!6 zFy-wt@_uII*|5z&$H*j1ekV-+D~{6y+YG-A+x)X#{7#ts&4&LAyF3QA`S~uK4`Jr- zgvrnEO8A_ar0c_m`TN3-?C~((vGB3wIbq7H>8tUJj654AeLpy-{?x|_lm9it|4YMf z!#4keT6`>jCro~RAH(ObhTn!2;6{xS-joG|4rH0Plw<6R%ys|}OBADpxQ zklzWD-#$+rX!vb-Cg6_rc^`W6p?u17!j#AFefaQ48q~*zNiX`C_u7O-9|uf+eka7I z+3?%2&2PWow)vef`T2bjpRRZ(#{6yA=C|K>+x$+L{QNG74=+n2zYW{`-I316=6Ay6 z=l4u}));;pw)qFS_?aKaPeIbrgrUn=a@5cC7;Z^NXg{q6VR zgvsxO$ z0h`|mlfTOF|IF~)u+4w1OMfR!er5QdH2gMf^KWqRJ7My#xm*);Pto?bVVmFnZh-Ja zcutu7zc3Rf?~!Bu*)Zu@f4#N%nEjnF`T5-(pGw1T!#4kU8Xe z=;C+6+x%sW;9)?1Crtk7#e%jHF|N>l zHcWcj&;G7}F!`M@`CqzH^Iv56ZP@0w-!LzY`|^sH-%= zYlh#3ZT|HxekV-+FARU*uDbj-Z1daSDG;6r&k2)%iC<@Mwc)p6oBy}2{GBlQ2L?33 zvxeV>ZGI%nLzwwHVe<1kPd;xMejB#=2WfQ7eomPDWrqLXhTn#5erJ6#eKxW|q&d4O~`F z$g(yYnBUOy*5yFSVdY}dz63|v-EZ7l0X z1Kag+zk%)gc+9|deMAgw*T-KCY}dyp2DakAEj{+kR=Mf$ja^egoV4oxW%{EWf?p zXSoU6`-yr3+xxxW7}(ywyH%edhY`R+w12H?3;O!_$t%iiU>oVy}rE1!1j9g zQv=)UcmDGc(%busECbv7moWm@$JQVGhbF8)d;L;uV0%9Qt%2?J#ft{E*9-h#G~~C( z|4!I961L})lMHOH?}iiZUT@jom*pDR{?6<&p>JE?&H{|$U{|W28V!GE!%w*2w_WhR zU2sn<#2_!me}M}wcfr4M!EdYos{G<#1zy&9t7|(yY z3--ET{`)VdzWmQvPI$cwZgIi=PKu|Wp^Gvrn%siF8CQ2{4W1;6QnzjVPz;oKv^(LXX>@FW*p<$}X5_$e3sXBYgj3r;>QK7am;T&F%GT<{bZ zJkJH+;DYaW!B4s1*In?xTyXb(@%o(Mg2%Yv5*NJK1>fg_pK!taZ_m#1_v#-HpRHk# z=x3}8E_T5+E_k89^)dc>7kq=J?_|rr&Bgya7k;w~zrzK;>w-UZ@qgvQ_c&e38_WL` z7d*rTXS?80E_kd9p6G%v*6??Bc`IFbzYAXEf}31$*afE~;nIu*tQrw|5T+qK6=9AE zd7CzF$Li@dVKzeSk9!VAh<7bL&q7TNggYCK`=AUszH`Zh8v-{JZWvq^+;F&a;IiRH zz>S1E7mmNrIv;xGUiJFIi{7mB7u0D~03!!Us18ZZ2Fo zTm{^fa96=q!p(!Lf~$tBfx8;67OoD?4;O&rtv3tc7Q$TvcP-pc;BJQd1{Hh&PAVEO zeo$%QhkzDdby-Pp$#AE`ErMGDR}Z%ot^uwIZW-JSaM!~%!Yzke0k;w^40j{kO>nE= z@Oww=7PwpCZiBlW?o7D8aQuh0*TJ0umkt+%3&9<(=l}22v&Z#I>O9|kUnOobsntK9 z##I`;#H21`9`4DguCDW)U5DFeG;UsXSpYZ5#8C06{LOLul(Xe$$pPGGlVN_NEI&@> zkCfwo(fxm?$3;F|q*3R~z%RuI;pU#XKK;AtwjWSeTgAnf4K1ti6^$>oT)(UaW@6^x zJp9I6U#pTi^pe^N`>vLPviyt2PaHBod$?CFqbZm;WpMFu{Zs4weB!2L7VAWPbqNw( zW@z`r_A*~hUB>+EjEbt#$^hO=%@{qi zu2C&~PNk|FsQO({NvfJ0z2GcWR$l$q;^ z^5?T^EnebEre69UCX}9Fp?q`Ez}>rfv^PJD9XFB4-1Wn(auFA!N}F361Qal1Dfy%)b9A zfA&Fi9&%0x)by z`bq;uOP&9H-RdCsMX+|Yj7(!?fieddRN=ZPx%w*q;2r#jW@=0!qKD!Z2-6#f3?6Il zW*TE|o+zlAQ!TwSOIsSlMNGrY5ukG46!o7;8p>|X%T{y&^%(Z!v>9?vjKBTORR5V) zS*{W2Kaw&e(z_)8JmMK9h)xnJ;fdtv$5`YMf2l({m^(T4xd<3g??N>BHO&2`_2416}ie%z$^=< z42`MbF!qovSxOZ8s^h?F@fZ6`aMxe9|%a5<}Z7F|@t-q3s!m4d-w*^4A@9^^n25 zThd%ih>;OXHVlkHJjGv_U0hsIEyHTrHI-$>b$(pmI2+eu;Zn`wa$hC(F_0uE-p*HC zSzUcqpoYSK%n;HN&AJs!Q}mSrn>*6$nAHg z@mok~h3$!4+vS5${lKlIbK7_5P1>P%hzHT)e`%}z<2J+nVEX;H-)!`XAT)ti`zndIw`+s;*{d-3UjsRIR*MgP^PwRTxEIe z7QX7o_K?geKEHjm)^^!wenl*c;r3CL&61gk!x1~t zG#N^6PdEg!$5i4{@QJvy82jSlw$t+B;W)|Qb^K>F2EJ-ejx`^1AGTT|lh zU!2kS@XrTIp%eQIWL9#2FZ(Fy+gB#nj^BwI0Qb&xz3!K_R zh_#J03 z7n>xzgAS#KRtM1t$eFaD>d>NwvJ2%_qD}eAim)5T@nJz#ob>#PBDd(F*;8 zj>X;iE>_z-M)9HGakgwU0eiP5yK*@h)8mJbUg_rdmel=FejbL$^**;O6g>Y*Xy6z# z4yH`@*y`F+9~llpk7GDsGC4pP=2dk}$BGi}N9AYfkPWgY(Jd$mX{zKch2xn!=3)*6i93>cazNdYRh!rs_ zpLf)|bZ?Vu>)pmMLMr@+F~w$&_B9jVD%;PtoNtPzWNE|cl~iUPE}Ad%u|3tHC1CKe z>kaDTeYH8HmUeBwc0xAUm;kDI&Ze7roGdxGcFDqP;vXw+xV{pfYo$7Sj(5Fo%XBp# zQR4^k*)yp94vi~7!)VOvv;;b+eo5`jK(`7R7-B|hoA){pJX{~#vcz7J$czV=+R!%rOvq9^A8=O>#qZ3o!#e5?{#oy>Phb)teMj)4k38RX#H4T;<%nuQj%g%zY-`u96_On3x( z3S@{A0`fRagrCKIK^c>7GmZ0@_C)W&`0+Bk?-T30j#bNZ60|ts2mYKRVha(OZ*2^1 z95-yWaZ?l`s@=1uS_yoEepI_-ElGQs?4YAWwI3jP2D4W9_(C*C@}?uQX%qrcSdt^- z2tvRaCNy^-ev>ynK%J=do!Po}EJ9CE9AmT;*yhUFOd%9P@;+@7HB=rgtqebFuezaU-%<4P;HiPv-4gi13*1n_frL0R)h zu0>N?q|WNjHgsl&LWBJ{MVTl_l#XmfY&o!$%-5ZvB{xuxt)UGgT!n;U%L+?b&Isk? zDRgid28}oedo>{Q+qZrls20gb%uSo?O;<>jwye24iw=>l>$*Z3pGZG=j3~>8`F(TQ jm(aM$n~IdxPC?u>t7HOJEc(qk*Ys84@V`og) z1U^QL7&hp{VQJbt6(;l(^ab#^Xlaf$oLS^pb2K6!BSxG)c67}dBPN_PZW0+IMhrZm z>X<`a5u<1LEi9E~6%JLXqf_+#Md@4EA=e5iURL`ijv6CH_Luj0pFPiOeXc>!C#clM+)0{Zn`(MpN8yH#N8igt=#2Yp>z2rsL?Y15}> z)%W0|O8nej%5M)olaZWhG8m>lbagZwx|0ZjF{k6zs=%am$pwDZk(J*4f#7UV69uFF{zJdK!f(Gd0-z(7fj;f4|Dlz&djXrY><^1s= z=W><4f*}5Ku2Zz4$%^pVV=p&^BSgCI+b-pw{6?zRMwA_k838&$M88$ z<=BNz<-|o!Wz7<&a#q9OWPJkA;ACBYd?b?fz2)PYp8TkvaDM*=$)R( zW!0cHY)86G%M*1U)f8$^>GB=725uUh+$`h^;k0l`LOG|`T2pA_y{cjKUlB?$I3)vZ zbtkIoN4tS+zKj+C{?Ust^eU|MBa}1iOYpB^za_Tc^T}>oWKX$_@Ri}FVTV1=Vf1*Bu zBvw<2mniTMz2HcA@6AN=LotknrY#QFk z@=HxgD=!zUUNDh_S7xmdnWoZ#$xXkmu~ie7wt~i#{6HyyU~(P$K^gi1>}R?`$V2xn-8~Jh ze409{s8>T%u=bTeBKc~f{&1LlRFSi+W$o7S7l!KA)-*QlQoD7+^!2q{C)VWFzLL|l zu6FCRnzw6Tv76o;zTDMuNvv1HytUJJPi%X!SHql_);LeDt=-yUTE$rnEtJBex780U zT60MZ0`u0^e3IC<8c&2=Kl`fO_%t=5C>2c94=%|`)Gp6qih=c$w@G=W_=rCPlRvV+ zQWav6#G6EFSJq7esgr{?p>~UUtxnVr3!{W56gf{8hsPy{4Ov4gYJWonYTN0^6Q7V?GeGw)mifXs!oZF@Lr9Tq&!{Pt+ zrkbmqC*9tct|rxoe8pEeAa+(Ar}}@_W~KN2aKW+qbTr-M|JFosqqS5~J6RuomI z23M4zUr#%Cp!4MKiTVU0=HQAV5M2i+zi}H1-GZWj7DVywnq6W4Hs{Ieg1Nud!f7>; zRR4B~+ATq6-ie6jNH;L~!@%TL<@VKslfT04iR4Q{XXHBdGGy)4?T%E{srD5ryHqL+ z8j+`N_4H^W)ytR+zd)79%xiGwtwhe=L|kj`FcEyP#GBy1%moRa_9iIWi5xKSxaBya zcdu>D3$ZFuf83H~oPa5RBv*Q>sn4J_H7y4xH>u(2)T-g05Ng8bjv@@lPt^wIezyf# zR3+a_{wQNZ`WZZizYbuK_Dj-+C7;M-yXmE=t&I zwr!|JNBGGpvVL-6bsPS|U{>1@u1+3S)c65f*4*E=AxX{1>eOz!=8ibADOUU2g*8Jw ztdUurpb{jPi$yGTYX+maD`+%Fj?99~L_oLsf{PZp8N<6a&Yo%Ge}k2h}y|P za|8r5P!HGXW;x&v)uP9qnEN=yCHuuK`Y8}Bo43EjeJY>z3SDJP7&-ji|J z_AvfjY(abnUqumOCmLGhFjYDrCvE@8aa(~p-P%l z!s*tmJsIbrtw}o*y7A*bx2Y;i)Gyu0*0=ouFauY)GDTwna&;Y&!ZhO5MD6E@Vp}DO z9gQe z-sNz&ruH?v>9y)??Q^6m&Y)hK)1%R6y6oDQ?)W==iHbjN-|Fd)C5Yh?OE|G_8uj1K zux`Axd{=+}topB^l(Y~8-^Ovsiy0;A2js9*qz2@0v<+jlMO@%$tBaVWeBNG{NDg1* zHkst0#ipI2ji!!hR!~Typo<#6Ktoks6`fM@H|<6*D~!ss^HoP8SvLcy$A2Z;@t>@)ma##Ls>Tn0W3R`| zv@R?~SCiAG@oqr{>*~b@XJRUD=yW|@EbBB%<)l29eHy%J%eHNoz^12ht;F>{u2JyI zUAWfc>W6kW71tBEYJhe7W81cyaOEJ9U4-jFTwM^C%zU->yZ>KighQ)12U81jF6mU^ z7(Y@2u;e&GW`F|+IZtA>n!uFz2#$eeW^q@Qd>N0ZaxEqj`(>b6Z+jkl}%PAhH@9UjGG z@Gpzv2C#Qp@hhUkqnHf-Wl>CMrxkN&Bf}MB@GpyELOZQ^o#^mbOa}k5C?>SiiZ_T3 zk76?TmqqaguyRmn2hZxCbZLv%lwMT*p6aC zJFU2@UojcmQA}v36*JIg_?V3CC?>SiihKJNld&DegmzkSf4^cfwxgKP&MKZgo_>gk zIL4^)Mx~Q6b{sl>r}a(F&^LKI`X=wRz8M+%W^6~_jGfiDYz{PJR6QB|%MuXgfW6a- z7l;l|2qS}kSril6X~hdghet6P{L7-4&`vA9UUYaAlfl0%iV5ws;zgpvqnHf-Wl_8c z?44G;Saf(4lfl0%iV5ws;w7TPqnHf-Wl=1$wJR_Ilou?RR-27GGo>_hHO>G%yW*bR zE4mZ2LTz8hawgMe{l3CXX|XkX=H?yP!+F`*h0XWtZcy~y^$rs%(AKlAgfmMJN0q?#QMZIKA;+-N0N zRsXlFq(wd}XD$3cW#X)be)|^x-?DG9-@bO=zt=1FC!s@mB_c1^rG zH9IW6!n^1QdDiSHL%?e~S9_2>D>HKK(6z>Xge;W`FA7y>(4j=7u3a(1<5;{gADo&I z##`Evre^B!_T_e*D0?B{PNR~t{WCcEgw#N4sk<4}t6@;D@0$t}DcNn@)-Z%I4a32< zA;~`^y91UxwF}WKB-r6C(G%lM1i|{<1 zIvR7jwa}Hf@Gox(BW|YB0a#?Wk*4BfFML#yV#F$W@zXE!%y@!v7##B9c#xMO2ZgfSK(Xd^d{ zeV&mS^v?8UL}E9!*E=J#88mXo292aa*n4l}PJh+hKeypEm{V5>6OGqvXB2^R1vrCK zGDXI_AbIy==JgmFF1rmdH<{NbQnH;dMU$IsIP0)IqbQq&MYK?j``RNjfWs!XBQsQTzDS}Czm&MRR*P}Lv7Pz94&RHLwHl;ooJbMk(O2? zqnQcuz}*65iz5ogj|+?+tMD?qc8gsTt4>|$&VzPW+<;S;VzM++GrOwx!XkV22=WrO ztF|^R+^C$|>uQ2zVna7zt*Zl1~ zRl{oBP4aBs%gzFyrzRGpBC#>=0hEhMNkcsQppYhLL!K$9Wm%iP9bG)3dZ8sr?hFTip2` zD%$_@kJH7AkQ0s}RVNQEY0`7C`dLr^Z67^t+`T|O%w4en8R=~Yi9y0g+-Yn=ORmPL zzDCtN*=W%&RAo1fHczUVqw+LRZJx6Cn7vpm2BdWN8n1hdqg0`cxg1ogkV{Ks5~_ksRcesw9JAcc(L-_3Ij)3Z)hQQo>gIw`RXYnEWGwm8 zLC!FWdwLWro;lg!+r2R6n@>+4SxP06xbbs2NrIC`nf+wCHZSPZv8`s9ckhnOQ%kD9 z7hKb8$HoEK&8z85{{&{Y(Ei!fR49j&e1$kk`8da^``TZKcilo59b2;MaOxh=k^#3i zHZ{4mp%$@!v$#~EYGarjW@%O%HQiX;pj+IH*-f3d4Q)^rIX4~M{X^>kaH;5LYT5$R&QU3&=%<>jT%Mg*bKoJwKth0bwDbco| z&K5yA-ZeOR_a+F5f~6FP9x_y)O(|A#>C-L?GX)$fcO-#q(}-ks@>8k%nH_aewg?;R z)0heo6AZuUEFAYeTd6m@jeoBaWXn<%Ha>^4HtS*7LRbUy@v#mc3*<1E@x*5W$Vo4F z;uTOBk0=c{kP@|0O$~oy;&5K6GCWmJhv48B_Y>4ndQNG&2>J|y0Yf+tOjkXgGa=61 zx)xJ$W&pz-wtNyL$eRIKaZS?7*f2DeYJnuLjs%Oo+z(2U7mBcr&< zAd&nRBryeX>SXDwhdkNTQHOZNbLq1i?)JKD4+*GzTR)@$n>xPUk1(p>+>Uq6lYxnp^;#W{I&t{!>M5@B1qIOGY<|$gQes%CSyGc5J z-;MZZ@jHJoI*07iO?p_=$Z+2qL2&&BD67^(DVx_ zl&jW)9y6RewxXRd#i?7X1^)|koVxq8V30$jHffx3t(v?2P1jP1C~Q1jMuKK8sbqv%)-r zOFcWRHk{h3N*#$sKn~-)c+!pYZB(5V8-7#kLA|y$?ZX=u44D>GEm)=W5lbJ z@IzI1QhjeqA1JPWqAZQ9!;(W{=x_85}dPoB2D zhPY-Tj+w=CVe<-_t6tb(Kww-@M$BD7#4{l1FLvqI9(tMnEMu%BXk5)9BKbC!Dz(2O zW{yDU#y*Hrrf1{nSZRVEH&k@%P?F8}I?`hvFcDJu9SKv@gH+>KWG~C3z1$+;<-p(e z<3g1gM{X{{xK%-$>+8H@SW}G|G!(`TYB)_NnJ48OZ&YtwE0JDBa7pTUU*kr60AfUw zqeM_B9rNq!R2)}i+S_JGP@lf<*3A8GofN`dl_?!64^BQFwQIKooJ$Wv1naPmh{f=UZRAqG8;fcW6(b$I>2a#Wg(UWd$?Sw)8}DK8$0S)c|CX{<_?8Wv^11zgXO|-7YAMn* zNff3RJx!;%s+f~!MChLhG#IjJ5A&pK%NUy6VZ>Alj8_rgj1sCD8Wqh(3*R1|1#g@9 z$Yz>zp}THi+cA)-5cT=r*oC7KN!0i{-q15@3YA{lXBjkPCZ$Ko|8d4tqB1^KGWLaN zV?fp&FXhmTwyVDl_1`Etl_&$&;!Q}ijRj+XtSe*#bmRYLTW&}1$bcMo&u>H8fEoWA zbx$SA18cI4+wj01vOBURRAV-=)`>i)6~j3$sUi0i8Ei)h#3Leqw^8atCXEMXvkLK> z{b0xYuF1NO5kx3wyBn6-_EwX1+y|0=<;rcyvag8f%zYyYhH5TcS@!}6ThFzWOVZsv z`&***#wqaXAnmFDLehi?^SMB>ZOYTxbF{*E6E^cuZb^PCV-Z$K=Ihq#B~M6(tNwTg zSJwc`%}@ZF%_9OZ3%BF#UAR6~PlpYz-v>u$L>E-@d%oCz+o(RczgS&Aa5s)p zXXb7g(duT(fF;Rmm$G)OA<18zd5?kJ>mz)7=n49CaQ#whYa9!%X-@xZ`?yWa3g7BA zizKnX@!!Z##c>r+RhVw9;PTrH`7#8lsHfrFX0SKNH-0UJH4&c!n0Jt9T-6L#{aGtt z?1$5%RpX^zY-h*5My?gJeuE9OZ}*#vsd~2Y`h9jmqcGpq+P1vUEv&4m?+s3=8cr>h z8pb3^Rgh{CRrXthDslP_U-Z+5UXAZKUAmkDwwf;St9WV#^OB6>>y?(BnZcL_fq^(9 z^n0c)dL6DMmvZn_&&~E*Wu|eKMA6Jqe@{=XH+7Jfk$zj9bze{o(WbIZffOzKg81!@ zXQgzWBMd(d6+?Ea_)em;QD zaD)1}mF@gq0E@z(z9=zY3`D5kV5-9CCQn&hyQ1V2^D7|`+rE4BMu$4peG+~v4_ym? zVK|3Bxz~>$_&XAput)?}@^(Y;ReXGl=|kHgc85wx9}N2Qu9mefxH|W3JfGPKV&#@? zhc<(n2Py~xe|h`kR|_^mU+~Y+kN6NMNF)&A&(;YYBApZZ-O%}@!y&%m5y$4Wqj-kndo_=_MRwe7xc8L(URAG}>WnBqgaDg4V(O{Pm zvqQHU`U;YP{5wDofP8SZ9Vib6^4~D@tDuVl`R{=qj|LTd4RlE$e?92i(JF$kgKi(l z|IW~FfG!K<^I+8dwB;MnT>~x7!^EZ}xYo|+eu)6@0x=^eiTP zA9RtOe;VjlNv{K4Y!^^b@IxA1$X`jcBTO7&iU`$O(TgF#S60FGX(7vb6&x!U+%Ig( zy2;V&9szwQ6Fg=Y^~YyU@D4jBKO`9I4APG6g?qrtFGljGY3UYN(lgLvZ_q`-O?Ezh zOwsxfN`gNDK#{tEzLWINpu=_n1%v+)Yd!)SUdulatPK?T6C(Ws`3cZcYAX;dZ$Nz< z2gc77u)%l*jNxD$$qLE?V~rh%UJmqSN;HV(0lQ~7!-~ESET=Q@Z-EC26@Dq~x1w#p zK8VowX~=Sp0cRSyIe`R~xrxNN#a)kwb!XeaPISmHc z(?ygal(U>~07sxWcyLy@B_M&1$^u73MYIoO#!$s+u*lZMRNBu3`(i?82H3PcW-TJO;y0%yn0phrH^53vTe=U# zEaw0~#}NLf3+oI|0=I_9^8t#c%h2*daIYisWb$bAZ+o z{yA`JbGX$yLP0dRB4)#JMS0UI_?$=xV}));no|HyP2Dt75b9X~mMb+p()~55#UE z5?hS>oH-EehVGXWJS)~DB0q`9Zz95k@Q@RHIyM}iR_t`# z?bunk2Vzrkr%2xQaP~_ea*u3#egPEa9a3^uu4QcjJ8wKH)5>EDm<(3lVI}7qWC9So z; zgXGwfx0PgJE_8S|l7*p2r|t121m{{oH*)8_Or6n1 zM$apf#b?wN`I=c2P(|LW+1YErwhKiX!x9AFq43)_b0X5jPs?h3JRB_%q>Or6k1}Mr zkY|A`>w<)pLb^5En`CGZ#X6Y) zI@!5EQbadpL7i)XJVLaUttTBSS<5HEe1pI)wl=1nxS=o13K~Dq?^gU>i2Y2_e#GK7 zn9^MiA?Z|rJRDcvAe+SoOUH|mVAc{yP)^l=WUg-FBP%b4YJMjdEvig^zZF#Swy$d+~@~@iV|2^wL;cn`~PCB!w)e5L`jp zxk!VX+;VmW+?@$`vtK6LP1s>EzOGRcyRmFiOc~U17{sJd55k6yBSCefc@L2~8`P^v zAA1y3`CL#p{KO zfK2vI!#oy@nPk4{G9x`fTcy|GzJ$m+;`G?`&itYjYaLP#MRPE8@L=kdM zhQLG$4a}xU3htZ>{4&Z6wpAn1javo0=#79LA$%MyRNX?xF-aYL3ef9>Ps<9w1E`Vk z8EKdaBVD8rKLgskHQ)=DVKn@^!H502kO5^fmMF&9OBnn-Z7P4B7 z14p{*jkfBm!Gf6-x(7nGuI+ZhVXrqV)tZ&$V;*)4q2E$$jv!h=gzU6ET44Eh1-#nd z@<_Rr>J@m;FCbk|+3<-6bL&(mPO_BWr3EbKI&e77#r|Wr;SiQ#zUACy;6Hq@s-YzY z&I@FwmUiSk3-}dWu~q@q3ypJ~Hw{u6V54ESI&^;mgu7j_&i*uw2I=Kbvl&P({)tNL zz`#RjQf?uz(!$_#8j*{fN%#<<0fDtzNM)IKD}>&s&|K#SeEiPG!9Gn6e`sEi<9x}T zD3JEJV#5RUx2G%}!0kn3j34O@Zaa=`<9$fm?O$u|NCE!n^kO-r5x$x=#Q;Cu$j@0r`@*>pOa4E#$rMb7VlAEre)!OTV| z9n%Tpzw-zj@xiJI7aO>Z4^~aM6mU;mv5r1iDc|3~y|Tcb-tQb?1P}BHy8YX7h8vkf zvdCD@IR-x32YXt_Y{)Fc6&s7q9@BbMNp1xDK|<4g$yG@nGjMGd*jtiSM(`@1pr<4s z7@6C$$XL#|27bf`drGnuGCkrj_jON6WDrUVIr~9CgqpG`QU$9vGIma8^AJ6h@s{p1 zBVCeB+Ec_SMzGuV1TCl5$W&#M@s#6gBX~?sMxc}dR}IR}E0B2~SM1E~DYKkUjLZdD z^jMD5POG>q3#pmLVx5kb61DuoC@xlL_#4SG6~%IL?WU6@sUoG$0hDHM9y>W z!pD<*Y#+)r&Ml*K8f>)~!AhT?8?`Lw4I{I^PsUYdIiDJtgil61MjI^Wd&pS3!KmYW zGM>Cbz(wYCpNyNAHhdQ&IAwc+mb1H&xyUEuF{%$_PQVqr+$ZBPYOImD)hFXOYOWD{ zV0(g=bF-0I=9BRl^#o+r;EKKOlkph!iIMrpC*wD2ixJ$oJweN9S*A1m-6!KQsvBeu z#}&)Z%WP8~qfRw4B|aIyQ8SHT=j{nv&P_&Uf1ixUsHY+GKCak6pNz+-jYejePsVRl zUI(pg)b<1|r<0MH>XY#pRRx)2aK+~46=j45`c1drlYmd8%vJIx#_h&>=&LdCqdwSG zp#@V$aPB=iT4eH-{EADqrw3BG0o3&OLovzIPHrl2ZtXZq(er09GX zX65@}N3S#E)iSJ5thO)XZWmoxb~yI-xcAcjJ}`<-r^Y*Ehe|QVxeOJ9+doDzzK7Cc zk_lDj%|~wB5-d6~?^0;sdZB1|-h4cAK~Qw6)u9VFZCWKeGhFYAXBTXBc^-LfAlK?L zd66~+Q~y@=R+mDqF}hsHdxwrFfnB_@Vk3&gId3uFG)3BRu2;s`p2zYQpoGQWmbS*n zzI^;eZ^ns;k}K^E;6#GIWdTnCz*bWHr}l898*`8wi)cA>A;AS;v2FIs1;s0P02~5} zb8U*#Iyafh+F1#ajkt>Q?H*c$pJ_S7Y``4liX+<quBkB{y=&(fX$(X;zW z0a(i;96axl({YbS@R1v?{0i*K$HCq+!h;kMzT=joCsvPxP5I8u!A@T%5$##YpO_%S$i|PoLu2|=O%b%BX4=|U1cF|-T7vzl7{u_2vSnnR(Ce8JsNYN*v>lu&jUhe zY(4S@;&C55wkXXz3Xkpam_MyUEgu%?w|!Vlt2oaA9^?-yVE0kY{dJ>fL$q!P88}!h=Hh*uQGZZ zK$1`08GQoJp#ag_+g`)K;_Tc0WsuH5w5h^rDxL`AP?r&z0k+ltZHgV?a;?(OsRqV6 zM=pkb0v9oThIr`&_G~Y-XT6`SS^l<}|b5Q9taBe5} zc$1IV8My+vMQ)~T6^{e{k|HBr`yvz;8LRZ)fVkb`oX#|^rB+1+n8OJ0ZN4hLO2@cp zRh$MWNtiF}J+LLcg>bT?yy} z!mG2U9tCJ2;Wq;GI*YHI><)6Bi_kf)fr!=RBJNPCK)9b($&t6mEF|jAr%FEcU?=Xu zF7A$|PVdUwf$Uq!p}WU}6z5YV-?&viN0Rz0<@O1lda*C65YU5k<$B7u@r z<&%S*h8Pl|e@3v=$%Z^RSU$%Nb{cEwQ-b9SKu&?!To7A#)` z`X)n<2$nAfz1YwrgXK#=KVj%G!Sbg;zijB!gE-q5?DUSI$MR@nu+x`@9>aQ!l~(U9WbCI8-d(Ue23`eJ`~_go*8%cKL!@LVns3Dcpy!cy0C|DC$-5Es zC*<)Zq2@J#?)e6I2c>!aK_|)UpXS{H`Umo=(!3UL;;?BC@DAhqILV{*5b#Ff>X7*N znT$5U$ThHDy(pY@C!XZSS*=w%5pwrXcE;qRL{=3jawAfpm-R$1FF7oSJ+Avpc-&>T z+rLNG64m#O0Nd`6q5}qVFqqS6)%DLD*?85BX1kUT`NoJsNb5oxcn;Lu1Jp&^UDcI%rN+ zN=^rjL)Ys-f7uiCSkNVQ{-2;Xksb%S%+B8n8HxNEpu5`n2Z0uS<3abd^9O-G`~k>M z0FA?!;axy9LP^OncDM(g+d!b?1pB~1nQc|zDv8_kCa_R_j={f{2gO-XpAb%O;(0zS z>tkUKkLOls2G)VQBgt7zwzoYQKecI+?Jb8h`W#Ocd#hwm?J3V}vP#9?TE#*ne}gJI z8xh4R7R>Tj zwxokwk-O!pMR=URWWV*CjmI##TTg|CgU=%OkJabk@f<$>^};DAUl9wNQxdde@9%-- zNbD2b?bzqI2V#x52V+0ro)h~8_uSZTxQEcIhM||l4=UdHBIYRZDS@)U-fBQAxV`~^ zdi$5pmSZW-LYc`4ClUqUa_)p6-`&Qq3z&xQfeU`5p1aejEay*fjzxa)X9I_#yzD6| z2WKR>oB_sP)=02$SIN6`Cp6g6`(Z;Mh%xqSh*`z6pe7t&X6K)PB2ZEMV9q#$(V}Gl z4g|dds_nw9_tAQ%FSr-%1Mb^qiCDNzkmy-JCQ?2}tW@&Ro4|dTT%N`>TB2*g{exU} z(pc**dI4XI?E`L!`<_zib`AxSB4Q3t+B#R~0w6CFDfOj^E(Vg@7f3}q=g2O1q0G)_ zfQ}^8EkFhhQyH}zPVNCnfTLJqRfI0F3WR?k`I?=>N{g1jc~WV8{E#yM5W{%9uc-tH za7v$B5z(K&w5*X|L5zo7?amBR@2o%&RhjRHTp}A#S5~wZLO)aR4-sTde(?ora=R&< zUA{)-#uc{%j1NfGFRj{&-rT{qnsCK=63G^es8Hw3E)*$y7&%+T$5$hD{NQle9tWvb z?M%PdvOe7(s{4oaR!ZS=wt~pN&qOlb@FK^^9O9Fau}aCj4w=@Ap=Yp9#?=!!a0Hc= zLMTDOpN}rpfd=M&I+Fc=yt;6vceAm66NE4u(JF`z@q%jtnfO(9WH?KvwiTb$Dtl3T!h;{ zcoTOX#wX>@YtgRiXCU2lUpkgJGG?9@j4+86?TA5R-vp%352sxxk_?`at0rZLI}bp7 zJ+642Px;rEvoihyG~hwN7iWQW+c^?=9cAWck+Gbs0Iedtz*k`^hqZwILwI5MJ7nqF zY&okR!F&r>{5n4pSYlaaxZ<~FsZ&BIuO!L(aS#$%S zUH%DprKbit$cjr=I0uCje#Xwt$Yp8oX3#(L%(wB!ahE*Q;C1# zb08b3<(vg*G2u_M!b<^tMR>grRvqLIKvjJpuIRo6QiTvzCqD#Pio5bU-Jz#shDz|K}0eTuRs?xG%;dF%KT-+#`wn=toWg_a8)l^&^*ndq0ss{m3)mzDpz+^7Xk5;BF<7 z8#)p_lp#&`#;b2c>%|ohh2E^mK%NBmEh2d#Gd4V;%U6t z?}KjO9!8{fXdFH~J~$TS6e4XxH!wz}y)zr!n~1axaZceu?ge)_k&@8s`0yZag8UDW zc9|CF`PA=#y50l0eO7p1K&KJjH7h(G&?SUBYB*>r@+NSfCQ|N4R)G5jkqSTZBe*TG z&Wd;PBOSp#m`G1(?PP*HTPW!+6_`R0t4-Um#+Q;RoJDb*WqW?=~T^}#BEEf_%oEvj_(^PJ9Lm9&Z8LM zImpNN*R^gJj$lDB9)K%$_6}v(Nv}Xvj?4`947nQwR`Jw1)c%dr@)(o!xFYT;z}}W; zfHe4cQ3j@xckptYPi9AuXBolcX+#iTM zU1XZ1sI;6d;I?Oze6Gk$*)?+CCHTrAuJ}uSWIedS6p)wwNNaG9Ao50$S#l`TN#SeP zfF2}l#ay!^Cmx0=`C}Ke()wUKs>ZfV?#js#~3x%;NMk+#_9u!;hg zV@VtDQxtm}xE1>rcYMpY1l<0(;s<&X{K@i0M}mDhp#dH!e?FmQU~eLnXa*H7#BmE; z@gvia6+IA~bICn6&6Q0SD>~mmCwidP$VL}*1@I;&JMngBZ37~e3B<|2Pyb| zU{54;o(JkK&?2zkBQ(PU9YDx&uEN*USsl`(rn9l2OQbly*c(3J!Mp=1Wps+znJKj zn2HoZ^?mhd!PS;khAVz6wMorrq$jvFL>8sc>!2fo#b|I6W^mp{nRYeC}&AVwMb zZP54uh;t474ru%U#Knew7j#*$fQsX*9fpCc8LKSk9&px>`>Ml?Jje!cTki$rH9yi5 z+|!7>?nkDAdlQj2{K);_zC+|qA7XX6WN+l#Wfkwm*CNQttmN#$&1WV1Ngr@FB;8qw z4xVZtW)ghG7#j4fBm>=*Eyo#a(D}AP^?>^XgM8;HL)5IqYWq6!FtZL~&1W4^F{bpd zI{&Prl>il;5Np!24lP{`rkZt7DV?pPOV0$LW*wP;lLDY;9V{P`cnkZyLCft7R0^9h z>ktDXQcUMYoE2RLH%<;59w@Cgz{)*OwS?3G1B*s|`2D}F;dwT6a*eF34H(~#v{3CB;Mqo0ct%D@EiW*YUtY+*f`=JdvG-()Pemhq0fuWh@flW z6L9xJMa3IEiS&jl*z*V>*9r7iP?b~fAzcq>4Pm>r4vJpbDn1>xD1DJ{&HXEcx9@~P z%Xws9w=e3Jp_-?>Xm^?nI>pXFS0l0I>}6WXe2wa6cqmc#ty=-j&?^MAtF^9{^MJRVrmuQ_`ic0Z@H46L6XU z=)TJGyM0wTqn&X^xt)QEGcx+B7@$h$j4`SD=~T^}#J*bk;Fp&5F|PQ}x_PAE5sKC3 z^qklDoDPKFDvqDxL#(zHsN8ZMHL3dP zRJz^-?fmXB>OhKB9EDMK{GCYI)x-44ZVh&0#G3abMFe%kw_5&YfDa7dv^gI=;%00s)B(HLLBqky^s?%?NM^D3s-gMZX^o#pyT+-BI z3{(l7&(6~?n6EB0V~es{@=Cv8PA4f~vEw%*pP(urURr%RDBYWLQRwEqc?Dg8P&Lrs zn^y}^u@*qOH*4u%z*N1NO6gH0UD_J?sotCkIQs(7y_xMDNz{;}#>BA(Ew?k!!=OF0 zH;VxgD#x#ym{k3AD&3m}?R@9)dfHfgH>|be{XF|LpQAZ!#T7q1WSU_M7Q}Mw-iX_{ z;zRvNCAb5LoZ#;5=rl)yJDtdIKe7PaJBiH8)D|g5ZYoqWe?9cS2+1!go%Bh&F9*{} zEGO>(9E`>lzsx7iXL#vcJ>BChx%KQas4 z=ZI_xjilR9|Kf_sbWqkVtxm)dxr5p8?g-_606F()WUH-Abyr9qcBEk8SaEy-6U6Tg z;UuBv^zQ|ZY(G6hc^nT4G?RY}@2U1vMWt-zF~1@OL3|W0mARZ z#$OB7f)kKKlD0_HD~ZXF=v4xVH6gC?Adv${dL#;%U;J%xiPDN6q5x|n*|~YwH8=3m z{xtA2kAZpM#5WoP7n}qGZ&%q@01*Sfl`rjT14ZH zoW)?RB0DdS-H`oU-mp5agBhs;5Y5x?NmKyf;yN<)WYbWKj)F{1JU=hC3m&Xk7u@Yw zAKU|Y%Z-oQam9->bu2+n9v#jS$oz+L?K0(96JELCA=o{_74PKA$zZI4(%wKWAlk!4 zWiVjNu$+s5yhyZ9o{7)TvcM4qziAQ=%1r!%B#sZziI4UrR`AJy|A8xhd?su~Q{aA2 zuSQI@EY4o zMoc^jaYJJFWILnkl$)+G=#)%UVz={MU!8WoMzhA~0-B+h6O7yP!a;IZq24O~7xcJ? zEZMTmA@EH!c+5Z@t7ZO`jKJcleL4}Hk8Eq#Z}bI4L9$~a`HQqUzChb$HQ6tbgd zLy6~*r3Z4ZV;((_N8f%O;< zd-EB`I;n`#A2E7ouKPX_prZAm-Wi9M-VaPQmJDCcLN}! zJ16I!ZZXy2xv2)7VrQT!B(|It2A!`_U7R0T*v^e3&AwYy>`-s}h&8X%nPN=o`4jzh zI#+;-`vIh9ky?5kn5s^xly$14OM~Z_I?V)}Jpt%CW%+!ConX*%I|G%%W~>RtfQS^+ zSvy7R?59&@cS7-aSZl{;de(&137zsnnfANZxa*||56tTc*bMCTEW#C^AK{r#mX>d+ z@dDsMa9f@UA)5~()v zHrV#rfNu3CY6b4GMDF$^k|-Y?3HIfL9`isP_^jw1V6P$cOd7JHpMw*H%i=G1xK1fJ zr;_`!EC^jMsO4n=eH?!U34*#DR(La-#>#PEf16)?4?auc_vVLI!t=6E@)!@b<%QN7 z`f1PsE41Fw&yco5-y8Z_(t%JxwNC#W>0oGALqAVCC)Cx@OG)R3_BHe}(xLprK=XwG z-hiW9;^*xR{W56$|ADcfSwr!apz;3)CW5B3;;TRx2b?*eW&LrVdqS=a)S){+287?< zjNk7bZxckfqLYurst{NFfqc`7biywXbBf0RdC;7BE7Zs?;0`A8kRLe~+=WCQc8}xf zG>gEM;|Y&snqfKr0;0BQ^BGQAgE~#|>6SGVSNzfZOJ{nKf-6{m4Rl@Mer)sVjg7o^ zk>!uHqs}}VFI(IJ{=<&=>@IR@zRT1(NKrihJ>26Tv<`jnrmnhAS|e{O^n;;4C0!UQ zdQ0OQNSA~<8~SraA7JP&NaNp982U?vk1_ODq>Do58~STSUux)YNUyg-_ZY@TGV($z z42}QT$p3?}&d}eI4urNEx`}is6knqa{+_fI+SkxOkS+_IYUoX*yN0eX^iQOFhwe7? zFQjur%M87lH2Q|2el&a~1u9p+lr|L!TNtO!|2{^qpbk zlQG8*S!=b`Ey$>~LlMI$AOrtIByJcHGIB#b4IL#NJfsTrKkrA&D#CdR%G zKn3;t!2B11&aSF&7gN>8V77S&KsTSN&R~upu$K=w2h2MO?C+{lc{~T^PXzk5>4^Z# z%-!y2MgIbFz`H=Jq=bU7RNBA+L{kH!YhqHCm26=rau`;#M4@=H$z}r|I8RJ@@WbXH;yb4l;G2rL;%C_R-759m`P!Sja+Z4SbQB!x z`MQ&{JWWh9utl zyvCsA@{LdzmHNz>3X1`HkLCo^3i|0(&FY!`p#3kosH1nGGhIDOOU2FbVf({wgIfgt z=o0N>1;3Xhyzn~%Uwd5!Jn34(j~!>=0W}%$@#hlW{IG#PxgrBzw~+8D+YIcsFqQWQ z*AwQkMP(X~I!XgnFwf*!?fK49!R|Xv1EL>H zI5hW0a6LO5TKD_l`o2c0bUTHEo9%FDq#qF94u`gfXCOQ~9Fm9L;kXNsZ-+xA%Glvh zDd>`n9S+4l7=^Z?A3~95hrv*6q<*v^ST5e~c;;xJsB?hR{Id6{AI{WEVS>0$AZyJsaX>?Vfm zVMKjh=}gGnj4S@9yO27Ssntu-S)GuL2u5#*&{_)qg>{l$sD#uG>xW?fLTFpQ4)ulF zf}FneaEwcQ5pY9b|mWIecl5ZSebo|2d}p`&qj z7gxNaKh5so4kgmHg`RMjG^4<+BhszKWm7XOcng)bsy~q3Tj-{wrw**mcn{QDP>T^1~$;`oj7+snVC>yH{Da${O~vYgu>`ZC4u4w_2Y$|RPv7Tmvx z+!JIXx?UqOl%^lcc&{HB25yqb;vn?50Cjbp% z;FL@>g~XOqZP57|)pbW}t zHFJV$z-NdP^o&rvpl5_zk*#M&c#V|U>3nRn8R3nBM2`dFnGq`aXdSqo8KLGr53XlM zsC91z*Eb_nx}BcGn#~9`ayk&-j8NNiB@oYyQ1Z|-!q))#W`rtH#*9#<5N~>aSVXaJ zL!qr`0M7Hw2tAO~-T1$6K-Knk{C@~~t8@kiCx2&nSULSy)1W8Y86ialxP4A=J3|I4 z0nUj*zqGCSI&HH+CY_=9my>9RZU+o8=H2H^sQ0vkrOKrHz?CkMe)sv3Akhzic-n!I zkG8;@V^2HK+(W?iv;(bsF1WsSpmaM=1M$84)X4WheC zl+g}U3c4g?WuVxr$c|nHMV@xxft+WVM-RBOZ-6Q|jgU8lqR%ssJc=o&>wlS0>wdTg z-a&c%zpGj#oD8nd{~ZO1rhs_-ujHdk!S(oGb2o$Q@xRu+-^gbESGt{ZfcX5ck-LES z{IBhK2Z+c2l85%c!)bP3_$K`WKPpj%|5XaQB*XuT-35iVq6sMS_}>FLHD)T`H=t&F z+W(?YRz!@0(ffbHzna0N-#xo)9;HfZ>|e8OO^AnQUhJ=fn+p|{?kD7J&?>5qU#K_zyrxdA^I1fu47^DC27ct_5^1n zxhXGqA~?5^d#Q)(JPeM!V!6zH#Ud74(T{=bhC;?~fPAn}m4my7cn=KrX@qXfSKEmi zw%VOT?oCW!>lEBYwcPhD(Tl&vIbmG!T3XTB-L+BbN8HD1Jo8ulfCert<8F>AnNCy~ z9kK=Q2ytl{cMnC$tl%`tYC9S$D>Jh9xd*~k{%?++1TIb_wj1vs+4+TE{NUO^0O_fz zmOc|qHL_DFCrnDZv>t#O*)suW2>?B^^EItIvXii!FAQ34XP|?iJ#%U*21KYFhv`r_ z(b-R@(k)uh&ih_yP9(;l-HuO=x(8I9_s8j!Q==C_%(aHEY}I=5DCSVWl=1WBEbK5a z(CmxRvUD_Mza^H%L9{(oZ=Pd>Bh%X z^Zv${cP~WnEAg1d>&C~k({4|bgZ9q8&>-j(I|Kcb9&r{JbiPJ)vA-nRIX=%UU*19< zCdd(M9^`%i7eTJP#vkN<7NFud0O=s7rRRaEf*h4H$SLX4B>+^A%LJT{0Z4JmY?jYg z*b?K4@=R0;o3VTm10qsP=Sq{RpH9`x32ONgL*90Lt|!R7gh~=?YNHv>m2)Wtl#efv z(AFqUu)3U$tn4ng&%j;ke~*7aga0+LE^Ila6Lgu>u#~2Sx{2C zohl%{`J_h91>y@z+Mc_Cc!HATp@Y(TK)#@)5@iG>l|sG`=?zMX-D@#C9Bm8dd4iG$ zas~jB=G8Yq74Cdq^vTyqrC}ERl46}b?8IKegB@Fodm#2L?m?^Q%u9(q?!^88ZN(gr zcC0Jzf!HuYR`_U`QF<9FZJ84ujpw5-$MXm$JPpr_`FxcVJ|EBjT!`muo$w+&mtBeH zDNc9^o)_?WniGBt&;Q}`45#hASF=T2*6Ct=@?CFy5vQ%Yk{w@&PK$4>+y_G<@*cQ! z3D{><0J_R-#^ws@;BJ+!2AU#zT{iS{pubb?O<7Q@c)|^yrg^fbX>PhUqiJ?$hWH-N zb2a$~x@UUjZDD1QINi=K|emh*{0@%t}=>eyXHRA&Ba z|Bdf(%>YKM`2cntxER3dZ}JadCks&V7=ZKurlsElQw?BL%66@!OE&{h16U^Dw7FRq zw#;Vve1$#KpyipU6gFc369XbrOs9=;LO-3VnG;lHTnwY^_4wd2-P&U3rHdu!W$148)R!?6NC+fN9Ww6>a_vG)JqAxuQt}o0_6C~OQ#M76Q zd~}yvGWwF{4h7fKm$dH7!1eVdrQ2Bn#24l@vIU5*FKK%^qhOxCBzfq*Gy;&XFR4Ts zeMzN|%J7DH#h!seThVKw$kUfRknzntbWy}Y>G;{^hE%wFJ%JG1^`mnGMnXd`;scGbGt^%Gf^pQMqd&G zB2rA}U+4y+v!71Y%n7P59f!Q_c%!E;^#e!xQd1uHR9JxdQrrT{#=n=obcJxN;-`>} zyN(kl>b`V5toHP!M?~J43$Cv(JuXP}5g?wvq~xQYg6kQVG`IMUjJ~9G9}TXrFDc#5 z#Xx+0Nh8ky@%1Hb&(}aaeM$1reW{eL?F(0=x8PKwjJ~8&NM(5Yl43uDLR-;cP~_=L z9>|$(s;_TAHJ0qv*X7#>P(#H}KcagS58L=hr(cxo!;sNEO8<1Q>QQn&#~EPIDRu_h zL_?jVLFa2!Tk{Ih&OGqL9_94>9_Qe2;fRD*;(o7QzHn_7&`^Cu!aXJ=_C-XM^W0YV zkcH7;cC^$X3#%;;8krH0iJJG?kEOt+k3Qt@wVw%4@g9J5uhr69z*N1KO4;a@bZJ}U zr+RHB;OqxL_gebU?X}9GV+~qvXQ1NHj9x1S=<=^LsruBa z$jSAw`DO%sLyGIP2hs;u{4Do0#QQ|_A;w1yPcv98~WhLi_3G#)i3_LJctt6MNd7;*?TY?>-h}G*Z|xEu@i6)#?Hb$CpHK7 z+}PE)hhq2Po)>!o_i*f8-1B3baJOSYC<(+$aSz7!qQcmbxaY=3;vR}!fO}r-GTg(l zJ8{pqikH2JWbx|2zz6Wq@qQRQ7~fXKKW*aW(dpt3$hK$x z;7Y6uj{^N5Xq-!U4LEBsqM-90XxR(C(`GU@m_C3pUnqsjF}UJ)nV<16$l2gN zN#t&us?uo+mXmuQ7{S8+L{!&g{t-&1Ep~qtKm2JI+q&Q@B)c64O-HX}r2anZf&T9dYKuuHz|Tqn zk*@Nx*?cNIN%EGBr*5#Z^CB#9M&Q9J?v8ub%4r;FD(Bl(x>R3W(7aTqiDqx9gcBJ9 zK7NZ4+9kAJ7nn#vl*$8pOQrNU?U0u)m3rr)6IjkPAi7lgZAjr%$y?rpNU6@f#+0f7 z!dXkjwWovHm+HJ`r4mkLrj+XQSKLxvtV`vAy`@rmoSw)_mn!!zB2}6SNJxUx z1nH=V4MkrNMX?|%7DPq#Rlou&HWV9{R}>4P= z_MAK4=88^1Qg@zxE|!*Gpyl8pPk<}U6=6A74e0c!cFSe`u(Md<_QCC-Vqr4m8^2q= zn;BU%!H9Ruf?fln?UqR>6{AI`zYK=$mcxvsFTs#*nGUWZiET`LiZ!VL%w%q36XISE z>EYW4Y(Q-i9wZfNsxFdBx@G2O({WjHLegr$_=wQ-zz0Jf5l3qjbCBA8$ zYso{vwU)6%lYRiTCiJECs71oadBQm!)R()0)3cU%&vw^!T7$uTcyD@Jh4kUaFM=SR zu#?OD>BUT|?0L<`c%#|iZDi~AqspBS=Ca$93L&2hWsYzwxR)pFC!YnJX+TGbwWiVe z^olj@Do|0=F8kfDY1c3#Yatl%nkMMSK(sZDgp#u?I{h6mY)uO@l8%5OHH}U&$7&iM zX-;bKN35oWxHBO=T+`Tq+9W(kIvJT`nO%%cC9Ys@c5YAYM5?nBbwVzGw-(eI<=05=G{Wg1=U%@itIU{dh>28J826z-n?5lzk=h< zyTzWSe}?AWtV8DA!@%<9-8NBZ-fdH`zubAZC9goHgF1IWkTdUgSV^yujvTa%GZRQe zY(L2Jf6oc<|6+X8cBD$_R-?PSbQ(BqXKF|KvnH^p1?0A->o-#`x(%w2KZqmxcs!+M zy!}@Lg*84`bLL2=7TJSiCxhFWj`hD(lL%BTd(7k_%>|X)@XIyNBMSNrK8amtC>Z~t zB)e;Bl?>|a0D&9!yC7=AZa@zVXj38~6`N8XD@#A-7)&CFb%I5_UZ94_s^sOH6G_zeBCllty!olbTc&SHw^8jAu@rJaC+*Wbt*%L3Ng} zLfr_e)09N^51@KY$;wV@fwnv!q^f#WqLvFAE)oFy#lkf!t$SYA`Ii9$`ureJ@$ zP05n4A}81R9)g^v9IsCx*+Jdb zk2{n*A&p+g;ME`pk05cz^QIY{~gl+#ZJb$Eo*!+EuA z0zM*Q<&5Gtlw0zXkQUVGj1*iNqkUG=P_X!&u45wh`8j>3>r5~*=*GiXO5?oKHR+b9 z2|mO(tuWHJ2RF*thPW6*Wc=wb{weM;e1W?RyC!J7v4Ki(L`LVA*#!SZmzELX#nzEE z(AfiS!6EP(V6dCcLL7^&`Wo+vc-=@%N|@G&{d241wiZOrij(n=RiKO|YBVBe=&gs7 zrh~}KwPq3Olwo77RU|2}vRgt(LM@gZ)L8{A{XJ&dX>qEE*#Q>*5j;q1BgK+n-*0A* z`ecH`+%vS$YOjNm+RU|zIzwc{Dysbum)X@w#AVjSXC*BKi_5I5S7z(L;4SMD6)R+tV^ z+pSsI1B|TQ&Z>f*KS55NX2{+_0iK%&7%WRZCX%| z5dHlu{0yTgUk&bwDE~|Wtr^|Et4jZhIkP1Or<0mbMo={|`gI?m=%?yE;Pr2f2hY-* zcSnFffPeQK@IIm+dZliZ9%_rysjL=sm9vAc=wBD3v>#w0XAJ<2YIu}h(-fs>^cTYM z6}>MpN^eMv()ui#gq2?lzDmVaReHMiiT3!LiIbY&hoEXglpY1H+7Um0A)bCx^B)jY zGf`Sjd>1bRFy2{C+tFy;~#y=Fz;VYVtMQPz4%_9h3aaz8jn@`Q( zfaepdMJE!UPRU34hYq1fXA_OCau(CoMUz3}AByJi6&=&JDd-e(&J%(T|4=lC zujr|`=nW@prdKgp~T=Tc6(hwawZdPMGQQfqLeIW zFdqSwa>j>W><%3}qM8aaGLe{r32+&Vz`ihiOTr3x0MKUvLbMcnLV z5{*(c%2E2m`ka2mT&dGO3Ga|6>y&=d*s>B1@%pzRT^1_NZC7h;~v0ii|R*O z(D|D_OF`l1NaxnCcFx_1^l6EiUdzPlk@0=4n!)cvL;C$xyJ={(&w5gw3ZiX1Dm4?H zSOrlMbM7!CZE&73=Usz~nfRKhp&0^y+Dm8(`WE6pmJN@}Olxo(pmj6vX)+h#p;Lk& zb0?-r2~AcaO78>B+(qvtYDlQeH8d+d;X#PzzdsMM)`0o~ap=x~aJceky{?>faSr{Z zZEb$pTUP3O_~$8nGarbvUxU|!tnQ!|5odjz!++V5H5$};#Cb5z;XR0~n?QYyIFH3S zE8+PdYY(WbXQR)lvsXBe$2pFH7lX}aY>Kn3$mQU$8Bh3}*Ol{Roa2aW_&)wF6W`3I z;%ur>K~_GfD~Yo?&N&6n3bGypwaN$JJRRpaB98;>Tw*^HXWN7qfI68t&&E025prjh zJ_D@P#NI-cD+UR&9szMLF`kbR?d-h`*^}PtBW%~>o4M6XR}A6|V!RYi7o^_+>chl& zl~fb=VX8qv)>aUICB|#ivS> zgnCs!r2B0t_)VYaz*s`W0yZ?$@3@msxK34UwTn~&d`^=`v&?Rxj) zw@$sM@taidE&SH4_X&RM)%zL0$JR@Pw!eaU$rP9%`Z$?EruEBOkN=N_Kj^d327xKq z1AhO@(Y&s_6-}%i=zYgfV{1z#Hin{;I7&?b-C!_aGDT0H3UtDfu6dscwG12M)N2;@#%4LH!H*WkF64>IAxxgnj|+R#|-#tbSAQ+Cy%xCj;4c8;R*dW%&i7 z1v@BuE-7t@R0Z!+^n4OK1<}s?DcYZ+gLW-6!OddqN(s%mOx`5X7nPhBG$=qmGcv!b z-V@=CXzrP{?48j*h;vU?+uj+Cb!Bz<&S>=k%1=T(CDM@OWPU@Ha0z^DYLhJP;Ot+= zSpK(h{!KtxR{G^gx}1{#kEY#m2#s7p`dV;y5ceR(iF+$42-5e0_!lvL2qg>BYwp8M zTzoTsqymk}3(|XoIFT5KsGD>c*MYc(7(Y=1aTt$)_%1Pi_86aoc+4kY{7Ne-Cq)v7 zt%&iPr=uf?g~T}GSv3m88;J3{KH1D34AO4`@hM{bp_{^%k@OOX+#4hs?GCI@k`98C z_9>E7)mO+!aj-9wnt?Th*ws8XbxiV(_;KLhLzwCw#){Yi){n%lQ5idkcH4lyhJK=} zP)sf8>VoU>Q*%E?>V$wlGbA(xFHuo)>)cAM^HwkhAELTE%1{M*mg4l9WW=d*e?oD3 zDKg@e^TY_`vG^7cf31jpQbJRZ^=L@^$$-1!`%v5wKbGQ-_{E4{crQ$(kC|X5LR{R~ z-#lr1JZX=5(i$d`n2YX%Gy3gE$%>Wr0i%y8cq1gf3*du)BVSB1)L4os&c;pRyw4(W z7m&0ukd`b`GGfv)9)rw_sV8OEnt_)%!p!-XIHJsepx^Hhq=|ROgbag_c#hXX<&cwc zqXTbzqvH54;)RQ0Mqv?til$;Gs3k7&`nOA40M+PjGwDtYE=&3s*IteHDvH!m5;j_G z&3la}_kXy!O@1y{ zntNHyg@aMtyU5gg&3q&qF_bm}zaZho^WmGNA~Ys^tr>YDtjO9;RmbG_ZNw4ULu-zL zWbgTDLf)$m)X2E^B14vuhJJ;}$OEFQp7kiacj6}31p|=u(mZm(dShn_{qtXtG@nU0 zgy#Sca@)ER_@FooxlnEumHde2VkEezEu(BUs61=sT~SGjtUV*S2E55HqDKPG!ke6c z?0*pr?^uyONwpMw7_$F<*faPdvVWtYZuk?*&j^Y?WvGXx*26`!iHl}RHQeN;;%O}M zTB+Pkrri^+V_E`PkPAU}RLVy*7#*O|cajvnHRV%gJW|H{6R321r!7e7_D;8xq@Z6O zI<6~4#AI?RKBnNQkPZ7ODQE6k&RlAB+)iCZncKogtBN03Xo3|YWUbn>#SD6-5_;CF zcmX?djtN3wwwkObQ8D{c#T)^tLE(6ibJvsX7Y&VhxewO_?j=L3l3Z>h+xfb-dBs0ty7iV|eo^c;i+zJSx6gnbeGDY}sI&)CwvmMm$-?J>8k3Ey zQ))oy%)TbrBf>tEFzvCF;qySR3P4cY1Xufo^Q9s-rVKwF^z(oi(*qapk*w#=s|49R zdH4>{#{)2IFD^*r0|*a^D9uUQ<0-=*0ezWDssLzXB|WZ^(819sza8}j__UIOFFt&| z2|5VzA_>h-Q=Bo+1YJCO;{-F9@2^kblXriR_AbEn_Hb$QlZW>N{Uj9R@Bz5!j*Bsu z;Nmj67>SFyxWFfWv?Nt~E`8)wxcv>Y4`mctvZ0La8z-Q}5`xe6UFp$1`|gJhwr{$J zQ~P!R!1nz>W|4iz*An|q#|1vDew8GD-cx_CNB7iU2obFQK@X?urvt$1SCLjy{{mf* zd%nPhs((Y0|LCdT&f?}rOkKanm-{f)RF^_@{U5~QYNXjk#3 zDIN}bRgdnee*z+kX8~8+!;$*=puZ2m@SAb*Cuv=ci_AK>cnB9~;lh6UC84v*O0tnz z5}Ja`pK&|P-y3OXwU;}qR*khM{y5wdf51KQcCfi8ZY%P7sN4_CmXP3bAf29gHKMjB z?k6cO)RZ5aBS`tTJ#pQva8LXlNecQ+K;~wPh*Rp?OqznTo^>wkb2I4lO6b}XZ$X)uFU^Ch={4#RpMc~b|49*XP{JX{lCH1W zbM=~NPkq4l)Z9CN6Yrg$kwh=49S5A=`F|uIxjq%So+6dv11V`!(BU~Z*O!Ann8$=e ztmz5}v|c#GUicF6!o?6${3JU1*F@R@3C*95+NE4UTp_9Ck1 z8)$U8JfVo{_C8#D_4!i(xjrAuqi7H`kr4ISc8YVjQ%tD`OP9iDX>$x6TAhISkeexf zYcj=`Q=As=X}9sKdp9AD4>z@{BC@W8W>f+exh-G+u`d~Dy|G2sX9+sn)B^yst%ngE}09IDo4s%ot{p37TE?Gxz6D>qgZ z_N4mew1lzGyGl2}D5tUhLN*rBlwlW{*g7G;WO|EO`LBtfy%JU+jNVOE%R`yA37yWD*TCp82XHkI7x)zS!*WICeXoYLPvG@zquUc`y|ES0!3{ASH@br}dOIa8{_g?| z@{-^;w=7X5H=Z2~%9xGA076&kX&>4; zmn?KGBy*;%b0>Ioug-lAv$;8BdN{8+R69Q09GW5SHiy0xcbdZl#OcEe*C2wDOH6PV zu8}2kOL^s5AbKy9Ftl=I6fISK6qc&?_(5^(@(#n)6qPMe)Pyd3oF#mJ)8Xm&-U zeUM|=1K>LS{!fVJeT6e^Z7^%4PhSbMcG=y4t~5IAWRYC?Xrl>7lfsqntLa?%E|;{U zCG;vEP*nMR)IU_d!h_Igw-f3o(00P!2Iv!Cpg!@q1X>IgZUKN-Hn)i0rzJGU+l=$d z=FDVS+4v}|Y*uZPE|Za|Kn|HsP2ka#J*eT=BF>AP+eGea39-l-Ok+J><-chi3<1ur zb?y_udIfGw8O#DtVc@-_U?C-Jp8P%(v_g(}+m3Ws%&~F4?S^Eu z4ti45Xuh!yvg%IbWZ#hew6LmxYZDS*2WGh9?c%8T#f^A-sAxFGu21leT&GHHLOOT9 z=X}J2;*vR-vDyi9kT0Q0P8jrjCG@O4@Lo}(j)f;CRL9w5TIb}xg4~)D66zzKOB;2j zAzv5MsIJDeSEEiya7Xw?u%8FxmJp1=c-D4zT>OiTqzS-@k~}6RG#Tg#Db8eI1EReD z67u)pBOC_dfxfCD|c*8}c`O6~y% zdpNHLJPe%M1D=qIvUKKUohj}NM3*8?pZv)p_caOakWef`!dIoad^hRR1iCB4rKJh} zBMHoICORFvt zkv1CBRLgoby4a3sK3&JO3UnFME){9m^O zo0FQ+)NB=!B6>_#LdI(@^nF0xhTIQvR`QbwKdegbH5Z0bK0!*jngk*|rX*BNCIaVF zlg16Dn)s6t5}A%d$(cMs=PlZC*!)#PEs-D>hS#hq&ME8_Iw>HiRsJy-MlyV?J` zPXE(RgrDrnk_M?_M0qvP2^V=27nxv;ms+P9SJ3D_2dF{)Fk_$Qq38uzh2>RrjHto& z68F)E?4V(x8cz*=LgFENC|;f8yKz5`4OT;MQiH1{EZ?C9KcE)w#D&Ex?rz0bPk1qg zUjV6`qYbzSitoUxLvimZzDC0E7eG%1V(d;_Y(cLU%4a?}c!KD)2FZ{Rtk0y$dfMPV5u#e?pzipXK2~<;P}Ov;_HY^4vy7HLidE0yR>XRhIsaM z0+QRZQQV1&?~zax!ygZ+j6WS0L19;H@)g#lpM7v={(4FBfrPmqQ(ZYXf$nA(ZJdSO z4xr3=33*@OdaDQ4;u}UY;vYyn)&ZDeKQ1`MLtcDQy@PQCrD~#jQ?ZXjACqUR$<-NB zO~%7i)x*uv0MG0)il4$%wTt}8{w`-v*#f{fV*l2xd zEwtUPg?yB(g?zHEh3>cR=UcD0iQxaJf(JbX@q4dq6y1FF)8OW77!{6j7AIW4AK9CP z2m3Gjp#}bi7%|<&Y>u&)KBnN(B^Ggl|%eTeJRX%7ycE)u3@ z79XmFjA!a6)`qD*9CQ@r;OnprBLYTANGT>&PDdM=FQ{Y0*5c^3c+yLV&q`>fBotp% z3BA!DrucP-zD8AkpFHtXhkmotKTi%OJ^_XTA5g|YTC|Yr&xF#z?g$2Es#WdNRkhLs z!KaC8r5{ucs#<|nG(k*tC!vg2)z?_nK3!ESeXvRr)k;5G>8e_RLzEFyeUngLkRkhM<3SJ$q^xu8e3aqOM zVyb%!WtysR zt@Lp!Nph|9LZz!}1zxF)Sgs!s%EuC#8CJDVSJg`2u98Hx(w|Ves#f6Z%8041Vs{vW z_7a+Ft!kgHs+FE8cy+ka>nUATD==FbG1WtavP432omK7ARkhNuQAv_(rH@j&s#ai` zGGeM}Q*Q)mEs#@u%3tk zDOU<*jfCcUtJDfwG)e3B{jF{@NLb+K&v%sqM>8e`k z*Qq4QwbHLvx~f*-TxG;mKO>Zb5}JipwNF>oN`Fr!iE5?4qI6ZQz>ky>Q=M%0RD-i6 zG>fcipRTHvewyIb;Yz37V)~@1Y6YIIjF{?iLb+Q)v)HQk>8e`kvJD)lYNbz84XRp! zimyoO8-nHiNlrtw$fF#0uLx7raF_hVDUL$LbKGW_UWox>74|x zxmJ1$rK@TMc2`DB^)*6SFQHjxRr_>Rt@N8zlH^+Hvz4x@6?m&MVyfQ~imryta;w^> zt7@fxuaZQy(mz(Zs#f4n${^J^dreEn2eEY2C1bnT(($}cJy^!K>&(i8WvlS)3|8E^)rfan0zL0qbXO~^MR6D1+?CLm4jHEW zOn2mmGJ#2;SD=nZyZz;dh9pemet)Oxebhj&LXIRh!zM#Xd zpzC9THjtpzuAufOhb*d(Xvm_)WsXHZ#suvnLHD?V?g|Sk^#!eU1ziNL&01aDr8W1u zf@(AkS@dOC5H=?rgI**##Ra$l`ajxc#3$44>IG&^Lh;;6=v1fva_BV#Pc7+qtc+F8 z5s}AT*Vjm(z$8t;b!yTwR1>WpS+JZwreH8X1hhUO0lQi)K($rnA*m{dOA9lwVL19| z8D0bfs7IZ{ty=a+^_o+n7L)gBFpj zuH?&&2^RfZ3_bcmq}d_zcT1SIy+OCnAo&TBoD+r2;vu)4*FF<@QvmQ zfHza^ktBP{ArCnBqyx78u!{*}3+bTgkXB^z(|j0Z1(3P))RB2Aff`-@2^qlRvkm(; z^sxuBpJVVd0Oz;MV0sLY+nuC6pFq#G=k}uOtqJs)PX2HY$R{h6I9r(Jr360M>C>@y z$0sQ#2u|_dUfnsT#P{mx)q0=8LfxyQcop#7y}G7|?kGHmR(k}-8#yrtD}Av zA&U1L^^WJLE66c&Gn5>)#B@iI z@H}N$M@^7u$WcmME===Z>nNYDjw%tH;yp(VZ5FOkM?6QJ2)@iI@NH#SM;(@E$Wcm6m;Gw9!#c{RtD}w)oZ>x4 zeeXGHHaW(rQTKU{dQBYFR>V%1kR7GOE7i80)=@rP9i{Zaf>%c=y{FREQ3@QQ4C|amx;iRNaEkXFRTc9> zz41bQ(jA_op7$K}nK-Calmh=yhILei=nFYYiMeXbUh62Iu8ulYaEkXFbrPn9ZjE}} zbJTmDqy7*_T_R%FO2{=ziMOe3?^{Rtbaj-{X9!*$rS!2%S4Syuwlb`v)=Mmos zUPtiiD5W0}CAp9QA|e zsN;brM@{o>qY0-HpHkaCv5xZT>L{h(DR_01(&sB(Ym@@-Q3gATEs~$Yj2hH22!9@} zEb%ECvlPz+RL82|n}k7~@rFAEd@jJ$bMxi`a-!fzN|@TOcz2UHxtoy5PLiVV7D|Vm zLEf*8O`rmhlI%Pt{<=*D+bS8NJTd~f=iXB?lIpc{2GHTzg0|qo{34(kvS?k*ph<&J&33gXd=MP%Y(rh| z{>AIvVY#~AH4)t!xr(1Esutl_IONi)U2}Ydp0}_ozy=Xo0T$9Jy9>Kvt=$zDCNXmG zM|UB7QZF~w9kDCuk=?X))%nri^I^`dpy-v~fLQq$prp=(O== zz}eHr=>ll3z?Va(jqeB0J#G90DWK!Pny!(i3!gUL0i1grn9b$V8&7$z60v8%ZRtgp z94>`hy5dmWL~=_fk=ac`Q!~PQ2#2J9+5}6)RLP*y2kCG*UuX+~sH2LwjNtD}>(hOCLa8iyNLT7FWQ9 zE&i<%i@D`rC30s;Xc|Ob4Vlsf8iL|_)A3#dfvk-~3+Uu}YTLc&Hhw!7U08R(7I?7K zwp@U@tKp1d2(ymsm%`1&p25#gnToxo|AKinAAKLh%oKj6c(I6EE@4_hsOGOlBDdz( z>jP`4=2u7;uKBab67QV-b+G;(&-%0rQrzSD|MQa37J6Y<>`oPK!Qn~!SXZM6y$qxc z3>mVIwt-HK&?^SMKs=Y^cr%8@4mmZzF{lZ=8 zaN990fj=WM9?*&BAkJ>A??wY8_z z*14s*HK-_iMd+PKTywt>#VMWGXE5-hUNv?n-h6 z;_d=zGsT?+(npAsedA$YZg#IlNw_x%hPKu@<|vtCt|%RH zH+6a?+(|uwL1oBe6ravx!|~`*hHRnuBIbXNMq#I(SM$^}xBN>~jca&*S{NkBG;~!R z5XVF&A9X8jdK)*^4Y5%FU^|&zHf4A+w*j@Za07(%WNw;duuMWTHgX|%s{r8oqma_u zpk}Z$+Z~2DPi(3*x9+JeA$p>eKV1Vq2h#RL3aJ-|x;;^|w!qP&gcWe%o~Rmdeow?5 zYq>Q%oagP7=ejtoIGQG~X`(t^LUToATgckJ5FW4_0-PuX`|}X{8L(Y9OhEiXy1UgM zXk`7kzuc^+wu7)Dx~o-g*=}}cfmuY^-9Wr>7W;u$X%_ccqrzFF&Zm%`2SK@{9^A-|T znxArDVN^Ijyyj?$^L<=oZ`zHiV2^}md}L|>htrG2`2OT&P;4uGfHYu-rSY_CF*rO~ zZ;6&opIiyeq)I019fV0+LG(dRzYVFJODg$xr9xDm=ad})a-FV#3p?n3;3{=c5oKwT zmnE7v@l^gEG4L_X4LTF!`i5SyZm04Jc_$8art&wUyW*+*)52DmJC#2kODJn(B~$t7 zU{;*UKPTc|kkFgTUx-BRRQ?6Tc`9EaU3e;gI$2W5RGx-k`l$8ZRDPA0ECo=mV~T%Y z(xW5(Fv0cX7f5Mum+uqES8-^yhzqR_SGpZ?1e+hnW3bpxo&U9wq5^t4;_&oKd4_vK zWHaW`ktMsP+ZjN)-IKVQ27~!L7;vpUB+62AD0kqMS5j+h3$wn2sET)oENc$SY^_y@ z%JXXNL;$(gR=|a8Z9mGYHzyq3YO)F1iV3`rMD|`AX_1KkpWxT3(wPGCz~uAck<9n_ zt&UU1RFW$5z2g5f(V#U>qOPJc^F7#3Z)-BXT=SS*PacjYM81LO$V0f@>-jYfWD@6(6_nx6-?P#vd z9g9NR$DwX-TLK^#Q3YJMhz0{!p@<$Dh^-uvJ4`}zLu40Bx$If+;GSL6habSzrO3vV zpDTf9?){U{iKxvMor9~HK<9PDg$h4MglFy@em=-+z^D9C@u=R>s((SKc(&W(@lk0X zUUiJrBPpKk(;=~NA6gi<aN&61?ORt?a*N}anJkhtYc=i4 zi2E{=SIK%_6?a8yb6X^+>I&Wp!Mv7e&18N+9k-+_!5K;Oq=DQC5YW;oirL9g&qRZ39L?B|HBj4ji|jmK$^8O zah+Rs=_Io2VdgPoXesRa+vJgNv6W?iIKH4}_D2XT{y9K@a63o*C$ z%lN$5rV5YGt1y@qme-cq%aEov@5K_D`)wl&0KoMmD2%JQ8*1Fy*eJxgoqZ&!KbH{g zY<(!@H$d8UrjP@1sN2q3p%A&9RltSYSsmc~cE*#^uGa8yo}ZvR*R3ON*+-BELSsB$ zZiuYVK0TdhqEE4e=Ap=x>aG*cr)tK#bqbjkhdM+2BGe`x;ztQvVeSw=IhKt|hWLG8 zRvhBTins|9dPDp(NaPOj*)W5L_zLO5L;Omzq>>?ihG#v7_~A>jix+|1VRzsnHmGa< zu9p;ML*$VfT3^qmw#9qb3x$1C9QGby@me+pP`5Ip_VY3c#b+L=WE_4)1nrU#mG6|A zuE0k~H+S+1c{>huE8k%Nx$;%Og)84~vaqsoc(urVPC~TtjWFf1t{6CJ3@p8JAg%%) zeSK`^d;17FEe2goP#$v?`k;uVF_$~W@#K?@kA%Y8P~Mk7mj;k7CmnWqY| ziXhKLl54w}uhlu+MQwpZUSRD58a3mr5PBfcc7atFQo(j>!}DPBg0U;{!Zlz%czzAw znd3Zon?C=M5C+C;_OF!6S=1+R=Xt9@@0Ji|d>yhftqTNl{Z)uc_be^~kn3*+T-f?f z!1>nOty1I^7Kb}edrJzs=eLTb~M{^SUBGcA0M3 zuGc>UlfAx$cwxJ51<$vey`I_z67gv(AqW^gB>k3in zp4V>zkiA|37q)&9+2QpX>~-owVR6{&yo@eNMbrD5CJS%K!ewo#y~FV;H!u5o=Kpfj zvy+II?IeP4xW3{nZg%j5!tQ$Q22B7fq6ON zjCP-#C8J$L*a~w;yANU>sARP3*}byS?idkQLqcz~YlKAZXg42m9_=cm3y*exktLOk zc4?mV-hy@n#JkC8?Bfckx$Q0K%_~j?e2`LAX!e~1dY0yFdxKBvxvqZ$$!rBwh)VY= zV1ph~0W09b74Rpr!>fR7{cthiTDAUl$NCPC?phz=PHVD2OXJqxd8}*wB}itiSBOgY ztY59xSHOj>FDE-Z>v>d}CnhXZ>vu#>InFg@8<}E<3~FgRB4>x#2S~6}Ja*~$oJiXi z&tQ2d*=eZpHiHUzH4b%qv?%~`|4;!J&fq}cD$U@VB6p93W@n`4@oolhB~y5E^}ay% z$D!>)&}T`Bli5T&x!OgJd9#wqRkR&M|L-&&>Gr_T5gwY1on9Wc(@WmCOG+fC*BOZJo?aeh>L$_&fXNiEN4LCwWo)ei znBJJ;zj53iJo?3sgZ$`8)kL}{n43eG;}hvXQsIV^#IfbLFkgfm8(FdfWm4F`F|8l@ zCqr7=d`xlZvq(boO=MLA*XQ|t!!1pe>?0-LcuMSzq6|Q2V%r}V=3A!=zS& zP>)Zot{l+xwNZ*|!2?KUo2EkQ#-VQ0{1HHIniX*2rnwV1ziD!nEYDzz!!sDZ6I7Hb znF?@WzH>5FAHH{cB0CwLB^EA-Tl#A#Q|BO=&6Glx#G!7cmH^0^s(=e;>I&d0%~VTk zaX3@F1gYCdGPQvq|8p|+7zuN_S36i9(+xJ`Q%6FS)N843NqvoEHd6{YHV$<&)e_qj zoT&=9aHeVlS81m9S&PG&;u-!H%~TOC%=b>F@=2JJsYIRu%n=J0#Vx%n&CS&HNMlJ8*zN-D6F2F;hOS>nq^G)_?hT)(;jFu2$<0JJz>=bhj4UPIQz&C&sP6{6yFK{zzthuMm~) zS$~sSUjY}keiGSHneS(a33sUVzd6=F=~-{v;8KCEj9cF%-L?LMnDq)#>7MnC^2PTR zaAE8Js>J&Ib)vpy530u4QGdcC*mI|U@;J;bOaWU2X#R|R6f(Rg>~Tx03dHh?^>oqE zOF~mMG36vT%OjA|?$0V@LLBO>SPz^pE7pF(R+zhDolju0TR> z#rg&kxhvKVFoRdD71D)QtPheUm8@8Yi<(iYE_|A@0mQq>Vk_1;g1<*X%!cAE{Sr#$ z^!RodTOrU@s%m?KWf`vP%aP2s6@{pDueNQYOw(D63b=4>TTOO&ZH3RcJuW7Et=17zs}0@2Q&PfCoP$81TRe`cZ`8tnX8j_MbkfeC-hCSYeL@(o-5zYMZJULK<% z*O|XBM3m?6S79PgpHc~VOLyw#{SbCaqA_|R?sqx3rEfDhB{BXsgXW3LR?+`S6$RI9 zLAtjoZOcTXNow_G1=teq_iGOBb)AyP@wX*31vfU58qf~&YP0Vmthwm!96v%dh=%~mmz6v4F0CHmC$rXWVA0-F*eI(Ub3HcF^0Uj}RLf%>kP;!xK z8d&^wCFHbY8w{@t!!Cy6;SF(7Mz#k0l!zu(b*TkhNSyb($xzC>f<}s-G}lwR5zL?)a>>))XC z?aM*vNSl9Y-S`hcIy&+@I#P2}2-73E**&PM*`)2PW&pKn*~^4jnDoC@I%a* za{y#P&$FOSWN0T5bS*RvP(CXP%7`}3qtUu%fznt`P|^_7yrXcc37gCR>f4FkaftpR zxbtkR<c^)pa z-Pgcf7Qsn1gBKG8GYmyk?s+|9(@COKg zz}e_z%tZR<2%K)|TtKm_=(&LWnu?GxKiwk~3?uMV%H$&uoi`3fD5kAo&D1g1fxHO( zATJ+R%IKkhYxr+aGoKL)fCDlUMr#g6E3#}@Tadx6f7@8iee`b|Vp=)~s!(``YSf{T$NUO??Jj`w9J zd_-EC7vld>=aEl7qB0-AMRzMzYIwG=C>tG4OZ;@^hf40`P2~Xbyd#TDFjeMI%XKbw z5C8FrPuAC!^WO&N7U92w4Wz!_p)f891=aUf@pGR zVG$0m7jA*g1vgSQAEcMFZw0jAE{Z-xo;&qYKo$d%pWecHt+j-C<@u-|5@{@!c)ny!~B2yYD}0_U#rDZ4@b zKmkvda0-=@5-${@d1fFAc*H!gOdp70&yH2kCQzlo(<=Gb30#YUOI(R_Rn}Hcy;xIM z3-T7{;Yn;St$AS(bpne$a^_=DR!+*c3FiX|S(y@d3emjG%J!%-)W|}5KT`fz0yySW zTS+;!62H^buW{<%Gfm2P%`C|yU8X>S3y=`5q<`6AH4rAI6AWAiL$~B z(DLYSh<_JZ4RfT+|BRp63nZ#!@7cH4p@g5=tM1{vXWtG2=RW&(+%Pm{=M7cuDDJGq z1|v>BSQSOxc$n(O7c@+=rL9HP`D*DGY-xLs>{(g@iEL>%59e8WCvdK%TgfuV($6XG zSX%8eYiWO2%I1v|`3uy%FWI~+J+fzBGl*gHuJLf5d3}L%&6|L@Yu<8-JLYXdoE&+O z##?Gxw~PEWYTf~^Eqj6EmUXPn#kQ7-obXEt&DWfZ|9WIE7ZD8koQt!8aoMm{!(8^L1V!$cH>~=Hon`{_c}E@_71)2&9@{Lj*Nb zf!}aelRUDQ)psC)vzp@JysRDp&dutHqrzG3N^vKvLlM`kszqI6mJOn;ww9=pGap9* z2T}ZNX^Nk6`st5}e*vEa_=9$1=Z-}?dV$)}QJQ`gebmC$K;?RhSkzZ7JIa=w=8-+iYF#0gb@XtaWjVmPmgOPtT6Pu19m`fA zPL>s+4PGXq$E#(3aiv^O#`BZNR|;c=0`T4n`cL>0kM7yN89Lajvpk$<`$xdJwwrNb z+p{R{*xn0qd?r>$RS?;!xcsMUVr+78}JjC7njHkGhpJj;SQ`jG^o&B95&Ob{+Q_cFjiAVSBD@225f1m2% zJo~N%&h_`bh`aV}r?_L^H;ChtpD$u>k+7HsAthcQL{r0X=Tc`vY|X-Xx>)$-imPe! zG|Z!Wd1?hQoTsrK&dbyJz`1#vjJTVpl@xdK^bF$o6yJ=FQcco)nVM$Mv!LG~DwUr3 zB%JV&5OqDxnR`@-??`BB+sr-T(Y?&=gAts$=RKU4xyZzD=CToYGj}${oy?6v9H0Cz zL~NTj(wM2hl=zL>nq&)X5fbsVp^mMD-wXdZNo?xcJpJm?y*xbvF`TDB(rJ1xPrHG0 z3+yoBZk|q<6wXs;#5q%%nNR_=7iAZ#vBz3tJ9%`^*h?Xljm`CNp0P85bB$d?#yLII zs}y$%;5)?eDcpx~dC2QDR-a&K?B077?pf@k`0<7&!S)|&>l>QG7tughP6PSz*7j?} zrj-(Uw%5Hi5ZBph;p{F-TK7pv#hFn}t%f@%xM zWZ2677bJ0IPYQ}@J5u>+ipw+wxu;?$Z7Ydu1abEGYg^%WQe0!Z$1SH?SCsMbS09!3 z;jXT7$36yxK-vQAErK)`xbf-i0gfQWL4F{6cTFVZtSPaIZtOL+Sv!B4WUV%(EzHnC zMKw%O)0^9}^yyw%7HBmqmUNolE6W?aYBnFHyJh(x#htQzgR_Qzj}x()ogsfvF}CDl z>@XQ=j%kJXX&hfo@j4W5$MF?Y(1hw!yn~^wLiURaT&(##)%xWpDC8oK*dkZ{3dOZ_ zi@X6;1;w-*to&7qJ56v~sA`lmj^^OX-=MhG=1Q7|SFug$F(JRJ>^9c@PkVIF{o5d) zo6<`j&U60(;M}HE3$Ah9pF?rS{dtIM4u2HUf2wKi+#Fs-$YRQ&@@uw}^}*>jhlw_a zNkVR|?DjT?4LrJ+!_AP-In3~IUJgG3&ds5j8qQ%B#ho1XLYyq8Zgqf&zDiB&U`-qB z(LK{fK?Ivt?BP7q769j(wt-A>hKIK(?wIxq;`rpx5V4<0SbW8KCQ#zDLNpyse8cw4 zYjC!wtP)h(%9J)ev2k=GcqSF7F?ZtXT3qnH?Mx9iU&6GzL$8J`1kUc;E)l?u3S1p} zLEgOpy8E`@kOF!^UWIhwecSE8Rou7LENcFTWKdh~#BIA3x-o8l3VKy60^fGc-2UnS zW^1SN_b9Hj)=mIu8&{O5L)v?Kx&n{R@o$lehI<^uxw~jr7xLe2eQQWCxkrFaB$iG;`4wsPoNS|nW**-EG ziMWsa%OI&H31xGX$XO_%IooD)oJaSvc{U_-Hm7(vFPme4bF;Y!aW|WfP~6GpZp0~@ zcZt}Ttu*@kM01Y0*3hjQa|!1XcbnwHy9{T^vaVQHg@<@mc(zCOayA>gJe;$B9?r|z zeZaXndyRIBoKAvXYUk$c*wJiT{uLtjVF`KbPl=O+Xny8JS6igvoK>~!+{waTp|D@< z-h)T>a&!TtaE@kqI4?)jfOB(n2jXsyo~O7|R-YlxANKYQvYoeHLh~Klw!|ZQwzV1| zwypGVo^9s?=h`+Iao4t$6nAWU2624ypAoTJC1h{=MDsm+dmqxUx9f4*!h_hi%TJMn zLp0=_y8@p6uf80{Q^i!!i2^eC+it3t7XiQ$F=;45yru9vDsHgd%qRuUc52G$rHBi? zPK^fc3x%mRnTzaJ;dY4Ot-^0eUXVXgaC0SOTa`FXH56J~>uByHocny;g|4NEf4&*7 zWs$Av-*k(5s3|^XMV$VL(9<4}`;CvL?70>DnZuF2nXr7F@E=y(W1(^DD7L!oxV2dT z&na+YXx!=nf$q5VBPpP9t3tZ)xHTL&f7~jj@mCGkjA8uc5%+o$+ys^@;Bz%7Jdi%% z8B`x7zy?)F7dB{TB?blg3F7mZ@2QgcM01%fxb{%Rm8=FAocxq_#z7W)kbrLu2PHRl z4+5S}RJ&*xPUf77vs-tj@JRy(@B?RQcct8niFZ&s6GG)U=4r{B);Y zQXIFiS+YG7dJ3n`T}VosC%=z61>tL9QFay-@qwLxV^C>T&KKQbOiPt~z43rL%AUBO z+i;mr()qkjllZa;E`yRyfNk%KvBp1~@dTg3DY;~Q5PaqF>F8#WvNXzg4X^zk_KaSI&==tvLBw^BE?VqEf8f5VVtcabyM%BnpAo_a_9PsbGFI4J{i2B z{lorb{`y<6NfY$D0Ow}X+b7~O2;P#=6f8%I__>+VQa#x8Aqjm9Q9js|BlvEbZkDr= z@D5PH6nY7(vd>c3oI@&}^E8I$Ci#Pe`-p`0Ak;kCN?JrmW$Ly-Y4hQo8)z{)me#Ag znj_;kI8)^BNL1d|0VcRY#LQBq3;6H*GM^%W+wE+KZ)mH&O$uBRnkn<)CFQ-Sn5E9f zMI9DadeAEb`m;c*jVj1uR1iI$Yb(fwhHhyEWjBH~6%`=+!zIpfzujC@_&Drrv;95= z-u`cZw?okLTBY{7RgMLfo4Ng^O7Wpvn3ua$t5k+msXktAxXL`nRjOZ&^+E8i%t5v4 zn1YvaD1@sF_Y`Yz6p_!uWp1X;zYh@|yK5nK4p3s5o9!Fy&`}waA5U|URx^9J?6_F; zf!ENnwnKCfi7-+KbtKGu2Hi$W*xLsKL4{_(XP$zRKhUj=s*KOFF#sS>d|bxq!T9*u z^HkY7arU2YL!I4q=2Q4K^?x`+`-eRjsq=94i7AMklflpAm8k0K9af?qtM5?I>oJS~xVV%qmf~V2F7PQ`ixEVQ zm|LN?wvD&lQR!!KcKC=n^(1=4oUfe;V^CHT8EA$q$2vK7)3;QDdc>T&A_n&R7r+_j zG4yMbfDF)%ZK?5oq4the+)XfdIY4oBK^f5=_GnchY=_cVPEgtdMOvXc@Ug|9qy)UF zF~wYCJM$hWFSLV_$H2d(GCuE-;^=NFy3KE)kl*vi*6|V0PKRhz+)KxJJMnuN_tH_; zPK7x{<;(bs3`EKa-{Y+Vc&nc^_5Y8Q^{Cr@Af-=CiXE)uZ#4)SZ1@R(U5Z1xT?b*Z zc5;odqu6SXe?Bd}L^>COUU1~G04rwh`D zf%7nNZY9;keaTjyd0_lXj632<*!UnyH8J`sU@iEHUQgR^KYq5KY^PRbdiJ~Edw}ei zM|Cip?} z<)7sdoMYnMA$QRKt~P;UdJEP}9kc^vjb5l^+FQkW?~6>JR*qLz*|1cQ@hLYG;R5b6 z$B_$Wn#^0MY=V*zaAFcbwku?&9eHPQ6YbXk{I_M)AJWY_7SDemMckov%R^_ppFs5Q z&v@@^L3h~jf!>2wC|$J*(4|bxDGbA z84~7=1FWz%4DW`# zAc9_%&^vwImW<}jhh3g#@AUOF0Nve?=SczWhG@FCRY7?3;SS*Z-4Gm7Lw*Z0=x0}3 z{FKwrmNxhqPd^#>u{DWLsuu2QjhaOFWF8Zr?v~KlQ>ssTWN-hk`W%=_+vQt5oVWki z95{FXuOH&>{@+B3JJY!v5vRf%5A*y}s$Yw$njNKi*;A_Ddt}ejCm@k6J?!B;OWz01 zwe(N2%-I*toEx_EEX2vuy6VWrVpcab&z@3k>XAM3E{7O4?^F-xnKutO*Sz&)j$_^~ ziaU-xggBWO=UQAly;XISh1m|gIQ!?@qiSAIcJvh3_BYOrPGhYmT*28%QM}cz|Wm)tY^UeC|l5qHi0hT@Ldb*!KB%S7z; z5)L8{&-94qAWpGsKB8yZmepNCWAD89WG^4BppUC?j+fla$K}Ae?tj;F|L>mr({Et+ z7Zzz1Zix$HZ=GByswPP2nbZwQ*`!N7oM+N7;9QdqA?~_1c|q8lAk^JBT=0Mw67rVo_7I>@S|MR3QkT zb!Z`sa}^*5j!*OGp6$mi7TeG8aGve$fOBmhjJRui3B?`T??fD*iKVEyYEu8WY5976 zlh8O110^z5fpXyZ5|8fXVJmcT%^2?CygYmkoSTPgOTu|*MsX((eG$hee~E~V*-8cC z6Y0P)O(DD3LMzTk##c$g`y`~Z`V*-sv*5xlt)%Rfzg=;1@Ykn%`L2nY%lUpp(rJ1x z-`#+7^Szw%=``O>6nFBym(9Z*t|gY<)QKO=K_iueyPu1$za;c*I*PPx)3+YZvngX~ z*rtaNcWru;;*L!}BTk>f@>b%slRDcr+F3$9eCyLa1A9Oa8`#uK?-@81IM-<@%fbeB zq_|_?5X9L&by|O1=;7ImMAtPEdN$2KTDEDJhx2T@2RPTJ*2}{-6;RxGw@SuU?Kf$g?nIjC+;f!p9f|)kaOk0 z?CWCFw-S1`SGiG~yT`+Mwl@XNb?zp_-5R-<;*N8VB90GtTvfZ+y4XxYJusW((LK{L zkWDW46c6W_)&n@#wBd-mrd>~Q$Fv6!$0vV)h@CBA{y>kA>l~h)NP8^`xKMy5(@Z=M zy;`xvCn>#=;rGI7e45hTgRu!qdh@whAC>SEJo?vB0stg>|)>-Xr2(P_c4o)u(&@ zJO@R>{#@^+_xw2nIM<&)dH!sG89%k$tcw!Dpp^DMs#IM?zOCI>>V@aUdt<`yySDi7zGmIa(^S}(+1(?(I;F>L|j_~hRt zVzplJflwtrr?$EWLf=A4J`n1oa3H1UICr;c1L>T8Dh@K(GaIQZkrz5+bBoAbC82jV z^cS*?ca{DlfOQHCA89!g0^MDu?WBNql`5nQ?fDqwMlmWWcglCdqVhGI_0)=VMxR9od3XSPT8 zY+VVNY-^5(^K5+vIJW`pBio#|8M!TNYc}HHPrhz==q5n^XR?EkB8w~gj}Z1`T`_I1 z|0;k#Bs6*!&Tf_4J}XI5s}wp5N9DTF?zzBUyQLVkjEm_Yn@==D%|trL=F@SIjq;J- zMK=BBNa(yI;WO-_Ixk7!n+9hI?0gB$+xZvE;RG#X0*lnlAL&@K&MHlZ#-b=cYuy1RDZzrEeGOV=+>n`b(vrd`VEftiRN`O zQ`?>TZ%_+NE_|YS0Z5&*=#W2%rXdSuP*b9L7D90s}K!?s63(6nTWX=-L*BcU zLFdJx^DML}q(-g^Tgj&_Zs1##{f-uxKwERo?y^Hs&;}{u_k7Mqi?T0X;`2#mi1JOe za%s3Twc*d=^GF(87{FTD}QbOlE(n|mojz1k$JANK%9Ni}C3Yxhg z?-*R(FUek1C35~~G2KA@69NWIrlSIj@5e2$$dV2A4AG5nhFe^GhKN&ij-!K;yWrl_ zp~Ho;&*retN*;okL6z~B@ZHLi?%+?ZjK6?y7?*5@{F^J|&*l5t<)(vw1MgBX$}Y}M+)-eH*M15D{u3^~n|LMN zO|&O4-ix2W;D5%nCot@vWZI-hkd*(F>;GHQL2ymepM&6W&z@PPE2yRTX6>v#1$LP1 z)dlwOW%kx=G!Jk(oroDp)=r8B3AYfme&%WfCMy~PSEX0WZYEwd$SnAkn73sdhB7*| z(fCC$`eI)q>vpTdr2kJTcL=36-!td?rRgX9BJewvdEGs@p>CPImAOipt4nZyHvKB4 z->vkiNED<$t@PDOU(fg`jAWbsqjWmnYL&#Y6=e3U0jD6NH(_+7BO6ukyCa^_vuhHw zSH>ss9Az{;69g98`$u-Bsm(PrmKp~S@DF1oug6s)ZwD^aac?oRIHT26k#`>mEN^Ic zkZ|{2C__IPRAA1_GQd0 z%UCLs8;=BmC6})T36f*!g3QlPAW35~PMaoXl!3tDE2@A*W^lh!wFhFXVQl&%3K^#m zK6sM7@=EpXa3IJ&rBr=?O3XeS;b~}s?)YY%NMy1{ah>P|ds!#mI0@O!+<}+ElaTju z+k`VoZ$#8gcEGF4P1e+m$uNs+zOrP3hKHl^V=8eF0g4Z`R57 zor@->(%N&fwPzCEc}}jn1Wk)o)&s%1swGG$NcwV#X~P+JX;a7Lop zN~yXM_ckP#v&{me--B;fBO;Tl6lYCq#HIx~YoW45l_VU6egs!l=MKh+E42Ma=a#mo zHp(Y88uN?p_&|5#=eVCK{SpTg?W-f{a5VR}p?6vG>lVvR%IMHB=hCLM*_C}wGn&UBVNwJi-eo!hp;WjlJkX;51A3?zsjjvru;@8@E)H68g~^*0ip@wR)|4k%;;4{yo2B?ocdZJfU+; zz2ER|9ef-8hT=BaE5=Kn$;*w7n6YpuKU&b}ce899Ik&ikd_%ZcAx0^G_FcxW^6Ax% z9Z(u+ubMZYF373#ADW|fL^_K(Gl5RH+QXt}CiI5!xx9XRlwZdilspYRHOn;jms#ii zaZM0p#E7ghC^>c-{t+-nEMjE2>5ufW)2VvGnqN>_HW93|kANMr|1-8r!J36oF z56YU20^oO~&+X}yKZ!GhET1nn4wPHdpjtW~f2oiv9!ULg9*D8?t{wO6$7;)}foqgP{7gN@R^e z$?G7d$B4ZcImaX#ynPg3$&$`8J4)M~?PTc=%t?aMFD{`h5iXXc_J5ZpUXzuZ=a8hb zW?Q8~ZeE6ptuY%r+1!+090c#gh^#Cqxe3H?W5m{sEW7{4AUJ}|aG@QJ)6Pl=)2@O+ z3zcTA=LUC10-1!>z;4`Bc@luW*QpavWoedEC4$GrD{y{5M=}7MYhxVSr-@|SC-j2g zQh?aPP1Zu9y%na-Fn{4TP}4-50g6epXv>)n&es(<51`h(2~Ofnwc1uTv4AR1P<99- z&aW0}BNtjdCe+OR(_``s| z$na3l5|U19S(r}n{eU0(H}G;(2R#*AYI~EiR>*n%I#kqHS5;d7>8ZScalQW;S8hHA zoE6x|_hy??r1}KktlhGji!I@@DGOAL*|fBq28>Hf_hfLI3z5hgtP>$RKdHL=LBVhTl&wq za?=}fSV1x?C^tD_!ff**#2m#p>lIl9vu*PcDHa6y!D=^wQbJ|Wc z%WVAT&~>n?v?gYPmHz+6aTvsd(rBC=emIJ!t2d*x({4@XYvU& zcG6vzi)5cddw6zm0(X8gGv@J?fmM(D7r>zfc&|EuT%;K+NP1B#=nZ7Duku+@P)4*d z9_?{7p?OMUIaoyB2f{b_X6=@(rkJm?N6tsnq;^VcIj5a6-L_L+1?!u% zC1w|_Z!%)Gsee4SPw}lpjc(;-&qaUksA0NQLmb#z4gp*LL5OFoBZMs}TZl&VDP)AF z{cdZfd3(UPl=}aSJ9HzQ4;&Yc%(jTO!lRuC+NVmh^QbbSoti9Zg|;5{T?1P7?`Qo@ zXYfl8vX5{N{xh!J42K*x&Muy3nNN}GGHhC9eP=hUV*68_=>Ju+zN77{PIOZv>worf z>)u#y--84!rHSpch_)?Et6EeX1QW15)~F}6q7PwtjW3AFYdo0bb?Qz1`GveS)?qc^ z?@*E|JZz$+>eiV4Zw5cmd%bxL**yfHx8!%rjW#mS+Y>T76+3VX{~6t3Fo67j9C&1A zBy|Jw!V^nqer5ETed;61k>E<8~XQGw_0d#cW<>h9{kw}eSNJeQU83s4|$WYWcFv9@r2(1^*xRl-@ElJANuA1mKH zR9>_YGw)A-6fi~9@855#gMrHqLP0|Fo}hcxvP)PuS= z&<^#J1G@Dt%j|z}#%ss_GV8RH&bWE^<(Yn9w<$btPnx|)6~+RdQL$_I5!&3;p1DkI zC0?Gn3pKXy*=>(BicpWvA@-7!H+Vb+fuSbL286OurS< zw0rbHCg@f2CVIHD7yel&2BcH3u z_=}bC=OA_=NsUGue@V^tx1#|K-#cAgrhXVo@2xIYA!+!n2JpgLmHM}>V)j4iSuSen zOo+s77SPsfXzSyO%sa47xp$?taAm;4PHo|)eXtjE*95pXv|~4is*abuI)oAKh3dGo zPC$wGn26m0ew*^U@>b>P8?WaF$;uU*&=m6HvUvJiU_>8Z)vq5$i3c3{jga{L5JzyJ z-?|gI3t9evx}Ieq{|6B2$LxeZ$ovEGV|MBX<~B3oMiHE%o^vbn-XUrFDMA5VBhvJ9 zbDk>ZBoy;~{G5D&d0yUiL$H_=vF_LCc|h;RD3QvX{xP7{CmK|)_^ql)bsWG`){e&q?@0B@GtTIgiqDbpiF(4W(gB+RgLYKgZ4-Iwi*@O zn*Rb^20!gL;oi&=Ojm%_-DPWL5St8M9d(+z&%=_bDzy<~?{vDYBlh%1i9xBWGF$QQ zUG&><%1hr>;ph@Y-45z+O<6Q&)5DnTj7DWD^n7aD^6i5&seFn*HJN{TW+|9g;s1$m zv)yVQMhheU?1Y+q4G&PEbO#N85kj-SXxZVV16d(ogiz_wqUTwN-HOb^bH9^RF?i{q zi$TE0(*QpR;O_ub{!og%O+?Gqg=xFPZ$}DE`OQ1}MBHD5|LMoeAcDCOO-a>r9BMO6 zMzA^om1%gkp7g#>-Y4OO>H*6Kef5B)`Onb$4r#tK+&b>ktz-DbxK{YK+T6M5I`Dq} zNof#)R{D1};TT?yn6DcP$NT#b?+>~W0yf@%*@^f1vti!w`f$$PMZfwIruQVR%EiOs zJwSCDV!(!f=+=MOWPExJ|4;Z#rtsN7>;Ejbej;9)89N2R6aPuhQ!~Hz~Asy zWOrNxSF5Ap?^t%Yfzx9NY2YdyYT&OxtP4esEWUybTtC+!;D^%y*8%ud09EyzL5jRh zM0++u`!ihkSD~o~Dc;fhAC>V=#s6r@x(1BDW${5|H1P9oM+2wFKvWlQ11D6dfnS~Z zKGbG17jyMIVrq2RsrTYc58r-G$ll6-zZ9pNqU6Dvl`q854_sR_@J2kHs&4$TQ}Kbo z%)G9X*HL_2Y=!k3!>-hwgei zlG~8nZRM`_B6$mvnR&UdBdH_+e)DE59TmB59(tb|66$XM3R3ORRktTPUfq->881gG zHYHT!)loV}b4o=BGC?;$?9U&Ffp#hp>S|`$w_qQu?zW5Z4?UKu+x7GK=lomn&;E2v&t&U9d=dUJAE~H2X(LRepE#`h8m4n~ z<1pK-qet>}xqI->Rj0rV`tsTIJINLrOLIpa!ImHD)%`afdejlMj;4=w^t+VmLuqyD zlWBC?rH=Lk>kc6XZOzru#7#YOtfSspchkr54?U$&j|b}1LyOx9d^y?h8%oi>SRJjY z>S!Ha_a|b!=WhH%pWCS0^IW9%MXRo(;jE4Vc-_f#dldOYb&AYhnZtJ=PvKx z{g<0|+Y8SHYUX78-H#q~%ozOoW`pPN-ZGYM=I(aI2X^JmVm&a%mg-Prgw)Kgo;U6w_)&X)yzx9No?yUiF}8`VfdQ?D1@aP; z4!6Qu^%2um{bOcQ1IN!rF(%DHLbr#yJycarri+jEHDzCQf7D?>95-eRjG20bqD_F5Dm`Nl#IRf@Lye$*JV?`ln@J*L#vF%a1JQ620=>~|YVb}RTQeHpA!3i$>Wpy$ zLE8|n<~e~9g*iuCPHoFr?fzqGbwNPzytx(tx7Cjs2TP7+0DOisIn^7& zOTJW1D{MWI#F>;?`!2|;mh3t!BH?*w8%tr@IRRnZp3Awzp`j*#~ zu`*CL#DdOR*oz4kUC7%7O28>Vc2knHt_pgNO0b$i;1$^(G&7Pp&)$-@HNniNbUh8M zv)7mieSNl2Bvm3GDvyAN54yk#s6L--y;j%yK)}%`$Dp+lUz$~=K@APrvQvev4csE1 zbpd0+T^}%Z3>mvYVj?wPX;l~4*aS<2dSRdhP<0Vm(>0cSwUIb_BpD_u(Kb;+HRX#l zl%y?aCTXF~8RdJF`cg1}l&&1K8{}Rpr0N=}O z_gKD{%Wfy>lx!4De7|tQ*Pk3t`R@s(nao?ezZd^zC~N$mnKo^DVSU+~J~TKmz1Y{; zGt^a>-Z^E;^oD8m({j^S7R!U)^m+aLJ;lzBa%-*n{MQ(QT{v!|nP)%2!m zGbH=4ErS~dr|0|2s|N}lU13gf=Io|0MPbVu`U|i*wmb=B?Sb~e!ocA4*5=+`6l7W- zN;!4ahW_a@rse8k+~7c`H@z~XtI$6r6lO8h|1+{NODLhl0W8!SX<{kBd84?#UO+ zg#i`;CP-19Fj<3%W;l>94|Jdf>mr3Tmf=yQf%JE;W5>XwWi+&2Wg<26)!utxELB)( z<#~n9a(>-FN57`7osBC(PkyM_SDsm~{DDxA$6Zr{x~ftRO*g*I$Oo zP>Wkt?W?KQ(L_MP6b*@dvA4gc(2HKDdSgCU53wH0hF|qfelX~H)s(`ux=J+?q-IW)I08_QvR%j(xJ%U7B6| zm+a-E{rfj%$BjDB|6OJ$P`@6YyQ1X-xV{VL=}{B>am%w~ zq4BZ0<+yqD^hHSD?`Lm=_H7rHM@{q}9xfyOL?+t}{vkCJanjH)Y#F`e^4T>L_xsct z{(I(*J~_M3wqJg8Xma+0qsEW+cMLBg;Y@kdc>if7ye+e6F*Mz%7_VfqTSjNk%MO6@ z`Qa^q{ydX??S~}!?O|1_M>9Ll^iL@J$8XJ^nC%@kakT%`#+t)2Q1>hEHQ;}mx$Rus z+^5t%nc1=!CjW8jR{!M-=GJEYn`<%N`VU;#UAwFQy-|yh{`!RvLF)O_=idH0#O@m2 zfx8znJ8Sp5Vbnyh{|$N$tR3xNHDx*O_SkY3*k3t)NA1+VDE60Q*k1)Z|4>Et^_hzN zhf(@3g*A6m#`m9|?ap4{_hq|3{u6)NmeDm+#=_<+hHL7`?|-PNIXnZ&TQ<%WlSg6L z^?!cGR`RcK%-@0*;cEhGcqYm?L-}IWI-j~^|?D|a&xc(E4 zT@(DvsGP@!+Fi!KDpPX=o+A6#4MW`jQ-*|}b%e+J&$nf_0&ru^Lon#ZOFH!yHqyF|wk^Rna2^O6NiT`ZNQW4|D;emI&EcLoOYp4f)+EI}4 zFF7N-1$tiGsMS2AtYDS4uf0^0Ek6u(pB$zh@O$OZ7mPOQCwnM!UTj0}p6I`gu5p-u z_okhsIkTNw&fAbY%-;smf&MLM2NV4V&}xZ-npTvI|0AXMO`}(JBeXs!fnJJRPu6Vx z7@R_taV0FC;9py_Q&rlZ>bCn2uc(@7ifb@`=e?hR|&vXh)nvC-iC-(m3(wy6jy4ZOl?ICs@Ad zjhg!XvbSe38^B=xy(6=?QFz<>88Gi&z7^B zK;r94;-4GiOa2l|+#is5NJ+e%An{w4_)0+H5hd~W1c^Ve#C=C*_a^tMqJK+?{53)3 zk1Vn^DDt=xd3|H{wzxX{^BG&ei3)pV<97ejqtKQP@ZVfY1Jvby_BDk^eUHxSNSj^m zzcy)$e~-V&Up2S3(Z3c`mkBWKpY3WUep#kwaRzPet>Nqz|InHfX_)w{hY807|CQmI zp^R#&H(+*0_o_MGklE~G#xpuQ9XUQdNzGyJJA<0-rzg=Q;g>4?lS!EC*4Fx8qB~@F z8{PZAQoLIyspfriJLU~AdP>cL47cki&RkSm`#ojf*EeELaG?MCWN=Zy7gYg2Gh?%V z(?xUr-=j32xac+iqdo?v+JpW3IhUK11uvgL!_SRKkM|!wZL`0_qYm-v)a>4i{c+to ztJ=f-Cy|*)c|0;HI}OmSr(v4uKQT4Cy|(ds@ex`5bWP2C>VTI_qWS0qe_Q)Q+08YJ zX-V=^H7WbzMhu#Cv)TW*P4LVrfUiSu1?|sjiSeJxuFt8`f3!|}<~8ELGcPL7+@W|c zOxjKzAD-C`74Xc7;AagSf8eSg!TP} z^#Oyt?o|4I27MNPwbDVfc>9DO%tO;YjF~F6gg1}}H9RzG%oqHZsA9Q3sDRfZg9-kh zHfFbgnXcCV$yPt5y!&NU>pz;bHG8bCWzu>Jw2t>Ly#S$EwSwA-*^j6&xUKd!FmAj6 zHJ|ZcsV%>hJ*IXatTkcaqmwAaKBm+?B25*8M5IRURH{F9!E%2lq9+s&E5%>0r6%=9 zYEo3{Tj5J8^_9c4?!CCCrZICD_|Ht*?7ud=sJ0QSAaHerxPB6?d#HVF$?j19ZLK+t zTG>4{$Ub{~&4hixeRiW-4s5GYo%ETFr1#;P>}G#otQvLO`}awz?LAI;`=8%PeHf;^ zSVP^LN_e$$*k4sOUuBvFmHK&A&8cX$wbvWAyf1dNlVHTo?$DL;`x^x@7{LYbExe1e+-zsyyIElQmkN-3o3}3u; zBn7R@mQ%?1$B~q+8D)Q`1hy%GL;Po0;2%ohawYJ0mA+~@Eg^Pn=vFNOi}UQ)U805Pns)ze|tIB4}T) zWZqi7!(Rtx&9wIkJmdcbH4mv5j>KhxzqLKPrRLPJm}2b6ei=&sN?a^IH_`^jTPjvv zhG9tEZ1z7hjI9ZZRsYbj>Z;Sbar2$JE&kh?MgFsDe_^ZIU$_(d3%mLA7uAlz^a;99 zf=AjY-#0mcY#~ulAEkT$vD1n7NZrnaU~$(9Y|`vga}@2wJXn`~2zB=m$EEvLP@H?L zjs~^Zx`z5Mu2}T%+b&1B9-$G5L&-KU?rhzXecgY=$8=9S>FdMFJC{tsMh<82+zQoi z?$U$Viy1^AYARROW%nNPk094PLSeZR0-62+ z3YPoVX0kg`C72LS@ZY&e4UfN>tOw=KE+?!06D<_HNXMZ_cg0!6e=(7NrQ*Mk$iGVQ zpHJjpt@t0N0Rpk)Z`>Jns19(C>I}~wi46c{8&!%7>tx$?O7^EmZVn76A5*lSm>x>F z>lN+CA=(XRVM_3*YFs}&k~U-RU%t6!;=VPLsqs8>B<+7Bv=p@1SJeCfdtzslsgfTE zX}<5QMIZ8icEN2mlg9dY)n=z<4}4c;%cY+_u;L-z`nF$$)|c@g!aSd*Yg>*)Yt^%dCqaG`4*yL|3$Mv6hx?vcM*a03zl_P_4%~ld z+2-?M&2cmwVY?uwMw8Q)U;oHUYqMwl21P$KJMBaOR%gfgLtAmbFXHP$zxy>pzu+nO zU7KFJ{*i~jpS|ucB=9{C{-xcuM>p;8hsb+#w)zLrX2~};(QeNDn|5LYckbxhFl-*+ zAE|xv*P1Q3xduBV2m0TbN`^kMZ27V0`@54}@Y&0Xf3xEMC$>-y@b73_e(4aYpJXf<7UfB+>bo)<1{O@&( z{GYXLy&ZtdH_?pj*&38s`{?G@&Dq8N1+Ss?)Jz>)Gvj?I%YNCdSX#dPI%;Y>4T@dp z!4q{c3)$PA!%FY)Z(O<<#oY^I%o>^n-8AF1*g&g7?1$U2>2>a?OndelqsBk%4=(qI zHv9W$r}@1!YV3y{n(<#7mHFiNp>W+p{@Uee0iaL7jC{O5KwHOSX$D**;sM#Mmm9MBBC3W*Gduk^hUvaQn`ehCuc_PTFSUEWq_#T`fpa2T#@}tj0%wli zGd{>=f3Ix^MwW^G`$H_fN83i#e-#vGF-G9w?6fby_^)8OG9FJ4veOnJl4kr*XSVnsLH$ki z_YIk&_P&3t%xQzWY7g=8RDkx#_m9HH`!}^^$6eyDgD(L)9{bOL?H32zaS3ufjxyUL z#8zeBp)y-SbAa)Fqt0x%5R7aB?`LgToj>$_Xc--1D=jZ5EiGj7ME@A2WvNp^Kc@z;?A@%{swD42cU!!rT@0+Fzf8~y;(fO-(yteM(FfzysyCrHsf-v3nFjt8NsZ@d4p zhpEy;e@HM^+n=Omjgl-=?Gpp*Q6AS1GA zkqf=0eMfD5_G5~DlFPmonhx||p7xOccQxC)QqA_hubw8UZin_W9-2S3G&>D>`Io4k z_50x+2x{NP{cpYH{z2KD@aZF%)e0SxsW9PDv?;{=Y4q4**w-vj+EhybJg%ZYpG3h( zO?@7jvAtp#|M;8KE}ChncI@^y{r7J62j`v&$~QMru8(`Kk)dCNZ?M^bE;b$y94P&a zN^jjXt((>_&v_3$iIBWaRpueOeFmT6eHSr9BC^Y+h&&zseSe505xMq|&nUI~lRX6u zxnl}FPSo)NQBoj#6NCmYRL*TvRP#qwVQSP0-y%5vk~`pjp^PlV|90lK$AG_&>O14_ zP@(%lee=T%b(zury_2_7))F&o$7}0$qpZ)@dT-R$DZOtXYt>t)s9jJAlC={*ONGJ+ ziosCxnnleiH=9DeQ!4wl~5B-^{gmuXCT!pw)KcrPTy-GRx2Wrum zreMA)l|vD*Hm79=$VFqc8UHicVqOPEseEg4cAAmYVedawu6-nF!k)E^!=4&QXy!qd z2R%h$?_6r$|4>hfu2%K=DxPUl?E4PB2>=JG*yrDZ$T!|^)sx$Q1WUm2@3*QIAo$%5 zB^1$?xY_C8_X})Ss@Qi2BNqu$ss?*Mh$}Yux%^ux?ojmGnh^aw|9clcgeC6-n3Yo$ z{L`tlJiJ#u>fb(0O)l$in}LoB-gT$xC>Y8{wKIx>zg3~nKj67=70b&P(qbFka_3wHKqiIFsmh?M$+v}Q~AkFIRK32cOmmW z#n+hpE@9Ty2IAD<$C&kbzWUy|ZVhf_=1!x>=~s_4>%aI)K9{r=bNU*dFsnbzl++&z zAxXTcz$7P%iqtrU_+H!fqvWQ^5K$7jIV(WqD6O^AzmlVX@ru1=>Qo)e3&i(MbKNAM zIVQ6hkT7lWoVXy6Hr5kk4^D!qzpD+TU6Om_6fynb)qkC^|BBQV#z6Q@ZoY1a=)-dJ zaDeFeO>z`4<%k2i^f#5SF-C~WUmMdMJD+BjXp4zFDIhyoi_OTXR)PH0*pdjrZl3y! zsSMGQ0+Pa(3XqrChCdivoDOw7JAS#T0H;I(IV%~mkXaVuWRwDON_8z|hI}O17J+O@ zhFr)j3vtX%0ohz#%jX&LXtFH=`S)bVR%TgGN%uNB2C|W_wdd}zuV@tav_rz-(^oP|&Hz$wa zB`8Q2bMn)c^e`uXY)S9OD-`s%gs%|1j+5u&bqe|eX&omYwWMEg@VgkHXuZ^aqqq*nh zKlvVzr}2$APZ4dFIwcu@)TqO7D>vUTM9c!@##(dk^_d$ukAE{6gBbN4O@}h#sw3DL ziWs#Ii~_i3;dzU%;{tgGHV2o z*tJ+xj{-f#%AefUlnl_Pf2#+Yixv(EPiCHaKd1$@@RXJOail{C}cOb!$O?!J_5+T ztSx4ldT=Bo-#gpgH%J9)XH7+unbUR!(vu9K&r#5yg*a_D1w`CdK}*cMROf8}-N?4s zsjE{7BY<3P3hijQHj+_nC8Pq~$(rsrnK_jptnXEa{4g2vAhRsQsizbW@oWVx(Ft$N zi2W+tV%HOnherVUn<;b(ElvP%GjbsGLOA`2xv{mK3N(W?(N}=zFJ?-89J7{HhqNa{ zPGFXWIJKPuA_cCXMb?2=8e1IqbumjIv7!232a;?8D^u-k`|q`Ekw9WC8WHGb)~Gbe zja47B11{owlfSei>sp->)|=HK|44?s#4HPO z8gUAU_@IK8=yE*9qoaAHZddFv!>)j22Sf!5*#o)Tto0!o-35saDWVRaTT_1uBsbO& zY_7ZNVxF4)i`DHN@kor*Vr`AK6#-eN!FJbafl?mCTSu|ow#;T-%Ga0>yNy|aU8$&1 zUyDFuR|tP$kY~2CmhR2T@s<=-Ev#A9Ax9@e4ri8yIDI1pL^k0nXgLfYkD|XuzT$bB zBuj?m%vnULo*`-rPi{^!M8rk8=?xH_=R%UBfMY847?u}E?DI4MEjF3OJWms*EuOP> z5lA=diLvK$X5DNc?UH=QkemsNNPUta%5QS>pdse3A0;=B1c;8`Bu4>bJ@F^TS1>|U zR)9Pc(c*jOxT}!Kd+Me$i?3)plHBD$&BA$_y*PQ0C25}hS6JY6In3%whJ2A(^#@Cfa5}}08S;x{ zE$=XEH>1U|WeKx>Y9LNV{mi=9KpZW%GHYux38-@;MrUl_dkIhD>&S%i&e9d@H&`$xmu(}q>K&~0j8MxnIE$y?u=>1Mvh47ew;f-|imEo1*ZtvX~4L)P=P#@ox2^wCqaD$p`ksZNPp+2$@{ zF@^n|MMV{fKPo_8VrdI;4sWJ_h?iGdFGp=TompoZh%;sDW!5DIvNWn?1dz+BYpDP^ zpQVS47H4P|>1z$dY1zWMB^mNLW<72o&RYrJW7abU;$-w=2jaLc1>}#cCD2)-6(Fo# zx%0&C+eqU+jTbMggCnlVjtPvt8Ka`GqB zjo?u;bn+K`1*$fuN&E2?Bu%jY7TCUZ)=taRslMuvD;aVVU#aIy`rGwdOZ>?2Ip@w z>uCdVMwk&mo~y2<0_1U){;tvD49+6`3j=XNy|7+ShP;=DlLPFq60M_s9f;$X6cEXv z(PZQd@e`S4A?JRCNp~2jR!Q1{@LYEwbY>XCtl%=Es9lmzG6|FU2R4eTVIETzG3pVq z>SIQk)0qCRLFh+N>F)t!%Q@fRq!bK6PKq_#P8GD6{Wk@qfu*e$r?;knh-f+jalQ!K=6Wrv`g}DhIDT0Os%lBL0_@S|3yyzsnL+$7 zNuucomSoM*skO`sNPUY*6{I#gQtjV$q?|_d?xe0}#dq>G#`(8YhkVw7IOe5*{G7G? ziLX?Jl0Jc37tLcN{g|csk`7essAz47{@=2GlvUL4X4|o7k7?QuT9oAXUzQZjF2k&V zZs{WdMNc!Tf}*UWsQrE>Sw-#7JBpk-_?IadPCjKxf9K?w;|xkC?7wfZ$qm*{ z%hajS%&Gv{iy?;?Ely+;$b{+;n^B^c3J}TQh~$h;X4VP=IVW1^PG*%YMC$JaONvUR zfIP?2R*TbJQ$Wt*Hq>j|Qq-2B1937+0U2T~mnCPkfms_3#OWYgn01GNIGuh3kh`mE zsQ|fwrEfG^oL2T-X4#&)w8`nIP6?zl3pCJ~U$^}`T1{tHSL{L@2VcipK4CI)AQD(A z*zzh%TZp421!N4zCL6(8C4zm_M6gzgU{6_6)HUZb%SxT?N}Zh~wbm$pH;~Ov-siY^ zJ5fU{4Mggwc`3B~fb+JlaYn8bkUy{%J485pOndYAU?EO@FJMRuUt z|L_2`@9~<00aB7P4C$O}IQa!j8ubA!FqyCDQ!o+*Cm@Lp05D;2uoXtV_pi#&8#J+iubnl=|%pe6;y!i&e9g*n3n?be%2Dx+^$bH zPg-OJ$VXY)LLBo_Kt9D)gd=K5XY7jkT0{A?a8*xnySln10a=Qa@>L>+d zD{J{ZU-7W!TN@)G(u;y(hV!pQ^u%nnq=4*XEpPD^Pb4xt$nI?h+k7_ZT?wK z{?3wK<>VO)b#b6;h?B#X^eIk0VoA}`i)&;C02jTuQ3m`wITuBYO5Vmy3yOJ5>#Gc^ zFm?DoL!^|xhxb9EneD4&qYR`inzv~Ar%~)c{>rR9 zj25Sl3S{qO$UCgXLY&@}0wN`;pk*T4FgMv2fgGO&yu( zaGKHWtWHxvZe!`Yjh1#ve$$Xzzst$zEh*|Jk$U)l1(6JXZM3vY@-0JhqLDyeNrnjP z@5zwEChPV!m9OY8k}MjMlea*ck|Fb%wI~^K8nY^7wA_I>FQp@le8vJ{Zl9W9P6yRZ#=7+ah{BL!q%mfoMQ^eMPZv`rtz%t8THcs9(-H>*hp_AwG z71NvnPCjNyKjY+0GmYSVoZNSoAsx=ivn{EclN&85>NzR%$)?P0lC)($$1U?YZkf-K zGA}k|K1a%I3wVxOz;iy3)1|nYuNdvV%*lUR(m`D20po^q#0|9#;)Zh?IQjiXL-M%z z)>-F>v+gyXac1$Cu}5yUo{2i|K4yJ88S)yl{>MOC#hLAL)vZ229aWtQB-V>p-4h=@*l={FYg}*bW#q_YDW)xbA%{9q7hUEhjSMe7?rE znR}S|ZNA2wP;((pu|1BK2bieo7%Y&3k|Db?%R-#_T?)wV)wRrK$Z5&82&63;ay+vv z#4$GoWMOqJWrkdxY>PlXk_=hTEDLeWO##_dUCXTuu|ufSUhZMY!+ec7{UeZHR)_rH zUjj*C%l{7YO*Zp!W3E#HFEQ(P$&g)no*}c6nE1UvLjvP@G&anLKw`g(nhJDAL{m&v zp6NiGu~g<8S28rFRM#=<9s_Y=j6k*}LvCc2g*cUv0`lqVS{`ADogzBD;0FxZ$=4Xy z3FPHu$WNJNAx?=>KxFz_LCag5(H=b8iycpdImt{3omvvelw`>Jm}MbOnNmOwuCAqp zA^Bum1hO(2atgC7#4$Goq^-J^K86J5;L)Ca5ko%C*O*2nkQ6Sb>)C&DB9-)ElvqQBXZ=5REY(@JIof<7jbQmI5M0 zw6-`}F5--CQX?~ zI9i+%rGSW;))q(01Dw$_#$2ZY1oB)mD<|9Lr{|Fy=ZHAds_@Aq$vgAx=gqAd9PO8DPjKlWh^m&D9|n zSjckTV;nMjjgB8gag5aZWU0-Zhc(A>O$x|W)wMjrke``CISnrb!M7L7TZr>W?q37>AZKLj+VM;Z$g1jEu3^ZHe2ppe4a~ATr`q$Gzo$=uv2 zv_MuRL-u3VOapNWodR-*qs1{d1w=|>ZE>`$;EaZn%}oLMprggfCPF=p*F5XamU5QzwZXK2w$%rt(M zw#YnFbG$2%Q<5Q#%(4)tL@6M1t806Q73Pa`jwGtlcbe$PBe(( zgN$Ma@+vDF%aGW)g@6t;dK?4Ais=T@F3BGlk~7^9sq+lPIT+QztholVRFWc9NxqH;|%FgPF{7qA>F~rXFp&_J2}}f&yb=4 zRO~!tjzHSxa`Gfg8sg+8OS*=WyBO2k#&XgYu+1%Cn-uUdEBIYbe&3Rw<>cQi=^ajb z#~4$`aI(pg=5ca?C9UA(d6qQ9$@P|W9Vc(Mq`Nu!geComlLwjVX_M-iWl1M+ve}Z( zZIia!WJ$+ya)BkC#mNCnx`2}xThd23d50x! z<>Xf^=}AuRw4_%!`I;pi%pK?m)2G^|a585}?VP;Ck}l_@?Tl^G86UQ&$2s{uOWMK7 ze_GNg?y{pzFK(N|$rCJT5hs^g(gmEn)RL~@JVG-L@gB{lEHr@XLL3P-~qnImgzxe{*vlY;+UHPGPAmtc816Z3|nNFm9aI(y#JllK(cE@v5fvPd4G_lEyQt6 z3dpMJTCQS<_ye}cMB;cetUGP7f|SfTVhVL5=Vg8F6e8`G26GN;mPDUvpmsi(vH$#5N*O)>JM5f>sATn_W?(oCK0=IN1R}c+fXEiZ z7pg0ck&@krn7mf9LTirWniP;?buBkA#Mfg&C>t9Dt3dmQgYxylhWOFRWc_|>TI$9iaQ$YS&UCUm)eI^@sF((>Q zK&G;m6Zsm`dIciefiaKkbBsMFB)5%PVz@) zjW(OSj_U*>yT&m!{RV5X5GSJ)khiOAIfBhRA=zAk$o6%Nxl>u%LL75bK;%JO1uf@t zMgzv&c1gZ$NX`Rbk@~EGIFE8a#HTCvML$U#w-hQyt?9F0-4v}-%}WO^2w*4GHz{Q zV6a%~8`m^##<)qHJso|krZ&x(F>S`Q#-_S)lU8;N7P`iPt*|qvH4d)rtMjH!n_gI7 zp1yLh)HkiO)0^Ht2qn{7n|pf;1Jf52))sn7{Ydqdx(fOJfzo+}&hp^&-csMHQfaU- zb+AzA(!AbM*HBNvvcgnS?^33!oQH}%UEW~1%gg7BrD9*P?B&HCkL?%Zt>rmKn(IRHk^s@+fmC>KNDnXL_VXt5{iBrSj01&Y=OiQ}u!zp&M;~O;>TimZVh^ zJZ5+#qVT7n=M*}N)Hl5zbe(b3kkFL7irwA$GTQz?p`&-Ocmc|EN`76jtGt>Lsv%IK zu)edYl7(ipoqYERqV(-c!Nq3g| zH=s2!NAuOcMiVJ0_H|LuIVC?(=MMAi@cOC}8cU}NM14aDln5A|rJf$D zk8-iM;2}O1%G98G3xk6ls|tf2oJEEdd;8V3yQ8yEh6O6nsT*ososv;LkR)SL}<@9oVXf9Mxu%E_I_a zFE?BDvtqf}(SwGnGN3x7&KDwjx-_bp5B0&wJ`6f4aEdMDU~2XHGR&oq&#@DwL9h_V zG%s6PT)MckHJ4ZJ3Nv;430pmjyb4>wDwJ@D8YepkvRwuAx6+1?0VExz$H_MWx2jOK zvdUdSN}SY8BSn?2U94qPBS1e}9Icwz&J}}8>OhX`J6fBUEpDBWrx-cVQ7#P}OKn$G z6v7_Ism_kh)o9pYkYPxmDRkv^r$E|9jez?4VwcffL<|WU30@=hkS-k>h^;hA2V?!* z&Gen>Y&vPW9N$XE!>uwLu}$^cBAFU6sWIPzJ{cdNTv(C|NryMARK;jFWsb>sHp&b~ zcCN_}!i~z8+5r)wn(@TwuFpZiK%u_}5hYN@=A~4DMXDZ`8KWkrOBPbIK`U9hcbBwwTamuJgO18@TqA5mCO#io4QtZPh*VCh`5K35HC3Ij?HickG1_?+tT&;^$ z^isJ(Y#kvw1_$+2a8*xfrJgzlS`iNl!+Z_at*&qcsbB+d;0~?&abJH4?J&QpZz$in ze!bUMSeHjRF&d$_dBfpb(lW2UzZhBVIzSV(2<(~9q2q%LsA9mCV-*3Tm^Gz-0eV@Zmmb~ z(4+v0W+Zw>gylISRisiAp#V^2*;O1wkST~t(#IqRsatLcDUF$0l&&)_2CW`UG3X|s zO$}x=u@Y6vMQQ@3S{FeVw+_-+Q^fMB*ryfgv}%h(16Ur=#I>(9(2J>g5p7S!M3M}| zj9Ct%Woc*YU~?DMr%YQWV+k$tq9|V;=qQ#4RX-ay`8Z`!3cda1fZnM}ER9ruKx)bq z$}F7}2JTeQ-rhh4Q>UhvQW>OiXmLI2vd6getaChCwdzHj-ik?QY5&O~JyS5HOjo1* zJz>GLWo!wFO--F&Z!s*G*3Jf6_@XxGg4J=UuiR1WqhK9v%G~sh8izfvqmKq0OKOZ9 z#lBTK_>Vizlg6s@))5^$QxYiEo`OVr3V6sBJ&IB+U?!C`0%H{5DJFAs6aw}1QjY?N zCPA1P8&qc{T|LF#Vi_ov4W&gBO+FD+&cl`q#!j7;+!IFIu0qDrPVjX+FhPUD9xdH5 zdzz(^o8e(>mBRAi_F<*)DB?7tE+J*UXxaK02nBs?`sAVpJm=7|3~KS*B|k$XMpw z;R0#zHDHXS8lnpuBqZ&>23n*8px5fkZ%y3Q*LpJZ)4f~fc@#sa5j9~YLBi;8Iu#*v zezRrP2sue=@a~o^I<}rB;Qzq=hskBxTWKfS#4q!0!xRfx2f)a_$=^q+g zjhS=j8suowg4H2R=dIE%!{*KLE|9mOgvBK9CahZv1Lfu_!B0(&s8ThYb+IhXCE0NY1~Y9fjaW3sxU{)KG*X1LlJB~p7}3n2_HK&WN`rE!O4FJQFT3p_ zt?&};xV6AtYF^MNgK`6gRc=c8jv<7$Uh+$brj1q8GC>Y@bkiuU>&=3R%xGF`+kJ~( z>|3anqgoHrC?ne!=-LfD0Yj?|EZ7Fub@VqcL&v8CDFw1oO+_h4)0C8n4ZL!dEe7Cn zGiguSY-2zmbZ_@F%o2gj=*BZ8iqEivlA>Obsd1}#8v=$PIv#`HI1ms~X)#|jbQWA9 zOA3RGw%kn8h6lz2*zziMt5HH5XlN`MMF#VU<0XjMoa#T*5({qX;}h5f9r7rJtmkL7vv5=iv)oP^c63S? zj@fEKY@ad%g^|zRhp`EdsROy;fmtgr*y#y0KhW9Gj2*E!dRRT}cXXCIaL@@y7^pmG zyXqmE5H;K$guwJ=70yQ#29S|HrO~`};aWV#YE&mKF#hI?$l5_UdMIOPFlq*ytrE4t z6Jkch>uK+nH-7^f)V7gBj>y9Ov=Loer;bSsHWyb?c9sx<)0PfZ4poy*5ddw;_@q%C zYyqDSxKQ0hndo9O!^fXgb2qRCY`b?iyC@<@3`&5~>eZl zZ~8D$)S4#D;P5C4=IBI}Pup<@V$zY!n%1j1A(ZGugx#pl-=MwoIh=5b)hQh?^=X}9 zIZQ++!}zgO2;ZSjDWDc{3=cjjbOpTPwa_`jVfAnR%+~VBv(4c`I?2cfZ%$oF#~IHU z!1Nc-X9n}$YCPZRDdfGiv%R%=_~0$zhiZ%K*UoM{y`yKSkju3Uw&P?JW-aP@RNziI z%mABO2A2%=^uQB3;c(jqhG>hXWsnkK?yQ!J7E7 zYlaeGZm!XkCQxiHQ(WnD4N{%}UY9iquIn=Z4-z8gK)bHoAY9dUtoE5OrlVZM=G?$Q ziJfil!@A+BWrbDE>**1eB*O^Q?9u_82;_#!=`bdTEL8(KVThg@DP4j42v}O12A^Im ztcwZ|Eh1EpE`&L6mu;u^)`e1?&$du|8-b#5iZ{Qfqc^17p+*D|AkgpvS(v*B5S}4j zxu&o+d>;X$kkAvv+S>?}_0Fsh>*f0hSnCa9p*J3iwziNCEC<0sLPWE`n;NVg3eJQG z9Q~W3t*LXl3B%^Jm25CEX>aKOJ(NPb7W6De>7b29q=Gkb5uk-Ra|znlQcR=J>~NYK zoqnYUlAxHVP-=6WM46bIablr7Uq7sdc6$>MuAkLfD9>A28YrLI*WTCJF@%%m&2pR< zGr^T>o4pDMuY*K!*fNhut%U7iU^?EZi^DcGHq#MzSfj2HW<&FOH7BD>gf(jc9~4;Y zaViRcg;X8Q=Pg}J)>7IFo$VY#JDyqZSTqZM(Sqb5B^EZhp4`aMu$%a;J*D!XcBn&+ zSd}B~ClxySTk%8-Q|w|Vo&lmVa}5z9tDSAOB6_Hfg!w05maDxsb{5mFOs7!cht6AW5f~^JwoA9MKebz?0`vHwS=T8z z4?eJ=dA*kkr;p^T1IuW}w9;>CaGG+iky{Z)x$a_*>Sqy(s&ZjROwKg`JimWP*eGL| z;02fw**PtJbeaI?`XOb~5s>N)9FQ!U^3XwwX(Gk9O(&{@jbx2J;dqjo027L)yiNMH z1-+_?Cm7ABgl0MdMz-h_>x=_8&gW-->RL&yI$u*ETXn8SccQqA+)z&2DI>uzqqC*C zhNbih71ry0`;(oK$L5X%=eJLxs_8p(mBzv@UO8Dt?K~;- z;4y?sIC~}m%4UmgGci;~%x~gl8(E!GRyU~ek?!-kS%?lea9`dquZ-2*${|chXt)(C zS-9zBb#fE^PbVVm+>G{e_iTf)HxV4>x2N_MPT0Up9Zp9;xj9t9IL8ER&jyQ+p++Pd z<e5mgc49VzKC{w4E{F<+FjZM{@=oyN?zxSFg~L*V5HSftYA!9<&v%)Xa9Y%u!0H z@HiJ#Tq-sYfefYCrmLb+2eZ&D&{H(V1-gk;p4);0jWnUBCd*dusZLa)>_lPXvce$R z*;-Fsr4}lR1VXs>MMd-+6}!*S$IMKcy;D&#*LX_Dz?v59meA=7gj84=p`=k$Ur$0y zI|k_8qn-^5BHCO=DkspwG;CVvKAjG%^_Ji;%L2Tlv|0^_<}Q^y_8Qo)I+4a3Ia*QB zmK7oe)~17lEnUrJ3KL;ks{C^eVIdSDOz^_PVH*2rSI&;T72Ai~kJNAz&Qpy#y0NQM zx9Ga5x};L2M%kzaHM7wgBfCmG9B|*Fy&f~Q#Ot(0Rl^~Qc$p>Y=U~Dm0G$JRWoc-j zvp};6TAs|v&u;GPEOp_uXERL!lhM3KSphIyfmeYQihuP@$;iOMFtv={l*JUNeaYe_ zr=GDS-@Ii0sS8?`oanWkaccgA6>ZIyGOu-hON+fdbxCssAfAf4ndaj0W}}J{d0v9Q zqT1C=g!UQ3H7KVb!i_{v9bB|L|HNvXcP+!(BAL#lg|Hy!QDY0k!{v$r*uupzBR0>f zkW)f2D~Y&eO|ZcZyAAVk=0PpjdD`X?ft+G7xg0iQ7Gi@@591j0WC2KLNT@62D1vB5 z(Uu<`9Rwu2HA~bh1e)(*9MZeTSnqcUjdt?OcmzNTeWrypMht3T^=5JswrO=mn`HVD zE~BVyTUSzZvCu?h>Ed!ll`IstvI&zjJk$)%JmD&R@L99Mc;#kk5aI1G6|a(7cr!U$ z4d54C`xnm`L6$JAG9m1fzdD>fHr(@5kS=Xdl4O+}ZCP{{be z;4-uRbi5hfjeQ8+@U$K7fKVv}qZUIWMm3EQ6Y6JI5~x-&m1M&eHD^A(!Rq#Dp?ci8 z#6f|51xt5G9`3N>KYUErxH^wKkd4nXESz?kA&CS8g zeO_lL-rg+@NJbR8W9GOZ>pg>9lRT@Ht%hcV_r^TL;`R`TJX7aE>-GUW6sGk;G*>Q_ zt31Y&3)iZ;s-Gc-%*V=%&cCDp4BTtx z4XhgE4UIJ?m3r`+E3MAfW8BuyX83Md0U~|sY0iQ|cgIjqS*2YrQ>corbz4Vlr%#4g>h*dgh+9O8KC}J7KCOgx+*Ju2 z+V-e!N8DaVb*Tzl8!5`;ZegSmitJgW5V6}7)k_q=J&_`ln7xSVxmDk6kaprW)17OmcU(ijlgEU^VpyWUl!e3K5XYDP>k)?0Hj zjz^u^-93n>yQT6%Y{jd?{)l3;WyFZ7kdcilTrRxpLE{IvFr!|rYFg;)A^KxeSV+iS z6>O14a;Xj^#rJ0HmJ(nMi}PIx;NsHOnRzS_=(A61QEM!t{ktW2LJ^TP8@g(6CV*on zJ@8hNYLg=tq8?LX5H8>~`YwwNQXIAF*(5#r@9EfJMFIp@g7&#uI|qvWWvXcXq+V}P zM5&H!ea^_vFZB%d_PNqQx+71=$?(O%vif#_NjtFF+7N7x;>d!sv_-#f5^RIHCfITU zwN9y1U5F6LQLTKeb)JfE?I}Y{nKT8*3H7$0`kqhT-uA#T9OkTTE#JO_jk_7E|o-<_a?dqbOl&VEFNK1H*RBj-4D-z*moNaf7%~ zm}Yulz^Ud32Ay((VDKZGAsDfDH$^bwBbp;vsq~WsBa>#9V8A1uCRj=LnMLwE!AMn~ zC>W^QW|L+Lx+BF*6{_h9%oV~q>{wkvMPS5!c@ot;^#t^?^b2(WT=ur^;i^`4OUX5>OC+FnTj_PSA5SFlXEjyHFWHN>94Qh zOJt=%d|_Elf%D#=nq<=_KzY8+GhtLU)lRNHIAhM$%VQ8;a0G9q)kH*Q3&yT3FPQM$}|IZ0G?{Z4&YM`*#U`> zjoAUgcQGcu1NX)JNl%+{OZ-Sgoq?e>4 zVtA%Ds6Mu$wgc%@e29`>nSMs7-ZV;ATJ;hVKOTee*n{Gm^m(eizrZs!ttLRA_h9kE z0i=;e@mzove9ouNI^)Ig6e!sVuB=NIc$HD-Rm)Lrw(8e#Y1VvI4%yMvO}!OM`_{8DaaVWpz6L$%6-3p{>0Dj# zsj6-bK?>$u=J{(dtk_sMK83k>3CN6k_?}|;F#mu*d!0o%&8N49Zf%B6Oz-{ zat+ZJc3dY1I&%DmW*Q}xDm|v(g{_j>w4EUX+SNz1AeEZoPg5}h+ZuqRI;+!P&i>)IDCa@8wXE_x^d9>=o^Q0yJ&0_PA6KaV{)vCzIBP}h|`^BVIC*v40LfD0C9pT zm+En%BU`h_X?S;w_c%=>TE)jINWYwq6Hl|QkCPkm0zX#CNLKoB3aT&pxEPh4b1^Zu91y zd~$yNye0W%&GQzRn=_WRv^9H6mz{c2%Ly%Qt@%?=Z(c?;dRHlQT9(HUb7r@mR$clt zI&``eqfbA*v`goCYzgdWim4oq0`Y84z`?aqa2?%DGe5x9QD3ZGn(^JPB{<^LvKFhE zz$m3y)G}h;88*j+XUP#?Gi%jK;!Xp*#gWjuWUfR>$F!2J1L%!e|`_b=?#{T&I(* z)K6o=m$U-Y#^T~vx}2kntwhzfo8{7J4m6vD6-GKem3*UH@rX@}1hK?2oA9Gv8CX!j zmoo7LO5jPsM`A&JQ&eIBK4D1*`0yDp6r(p)&srFWuC(TF|qBp*R%R(X6<>)xvv3F`i!6KwNK~#WB7~Vm#jQP(+Gv zk=HheG~$3yD>5leg3sz{`<51aT{1oe_91K`k+Q`fQDK7vTI=jQ4|1deE`VD5s9FZV z08c*ng?7r@B3h_Xe^*R5U#TKBFjA4@isOZdk#Q@;i;Pg>78&H|H5WA$n&;*r>C=V^ z0~-XJFd*W?FkG4G05zp_=r@)k^&8~4wW~$qYghKS;w{Gp3SJqq1&Y*ggd3^j2sd1Z5oWZGBJA|F zAp3sv%(plLJ&)@^=Cx9zmEW-v4-wkYn$Z7qv*`;P^VEk;<#lLmEV;x4c@;l&jNunS z`3I@d3|894LGeRJTGeN{p4C$W9)o6RCF*5v-HKLXGJIZZQ=aZfUc0A7o%&asO>xwW-J02v$%N$IO=6QvOsssR(w?rn{~E3b6q?1 z__#hwJtHqwZTU`0TpV;HbzT$Buh|g22=C62wNoj3y1+9BN;!z zjyz?QIw5>y)UGn8cF>h3)DAdlHthhr=xeUJdMes#++w^DKaX}Ya0OM@b+(y;bI%c4 z5}g}|>sjX9@{O%r6M~zx(6-W=Li9UYc8fC#WJign`kC#61%3h;R=Czn;6ya2mn@>9 zh|D2UM8aTQG!bEk>n1@d% zuA7f9W1m>SZx*UAuaT|#k-#9f^(zCS`ta@7L}f}7e>=MxD5AGP9W$U$7oVbk-g{wb zAW=ndxS$FQJ>F2?KTe?}VgS}&@KdDypb}%K5y_de7!$6RmY;&!r+idk1xEIO zz{d}B zt7_A|SgkB0TI{}3B_)A@Dmd3jCtSUMrPCAH(TWsA=2rTHwOFL!OK1$iEDfQR7A}@1 zVU*{bN=kj-8mF&y2-H$xT2u<>0`UVT_QTuolP!xK&%>yQlKR}duC5d3V=JJiv}&jz zt1(*XF2zTB$n_`AS1T7J@s8+xK`iX)Sj9g)8>_)vqvcvV@iB@%{GdAD)AFlzU7^rF zpMKI6zeUe<44|Htpif*y@*z+#W0oy+xePwGh!b5M^kWu!MoEjy!6+8PEPh@CnFciv z;y&t(sLLAk19}&j+G{utKo9g?4biN0?KJln|ChBB)qqkuB%We&o2)mbi~>hq%BY4& zDRWKB3g_d4B>G6-zz~LIZhlMGs$Vvavh_lffKqi)jScFPo@ynj^x>;k^vz~Nh~Q_U zu*!lHI|f#EtSaEOi5`4F4PWX-BWZ(W^kGBwZLXYyP@Mx6T20^CMRRSMgP{h0SI1xk5y;24h5D{&;nahUyPATF&opQ(E8afvpx{sopn)^^Q zLj@xdnL!5*fj8qf2Ey3t%BZ2Dk>b;kCW9m&&!8pF5FSm0%-7pJQ8Hyr$8cm^sn4BJ z#Lia~hQi0vBX+B2yI9w%eH!~vQ+k>D8s99-Ux*LCsxKJPjHDm|{f8ee3Xp*z%Kn*yc|G)> zI8Yku#|JZ(#vUZcq-J(|UlF|?5NhrrA+HNtD=;wM)iJQH*hjx&*k8u)RMM|0=!D2p zA*jC^W%|bjb?HKkKJ^QGF%0z^mE;d8{M?9VR4-muz*kTT`1%X2u~pe9o|$YDib*AN zB_sOPI|2rkpb1;lA!Sh=XeVmu#B`1aF!j^r4%Oo)B;vT>dcr(BaaOCbs7gzHqbg~s zZvY8PeZzNGO7Tnm3If%aBC$(-qcPP|-=H1mRaTyMsc-a;aH((P-sMu?$d7EPZ^cHi z)Hgz@mih)g@}<5N9nn(Xh^1KS8?4)ala~4{61UW^rY*44k7%(gQ~9B)cXcYSl5q9@ zmClIBQa@M_3gvobJ-e->zx;tYm?R~b8H9OXs;#7xVMMN>twg^mQsj?vD^)>47>+FU z@T71$8AjlT#At~_D*>{K(_sv>v}62IKNcuSK{RO&?;YS-hyog}-Hv5o<=t2Vst}a8a(fEtBqg0lgqip>U{GBg|f$Re{5dv}4^h>s{PTdDM6 z*~p}c$_6~*pll^a5|fQo^^k0!ZktVt$hsfK1mtSE0`WMk!$!giDronQ`+WSyYX#Zr z-6@p`kysokgbl^BRHWm8hL|_AULsbbx-;P{#FLVtkQ!Dwm4>0vN7CGe|po#iB%AU7;I2YYY@ZA-8{sGJNd zERt(FZK#OPy{jXG@>}RpQbZ)jeEwPVz+D75lUZg>5W0_m8|hg=*p3J#B7mWb2;7nu_RmwX-CXUcHHA_W&HB&e3sw%w@E~11!X;WQ; z1x3W^8{HBc=q(HWdGHX4MAU>qO$60#(>DAH&g%~Xmj+5 z{lKUgX!%iUq`%bb{-Qq#g4uHLHVRc8pT8awi9wO*z@V^#`q>MMeO>YujTZYIkol`| zq$r{={#}Af3c{J?=I9`Yj$baxE-}g%LyZW|h70i6bx?h!tu#Qc)P9K&qhd7Cr!Q*- zUb`^w5pckbd%Gi{ji~8#Xo9Cs#)mS|=fOjyh*9*oHpH)ZIz5C8Ynn;ZF845UNFwQY zdI72L|K_z(-&*PR<`tovd1^R)JN7Tg2FcD8Zf8^dQqgI1}2(eTv$szjoOf|?|5SW#|P8-C90 z)V{!5Y_!1WK zqiT_BfLpOz0=S5lS$gsq03<7NpkZB@KrJZJw>aoCoGKOOV@sN5e00W%c(A26e17$=nr_|v>6}71$ zM!{@+vaPotAA6wET4U+=f+HmPE`JQGb#-Z=oB)sGp)?6-m!nLNpcklLF^UjX!_qXV z1$7rVuqy-qocNv)5>rhgsYf`-NSmWy({kFJBgCOK+MFF+Sa}0|1G2hu)pFzei<5!t zq6XT|tDZ^4Zs}wb`Us?~MP}f2J{)DB_s%1+?;pSW$&=Z+bLPy4@&p{-rZk`8O~famurU=^*xa3)30XlRZpFtg<&T9i$~&k=ZV$oEi7h zoNGNwCHzk<%}H=;I0poZ zM_z)`;=>YR#tZ8ZPr$I3lAxuH=C@ zbMYpaax$^@;>D7onK2pKG|5{0Mj1P#;py)Hf9K6kNik_SI}dTlA0!A@8ZE(jSX_7>6&CJL0@nRU5=t0%!nrG?m{wTu`% zcY#f)OtEPww9XwfhZsuMhs{>;wK5==C}ojRY_GmNFCfGlvmSB zg9N5Ul(^-h^Q5ZXx;a&~mlo$--iyvoz!N3dRH59uX}E6IAwBJZZZ+c)9gvc*x&K%hkF0c5CX%V}9kW z9*-G|S}CjZR)W)ysG>Ef0MF!4a!-#Phi5iJL-ewbO-_r!OUrb%5rjmPWsUVCz4lJYB!O^#Q0WKJW}vy$nlKG(aEIk7ZdcD>mrXDl8F zQ}?8%icwA7lI3!_6(0-h0Dp=^_(S83cS4BFg+^@G;h}v;9z@KLSQny!&eF)X<`8$Z z5PcjD#Ha|_>3t#x4qzYs)TW95=rTLdj{uw~gCt^7lBeJ_0fs&2*0I0CUVz!;q!Jbl zMGXv~|FB8%Q34SksU*at(wm3D$Mg#n{<N=V&4Y|P zbSNO+sRXu&$moc;apPh&-AzXl0c0LJ@*?HM#n3CBbCISbxr0}rf1Gm&aaeCQZM;1p zCPT6g#}Dz*bi4x~CPQsFQyYg2`y^+J9a=>p8;SZFqq;jVK0X$PdjI6Kcy$X0vl8%j zE<8+}iPuS~yAMRlG?6-98AeKg_Yq+IT`s@s?_x-!cQCoRrGFonsABm_1C_H3q=#9M zcpf<%kLGLRWr!^e?H(^skoVNuT-3yLTF)JvppO<6ljvLt4$8vQ*>1wsd`$PUGgZo< zRC+9Y;8>MN5MBU=2c#3?<%7@VBn!$8i^DdmcI=-kS`d12K zxzIUG#1W(i_>4HMVreOx6p!y?|lE-qU zz$PY>dhe9UAqlR*N*%@eFBCB|D;pML7LNL+CCYoO*-RjHT6!Ep*C{_T4~ZLYq;i$f z^IO#@K80qwLvX5(GIUmxH+#bk*Ud|?u;zd{ZgVrTsWeVnv7*z_0yahV|Nx3f;E5$ zDcHGGo>HR7tvLDl8meq#9?{?GyU9{GiQ~7<&e07cy|S2AVqp8wEY7JG7iUKOe+bmr834v>%i-`dEri-I(E}YX}gU2Sl84< zWzcQ;q9GiX!poyv+t+w#HQJ#ZNby^Adk&vyV8Um}G|sY$c!}ueLc>zK*lg4u#q(=M z6;=0*<#xkDHAb|{GSf3OOL~n(7Fh$%eD&zk%TQW5Xar>>^9w&^$x_qfb5attwAAQa zS^`Z^qn~5xwP5rkJ}W(%mssg`a!NuPRsks_Ga-@IOEaU#;$<#cOniKLn&BRZU_6l( zVhE7L?!yoXIZ}ya;H)tvhL^65*U~WhQ6ObEdU$8Y&*->GlcE#FI3JxGlZp3xU_6Z; z-abA#0k4M9;E7x!z8@X+P=qadz>x4hw!yj^kx_%`lTA*FfqfpZ1xM*_1PvY>^pMWq zCv-s2VEv6D1MsD&&;hm(9nrv0y|2%}fnm0w0lM&zAiOx~iM5paqTvdgGtT-_BeQEqDl0}1!`g8AsAl`SkkWxs$1(wPH{LSpLl-d{z;ZCR z1NV(f5g~S9SMlOb#}t+oeG;AO#AuWXeVu|&g5wRKW+WOdM`{_cyfU-33|m^fke_aq zNSrAN=ww)S$_(hLqX|im!^bzUxfzScVY1Y6kGd;mQ<4LHhcXF}9E5MS9umq*XAx zV?rKC8E?ju0$z%eX-%ozunUYh z$*`$VvhDMk1#jtz!j2;h;ikX~_bZ7yE78DT!;(vUN=WIAOL)A#@5AgsDlo06Qdq9HF7<4 zplDcP<;xEeFw2s7iL{$MMVV!Z&i=?QvbD8j_N2~~nk(mNJ^H{Tgu-wC6$Q=}-)saI zp|BzTI_(W1?RA7WD?T6qZfxcY)R2Iw0P81CXPLdMh#=}O* z(j5Js+KG5`$8gKvIc$`dxg0tLUAhC zxio0AMMX#S$7>Oig;^vhgbqOI#89M~i}k+panF_<^=ar?=cHwcue(^Y=y1Ja36m+& zHYr2w!s(QpezG-0586O?<%{9D_t16QGX71y^pDea7nk}~e4xpBc(PASR)Xwvbtio2 zrVyFTgep_Ha%Xs~RdK+!3!b$ZFL#Nw@u7)$i8tPGorQbhIVsu6Sa?d%ge*uDbiRyB zL65*jrsv?@^XP3HzYRpR5h(>JXdHZ;Y)lV$%M6+v@Rosl&|?GSN^gVCxxqneh{ zOMP71L1Xf~wj*4e3V~=0BdbcH?fr8#* zPmM#4|IiXSC~&W9o*A;?oW_g0q=HS%8}+caBP-6e7Wa9PBW}r-p%|5Bk~wHfv&fu8 zs!W|Q4h~3|D8@gN@k;bjtflAyVLZt=q9Rc=f=f$mqZ-7qU_71@{vmqlQ)@!^t1m*A3_R25(=QSdS%I@?kC zO6O!J*4@oZQI5rDz0?9+R-fZb7Q-dnBLS2V(_;y^U7t1z;%1kljeP$5s&fgB8>!IosVePatD(z zTpsJAMM3|v9!4bFT2A1VmFh6JjY$gaQOiQAqDoA`Ax~YlYQUY<(@bR5nhE6R1r z3=N4F&5VgSZG0VT#|+0|(z#4j|mDR0EqlbNgs=t<&f zNkmqd(n3QiOV099*`7ubDpx{bMIWcyr*T2akPWHMGP5MX63h(rB}7?P1m_aALn38G z@$8v%z1VN=v2#5KkDfetiCF%J&-KyD^ZdD<-s4BmT_St(6uLfQ*$<-YsY|N1So(2x z^$tVJ(dt$IQ0~TJT*@lJsjK5~wd;vUjLq>lA%qWVmfqM*7p(Lpb*@>N4{2^53jJRn z+nkS!@~G{mS8$il|2Ej^Q#F^5vgrTUgkmrk-H5`GrJF0iApyff!iqUM*7Ceo0eYxL z5*J$t(LLqlT)%VI11oM=Nz{-2#zdWF!hbJ-=e$ZUf|Fkvg>a+m*o0pL%q$-RUHBd1C34GTE3SPWo3tlV1#P z1_M=;rSvbgFi9z9DN~qOq#Wwr80El{b>Y?yHKo2e6O`GN$NFT_av7dXTTYvksXa3{ zInvEpnkq#+i$jms@snhwTi+^9`Rz-NQ6AG$F&D>iu)Kk{zVHKhHu1Fqvnhd!=ZQhd zamuzOnXsg0nwgP~CWa0~XF-MnwQ#J`d%BuT^&Wl|3+d7EgGt~H^H?b`ZOWyl2{$M@CB-=NH+ zIE8OW#Ifv2>xBAN>n4V1w9bXna>Nk*g2PNMQ4rHK4Q52DiI;>KDO>!GUuSJT$-JY1s23)RQH^ka;$qMJ& z=v7TRAC;QudrI42b0KuyA#x<5FNSWmsA~^&RF%d$!`1`#5a?bRGj_T6pf7c~7XEcp zHK%&%vZtGM=~Sa6fxdK(hVVaEHrI6yXU-i-mo_FkiAoz4byR9xbUnG`Byg^ixXX!i zhOLvJGqMbJC%=g79L+Q0a7rV6i zTW8qA^nj`xi&zO&U(do?HHo7ag@dGgqmjOybB1_8H42484HJog4t$@<#hDXF9^{O| zaMG$gQO1e4t3Wz>!Me`@zLjf86pa9_Ts}WV#;1NpgQZw>Zc*uC(L&F#w5n1=mX|(bgR(k!C5slWAQO_im zLCqY;5rtjEIdH38rBIG@nYFr2M=6tjrNmU1NUxl#?$9bHV|{h=Z1$#FW&1$$HrYPV zAS$=bOU+L#Nr=wY zl#5})B@ucmAK&41$-nO1q3%);Q80%IXb-zfytu)ZnTZegx$tmWF4U@=R3(<2b)zm+ zlzJ`4I8FVbIXzDtOVS5)Rw;^imQdc%Z#lBzxXG;D?uIKH<>rn6I7d~3j3^(f1_C<{ zptp)d(#g-k1EU6t_osy0qU^ZqDoZRzbTXQ47>U8mGs9UkO^`*Q8_Q`yI) zCy5?rRyP&-ubi9{#8TDYxqBbbMNYEh%fsY61PVBg$4vcgC=(HjSAvQ)K=Dh%`%!bF z)977j@@EPi4vpr$@<@7{vNlcfl^$uI2jC4X^q~uJFQB6w?gx&QH?s_fy9}YE)nW_N zg$I4JP`y#lakj>l!uk44Ljvyd6evDJmmqT_=pBc>9fyN)+Q9jZ2~8h?Tb^q%OJNz{ z?|gqBC8lHR3~r|CLjMoS}c9Lv%hYEBkqPIqPV6;p{mctkNFCQaC4 zlxI2nKs`9wm9}=Pqbjj@>z%ip6o#_9uTWM_8v2|G zkY%Eqs6}?#n^xL2s986K@#lLdP1V1>6Q(pQ7QMr0V znN$53ek<7tBg(_*p6u?Io)MiIcc20pic7bUH@yn$`5Ef4Estt+i+ePaW6ludNwT1*o25S87KD%w0)@MlHzIYR$n&oJT8PVzTCGle&ztZu- z)v+n*6Qg4?6M=*nEi)l8Ix8kOLHeTcHdDO$G%Gtg8!uFkj!sO=iH=W*&7t4Y#pg@1 zViFUy?4;x@{&0#mK4G#JD?TToC2M$TH@!I>FPfvLMYXZ%nW-_^8q&j4a?!Cl$#}y> zno7kvYvN=z<$@)BGlE$2Cm8X@5_~@+29F)mO}XF0FIJ7AS0vKcqUbH+>a{MJ>N`?+ ztrWiJO0SE}q-^-pzW@!dipIO`vV;{x<1A86LC29U-|7ajINsZ%J`WQQD=IxTJsa=d zNkd`c`So_X7jtD2sWwomGccj@zIbMzP!T{mah{|$jppR%}SI^6EZb?*aYfAb%PL8eu8?B zp%zbXXLnY2yz`Z7nHpXi4Ebc?eJWa74&L{lIdH6cl~5K3$QSObYDCF0`K|Tx+agrk zIG&d+^-y`l?trK^8pBCIS}Z+@E#7bJ{9u_Dqs5{GSbvid(4_6>-S}w*yr%h=&!6(%@xp;OB$l%xz6GNt zX<8O(LUb&t7d>jJrDrEW-Wf63^l~7Lo)#24GL#(xi4;{pb(5J8m#bxIW7F^#Enb}b zLR#{TSu$#{AM0SnwKQ*M|Y5dE~x0u~JJ~D-- z>>AU%>LLAo%%=^zW7(Z&!rw^$$StN<>5pT+6WGl$$(rpKI*)<$8-SslSi7o>sHFncbu88q3>^@2h%# z{}$6X^pL;G=Vgv}o!vSnO<#R@=iZ?hp;=2T_b%$b2)G>VD}Yvcd%=u z|Eht!6Lpt#C*336=h!vUPh`4l?9OAl_f6;<+$}l0#O?~F+ipU?j_GmPwD#@_$&P`Z+Y#kmtpJU&Q}tHWp& z{a5}qTgnte*xkta{MJOCD&6wZFJ`{4DgNvpVAojQb9}!sr@x5ZH%#)Az;a7wH;vs) z6M25l_b;<+4UjqL!LBhsivPn*?`ixzj`uXX3)x-9u6JvhVr_Pf>5t<3bJ@M0^EtvK zzbcJ8yV?EPgkI4p{)*0wzo+zJ zZDbA~XLmHqb&836l^l)b|B>_WDZjHE?>xKzu-kz1)12Kd?9OHP6?T`hyNz9=yle9P zJK0t77qfpYyPMcG##ixFepEb_zKUm-{(p`Cb32)%yZoj5E7wbr-$1vad>@H-!ADi&^_mKWQmft7ru4i{IyRBKSUD!2B z^%AFNq@Tw0)wv$5CiU?h(;a8GE|;sJN%@{-x~1&y^DzEalX$=IePj7lIaGLA`5VpU zOk?*+c3(0nfA#h<#Xjsd=_38z*)`_p59U)|`eDp>B)bXhKF02c?0&(nF}+;A{|LK< z?Cvn3S9FTMqBG;~DScuGnZuXZ?Zt8$Y9g;l&gTJkJ&pe($2-aHd3LLF`hD1qWcLGh z*Rs2r-DB(;u* zMs|0wYs|l@7o+@sQ|14U{O5L*DK2LBO?G#)Ys}9XzJHG0Mx7)@2X>A01$=)KyQ8?A zxhCb!^pIZ3LGka+@_2~dveMhb=^bGA47*p@UCVqnvuiBhlYIY0b|-VWo;4|78q+N+ zC;fHiW9ceWuF7r)c8&STu9{$}*Yn9uFqW&BJocb-Z4cX&wuY!AtIF1sJFyM^6qoX+hg>2>0K&1YBfD{uU* z9Pa?T1)R=nCh5Irpntii%>P^LmKA@cK|U(~Dt%-Ajr@)BQ1zkmdzkZm%q0I!IR7f$ zU)X<%U0E9E|0Y}y!`OY3`K~kJU(G}M$C=((?tOgUnG^YI3(NTkyGk$aG0D$w%qP@P zPvwpOILCXQ-3^@1L6h`Gdq{6qA4Yko^p&2OVE=SMA3vKmRp;3)Z92>^|04%Hc(Jjq+0YT*u}0G`@!|rB(>F*sNT_gX|9G=N;EtccmCh|1W zpJcvf^r;mGcDI;cbuOP-zKr_wcU!4ns=cWA<<0+@ z{}}%e$1iVsFMCK|iRqtZ*VFh%xnH{3_^MyK+4vJp`pKK+XV#D2EI&04-E91yxt}@1 z?jP*d?;`cmsINo${up-S*d532E9}0{Zh7OsRL=N4y2^YNuv?{<^fzMHm|h(Z=_`9k z|2OBmy!m;D`M<~RC+rroYs|l=^lupW-PTRY$I7me|BD{dM|79`hOqk_yGz+M^6zg# zf5?P>P!GxfL3W3;JAqvz|1cB!hfV0;;QLG2UBT`?6Z)4;=-=%r^J&b_5x#$%-JjVl zHlaW0A^jlM^9R`-!R{0j{SPytpKU_Fk?(J1cQ3nVP3YH|&_8j%d-=S{_rK~b!%wk0 zI>^{t{v41tAQ~5H|`!k>N z)>m2bP~)i4?l9|L%HsDIkH5xo`d0BjeUtpn`eS9Ml$Bqz_-1yJ8T}$27hYobM|OWQ z883|V?=juca>m!R;>Dp}VzG`_>@M1D3b&uNELKi}+u> zc#p+vi}-z5-qAGraW6s-Rl>g;@MH*5{7bW@YXasV$_F18Y1H7^1h}WfyWn~vv4hcv&RQymfP@;Lj1_n1pkP&xNICUl0u^J zuS9v)YhL2yfn)oPek`h@X}e0E0uXpS4JNtnX{I*lM61)PH)Bxw;s>embq*GBxOT#Jz7_;DN1ml#w6 z^Jk$a!^!hKG~pe%g6uI=F|q!PLOzA3oeDY4AqObrZv1m3N>9#Ev3tR_jKseoD$eH| zLeBzPzGKfd@|?s!l0gNb7x2`BM_i)ZXmf`jn-0C$FT9SUZS;fIeUFj4m zcggb+{C)!Lv>+s8s*pNJib5Jwh#j7BD&%7h=}jSL;2~)VZq1MfiZhZzM#3{ng%rW_ z0z7*V;`Jgl^>!8V9y}E1eTs7e9ukn?_Afkr;Sq5nkaemr5%K~&6h~ZNz(W!iA*bOX zZMX*4+Z!y&Qy;FkAA7oxCm8=Iohb4|vnPW*lkkr!LU3CF4>8zEAsg|p9X#SX2M^^S z4!SHlJ8F3kkf#Iw5o;0B8y?D=xWYMP1YGZj@UM;v84nMo^Eib}!9PbkM$J58(I5zM z6)%2j2CDihWR8U7J^6#g8HqA$c7QTAf;`iJrl?dA@&;G+L<*siqAy$#(hmF<;6^Ue z@!G+4I2UAI|G-0fEkddxxW0#D|O47CIl7#>PTgxDc;%E2hOUNj_9wTmko9%}BD zAQ|mrcqj+I5^EaXNX{bUOL(Bh^7p$wW{(JJiHOuZM52S>A)zP0^-jez7Bbb2B2wt)>r#W6X*|!klx(xHd9D0JdTh}9CCs}Xqa|{^g-Pc zH}R^1N$|wsx8Qb!LmHtJT5VKXecTWs_kjz=nNArU0}r)G5%MHFRQ$zoz29cfI`V8| z&tdW?t-nGZQhkb37p`{`{G$qJPoD1h=P33xc&rGy0M~0B{xyY1B>E#fE#VOt*@mRJ zWCv*7@sBFtW%BgLKWfDygv`Qr@Q7;$Je25jaJ^q+&xhoBAO9S6yAdAB=s^nk68}u= zmThmc-^4{fd;oFWl=4j~FD@E9Dd{l45`upYo~R^T#fz6{UJa;IfT(0Ci5Ur8T*ZqI zPM@xM4Is}@c}xBn29J$+dMSX3YQLiRjiVpVbA~4o_|HH z3`HshkL(Z2|5w}&&EFn0{gEnKPW7<-zr~%Ig*lBwi)~t1ezEWu7upwu;s{N^Ut#%w zgymn9H@5_JJ(}|>(V<-RMg)xv8Wl7;D0Ny%6x+k{bM_Lv78YH@aWL9oxP!fCO^JM)8ma_+Vl+(9|F zt12i6hUyn)SDbFIR;$#6QxWU8PVN;xjlvqZ4@(!R=^KM;3!)uBc3}nW?XyXVWmSiv zH3rRi)JOB3MYeKiK|ji&@5~kOJY}yo{ex3_JR?pIDaKr`>Z3` zb*M}=>;={A-F>p_7QIeXvyS-AqWK&#n>7bNLJJ-h&0eixP0^#Tgs)rU-wion< z>J%66r@YAu6>USb3-?8(q0qJ6yQiaG&XumH3-r-F@uMY)gNZmFosYi9klLl1oRYEX zZ-#~D{~4N(Sl_X3Zn5W&LVqJ;&4hSoigctO>MF@*i%}uq>$OM`k!7a?LED*NW?}Zg z@=;QLb*XK@xESztz%JZV^)4v%dCKmnVqElXU3k&=zMW%z+wSz8Re+rOJ~a#fgSOkW zTA>94eex}#Gy3^dETZAUUf^ZV-(;V0!plD6swJlbDze!3)85sZPDhLxS00_%grZeY zyhW!qI|n^Yu_#GVJ>ucWYIbL$Mt{eWL1OmVgV1LT^~tjoo#jkeprt++eQRr!4WFWK zaa+ZJi0&j76{%lyB=U(X#XUq(MMa?!*=3P@it=43eP`xzlGU8l6Lo!`swC?B`Z=<_ z)ROHhxN_FFTe6l`Fy2aDT9Ixcmgp1*qEk$D_0sS#OxG`}ETD`Hs020C4bl70&M7Q< z`(O04pCii}X;A2T`b9&gA|%b*sPiM@n$Y~M;RO@rkP=$(3{4&a{<6>7m0i&{#tbusLO)6=RGNBk?%D$MrrbI>@8z*4LR8s%q0^; z>W-Ugbji{H%2G{dT#=I@f+a z+k>lUJA%Fa@S00%Ki-DolPytZ@sZ82{B!pF&1d@lRa_iikd8vyU}5z03EE+^_$9{+ ztD>TTbqmi}|Mn-b=22C46SN3dX6Eb#7$tVwXZ!?f>Y62|jlEzHMzz7!9=j$+wT5yy z6XxN)gX-F8;am>zU3X_U)0-SSf-HXVv9c(lVlX-0d?pInGT0bYRV@$YdlfzVw;cWS zR>d6D>l|IZ7L5auUg4LPw^FmKQmZR2YH47wqPz@zXP!fK5tB!YPT`khLMOT^YBon` z)M&3%S&SMxd5$IQ^9LhC^Z&vGD72uLh=a*_L4Vk?_JS--0=HMR=VxJZ-OD+#6;$>G zc1y4iO)a;$Sosm5`8PrfLi|u)m=}n-IeC~jYy;J{g7SBS7o_+>%O0`VW)+9#PxbT3 zwg()6E=YTyO#-=A03L|Q(?xW|tg2Mc#c1u!M=%NM`eV*I5(wtfBI)q`Jefvz&DRvL z7INeNnTg3ftjv}6larj-DPypxgboV*%pF*UGfYNc1iDT}e4ls~ z=CERiu4WePDm(qz_efJrj(L|#J2fGsHeMtWKPz&^G1H~7U zN!AM54G%2{H?wcu6(+ke3PRScyMk0N8ZJ4S8L;j+`p&!xcA*6?9D-wJG@vJOXT2(= z5#!Q}RLgG1B@x?bz3vdAcUCUSbsP+M`i42R!+a)PchZTpULex)rbSk%w@3{GkWj_^ zL!v@jqv4_8q#kAkhY_w8X@l~%ITgh=^Y`p-(0VdJ-DMei;8U~*MxA?m6Q*mKW~QvH z5~&6v?v+w<>{?YtHz4>Z!-9i5QfDs!k;! z%b;Mcsja9h7zSx9+#_F`&#b-z!-u*Fmp+%QLee8lIrORzISMYvgj980GQh=!0U3p5 zGB6m0^$kX0m4eW_u=eJiT}Nclk!3H+G8!RlApItTP7noimzGzOIcr_wm1(y9>zb-_ z{a&{#(?YkBUx0BAcGL{7itbG)d$AXcr)*o;?9>&ufK#;V@CVyZA^ATEIn#h^w|GJF zA^E4J)HPGN!xOsFfRAj%HBMlSqtP2|K*eREkB&46!?A8$5X6;BMBYcolfxnB0_0 z0o|gxeSWVLDtQhoRX4|7?WZR=5I2%A#r?rg2a-QlM2b^ z;B#vk_@V`V%Fj+vxul#FgKk#w#STYOW#mW@ce8qy){r!m4&QK-rMJ>2AfN#8T68Qv zlp?-4Lf?Q99~Ft#Ftg1_&q@~GvcMNeqD44=&ILlnhc{?mtHwex)WZJu@>WBil+9Z{=_ISbHeNx28}{x#<<+l43HgQU`=I zs4lEZ?((xIvaU&csbh$-DoJV_p#0W&G)p3pAHJcorOU6r3`|RCZOxvTPMJropfoIz zEYMEKNzR0v+E_QO|+zgwf#r_%@3+}?DCYX9RYxXY9yeaDYcj*OtZR8SNJU)`Zz zN~*xEDscI;lQP*lE+#i7D=sq`+95@pWzEXT$Vksb@8wP>QWH|sGiC4UtUyN*+*O$t zg~~0hjII)*+><(#7Q=0gkJ9>*G)bz-xd}8jppU{wY;v>D<-97OYX^3 z9Xq-_?#Ghx$)uPx3@(xQA~Vc_5_Baz;Da z&a6!@d<+~Ps)|YJo1Bmm9}GJXr4rd~+qNCPdfSf1ytZ+18oAm~ifK~*X)+V;Nc3gV z8RY-NKWpA%{`SZqI?AW50>w91Yo&ToD!f@eboTU3mtl8tTDq0MMzwh5#M<^8=azEdV-Y+X`p{_yZjPI>*u#=mF5l-5?+s2m$Ose;^D9 z2L=I=z=Oa;06iW;>5hUM1H=PKKr%2MpfEZCH37&3vVj~R7nlOju^>9d^CXZ5JOva0 zbRO;*;CWyk@B%O&SO~lXyao{OH`#p~?z_Ny!27@l0G*)x2%z&MtARBD#i5H18hi%O z@e4X*Q3z}TC~Pa-?Z8f8H{aU_cR%nAa1b~Q907=)uA}^$b_ah1jsquw)4(sl8Q^!| zJa7@9IDfKBD^1sc>*NP2Sa1dcs0a`pJwa0qs1DQsd;z*&3-0Z}9YB5HZh#(HvI32P zCIFr7Zw9mi+5zo>PC#dXHrRUry@4Pg7zhDKDIWmBfN)>{K4a3AE~L*YII zi~#7MQ8X|Hhyf^W0^B4Zczvbw%X;3H`uL4GITK%>+qT=IA5_SBG3CgPr$1=++=k0v z=GWg5yRO;CSHD=9(>veX`-tNz`n$@XEzbJIusakNUW z2a5)Dy6yERqqBYryBcAO`Cx1Jx4YNP9<%tv*Bd<8;o7x7v`hPL6fBsZa98SYJ%**# ztG&1L)IFQ>?i>5sA1Xl?cVc7eRpZn zPYZu;FDB-Z+fR>J_R#1J_LygmyJh**yimF!yY{>`SJ*U@L z-Qoq`sy=sjOI<%ZI%=u){(k&^Decba~`aV~^?%<1`6j!}) zVs+)g@m;>m+uGpIH-BE`|9*|jhoV9+1-`U4pe}B=xSE^mRb7u2yNvF0f{ywqm#^@PGL!bP+ctHK;`I{eq z<&EK=6@0MwTZPS95w+pQEdhw#UhihLu@oe$% zUq9|X_QcFy9|sN1^XhQz*g)H)yPmwg(fJ0}-A~pJ%v-zpxp!Nq4Qc*(uRFruT6p-= zh7s>fYT9;qRO=$^xA{~5>eD@X%+J5JAMr%un=@11h_XEY)!0h|`wlu9wzpQZD-*7q zT({v!VBdb#{r7!X?LxuODbLk-chdY0zdULCJnq|1mQJlw`Ti-5D!ue;JzMk7e0pC= z`{=aw$yQaGUf)0T`B$DidFX15^RwRiZjxWi!JXE;^Y&9&vt~}6SoGEPA@e>N^4fj3 zPk8w1r}oIRHG2OO5cZcduie%ub&R0?Ig{v-gUr&6YuOj+))q;lMt=@*w1I2dG|5zJ5E>0dZ0=5O3ys<{-)j^ZLV_1 z>A2ko4ka$!F#MOFedi=~KkIXD`IcQj{$8B>hS%VVUN!GHy`|ZdBbDyVJM?edsEG9X zHP6l5wffFg%ZoFQfCuXf0*M9c&`RRYX z^~Wb|>;3)Pu9U-f{@So(-Q|x@^-jFMW^+sJwm;SC8oTZA+5y+zUOn$x(`rYbO5F0m zPk~)xpTBEV?Rm>y@`<%IY#cOs!pj#vUb}hRZ+|RG3anVOU((jaD-OQ3VeFof)mtnW zUUXlRzdw0;X-dS3Im-v-rEFbX|5Wd5XIi}XOs9Xoc{k@kt>n5hA8WDr*^gfwy}<9; zT^U;!pUjDveC4x?#q<04PWWt5$MnD3*6liRncv$h&cwcTw(7yZpMA5Z&;IB;yT00L zQTMgY*IZt|BCCE(gM0hkySo_hSP+uHs*Ja6|q2lEQ!x^Fr2 z%CUc9>wnUzhE3cI2C%`n=uZ z&xeyHe`cB6p;NQM_upPKz;fG_ZcFmNsyuhjm>#h?>q1~)Bmq-_r-3EFa$pZYUn@Hc z+yMN2aUa+U90G0tch}Oi)<6#+3>XQd08@ddfmeYQKq0UnxD3>SF=GWf0CpfA$OdKt zEnwu>Z^JzpI`e?7zyaVgP!alZJJ1>k0rG(Lz#iZf;CCl@0(M{+FbT*5mH^9voxmaB zJm6Coc?UWGc3>Eg1WX0y0Jp=qS^z8s)&M(!A|UVY>f=mOY*l?{+j-~ezLSO9}; zDNqRP2aW^h0eYh9cEAtl0@#6JKnn0GuoBn`901M&^GT_q~Jb^G^ zB#;7}0q$;s^nf0~NFW863Csg_0*8R}z@&Ro2fzYgDX<>c51axn13rEzC(s3m0+N6w zz;a+ca2z-f_%%hH15rRcFcX*uEC&h!zh;w)0XMr0)_2$Sk&>9Ee7KjJ<11Z2%;Avn9uoE~0TmdlA(z*a)z^^k2cx?^gswO2FM0x0&fB< zfdjx9z^5bR4|D;-fRR87Fcp{syb2U{0zKf<8D#@n09}AEAPL9=mH^9v^}rtBC~y|I z0aWjT`~$6l9>5qN1E8-QEGK_g_yKyW`~qM(a2&V-_;f>>KnEZMCfdjx<;092yH{=C0gW+EZZ2E7;d9<^w^U%-#(zJX` zP*SQQt=bm!6*7J&OiJii<(-nACPCyM@}czKg?QwD=2Ph}K-{YMxqCex65WV7Xd&ir zD1$%p6}St!_66oFdof?whq>`rGR|a+MLdAI29vP%2QbG2T7C;z0*wyhNl@U9?@&&l z8uI@HmEkaS4)`0${2p^KAn6F^X29s9n8yK8KWN%M;DKYBwhicwynhCCI*$1xKvx&! z%?s}6xfabf&!S}kbj6@ulWZ?y;^dVs?**KYPi5}hq-i@)hDl$dp95~+4_yQ38j6XV zH{AKFHEnJobOLhgvm5hf)B|19uoX_+{@5YB+M9n%`E{)<(>RYb=vUYV8UFe&(*G(= z^l;U}M38>PBHwg1gS^TA#OK1R)juuikJ6?%uE;a89FsA*tDht9T}qQQ;U{IBuc2QQ za)eHN;%a$OhTj$^{kO-&Uf{4Jc!kQ=kR?1Hiw)MCg3~tD5%ZKX{(}Up(+% zOzR64?JV>^1{3suk*_!(i?#u6;ZLAa4U4uIn2NfqjrQ<7WFAq+qIJE^qBTH$4+dt| zwP-&AD{-PBA8mJZ1B*5WPf4r>hC?>>8d|i2z-H86h*g#$89Z#r>-+04AO8&f2+$wx zrrFP$HW2kV33dM(>Th?Erd|3K{mxlDDEhmmrJcizT>ilN%5}{5Z=kQk+zXXG2lMm7PnupsbYHSNK~ z!(u_-5R0~~uSI*VANXL=pjW6x`<^fg0kSy-#6dp2AfH6YXAb1E7V`NC@~QS4k)AF{a)%!hnpgAfM!Y=L}6 zLq3}!pLZdj8IaEq$mRk8@>vY|bc1a60@EO$j*!bgz#Pb?ALMcwcm}e00CK4bxm1E& z76IKMmwiA6WYZdQ*#Xo|fqp?Q2Y__QW-DZq!LoTNRz5sk75&8b=x2-2A7pGrUx+?7 z1bysyw7D7RW0!Fs`wrSy707a9Yw+=h9tT=9JMbv*7SJE%vG%uUxr3zav(Q%Q*Q?yG zT>($(*BZC9Xaj(Wz#G6mfUc3~f9cn-0O_|t=jm4~^pAAaIWPO!l#xgqWq%!Ir^}8$ zp8DUvnpm_(P0J#+Gz{h}|E*^d5Gr&FQFNXmY8e3pr zOTHg~Fa2tJ0{?Iw#5h&~?q%rbkI+xLrXbJsYcFI&S9kPVR0n2bb#3&|L^&5Srt5=l zl4lg|Pq|m#`y1mR{rc!bL865nm3{0B&1#>b;sGg(NVKa% zkWW&Mr1QHEVlGzND?^7<{LFfeCyA5^PjqB74GQS7+d@!!H2DU?& z0#GmaLY{3g4*ZU~nTxUDNsI;KiV+W~g!cM%sVkEeJ?I6Y1YT z+FnTa8(=@ueZtG4we$u*q+1i?V}}|R?Mq-8(hWhn+iIiVsbkUNZ?kCQG4@nKx<`N& zNP8C2-iLH&qy6=7h%x#ev{kFDr&XvM`ZdN+`u(B%^lJiSLf7O}=^uMi`Y&_6zJq#= zLEK|puWb-s5hSGdq~oODq}z0zZYJ#j%PQD%z*OkY3V<${K_b2Jt%O(m{zvH#1%J8@ z9hd$Jp9-%wr32ax{XBqi9(Wj-2mA&2qV6XEPXT8EZ`g>5z;xgz;5snsJM2dQhky$} z0NnpQ(gW53-vAwY{D=1J48R0X0y*Ws)RWYXB3$(|$76yz&Uz7vP zDuS*6AHW9K0etrx>@R>e9_j-vG2Zn72LFM6A9xsj?L6QI;9j(i@xUACLta4}sf<4M zGhlWLi}o7&+WY3odfSWg(y#a)(jRkK`kRiB{%Xh{^*z+zQC~;>8ue+aKl>!~|9yKa zaf>XI(*Lb*%f6@@`h&!F7VT&5H#ej1sMM;Dya(e2`PH0i{O8jDDP%}jgP){d+3efV zzNinnwh8rBNzzy#bNW?@+rk5=C!*2YyKOd0KGts#fGd{AqM$aC#|bxlFQG4}3R+L* zTPwhq(k8yDe&0o3LaB`W6#sDbLH|L1HGYrkA!SAO^=v@R724sq59kiB#khoVy7eWz z6%MlOXM=4Ad!h!$kn7?TB)Ii@yClcrOL-F&OJF0BPXA75wkbkZJVYDAPC&S?yt4;%}DgS7;A(9f9nL z`u8juXWR)HX9D`S1N#Mumcn(uj{C~_=pTsseSaAzgmq~OkIf&Uenp(8bd;v&7 znSTLdQRW|jVaVS%z<}eB4?x%DzhxhI_)pA%k&h=~59FX+&7qfc^}^UoWjeJ6W!oig zX%nDpmGE;f?5ftVt9+qzeSrzUi>!a~EUVKMC7iS>MvMz*Fb}GYINgwT9P50)S0s<;Sg-B`{jF?w??7*sp#6Mi| zs6X=0TO`Xq6YD7S>v`B+bk*!8+W^@JWFL@iKz0Gy1Y{48EkJev*#I>D)7VerK8^V_ z-qTo5<2;S=G``c=PUAX_=`^0xSWe?Ojp1I$<=A}{E?vv6%JO}WdhkL$v_?G)fn2Ad z9^OGc>_vSb z+s@-YdOB=jl1l6<$~|<*OZsWNqU&wwCWWi{!%6P5FQd=ixm%EEEzq_}kEfz7o`>yC z*OoWsy+-@+8n~~-E$uhfLuEV1cak(zuYYjeo+_5#ZwOEhDSh^AIB#+z0jm?sOPuOx+9y^9d%Q_{yk!(h?7s*y6JCSTevJc5N zB)gDoLb~$z$~--Tc@15okv9Emv{87q(PL$Qbp?93`5I&ex=xt$grdDw;j!-H<1&u2 z(|dd_^WllTnT33jEUItC+C5}n8To1j`3`3JcH%UOxh@lblxc4MROa)rRmzg)a5R6T zc^b{d)O@SK07+jpN|v)0^5})A)gZq&VT*aQ-Fp`KsDS$`y|GpW{h{k)^Z|Fmo!1s? zS3oy^%*lXDKtKT2et_eF7>7EdFGJt zB!|Tqr#9!vJT~CIN{t!$uy={ZcN@kXwqw1yjpc9~dxXoih0E~_bdR|0O^`gFJ|_Jq z?vVb*82hMRsw3S=<1r3!+G7sO`?Q{vPBQ1Q@&MWr#T>!9xb{owe`OhN;_8EV6i#vI znrG0P+geFEzq~+(Cm?@RCVhL~yjk*4_Tp3ESrIfe9@G42DxlU_KI8n{%lX-MLdN|X z^+(sgUr7IO+^4H1#v4lS2k6euPLgJRN0cA;+9O@s?|A_-q&=Swm^;wE&m72#_I{r2 zE%$$xLQZNAh}tG`QR{TQx5)J3d2TWe?U=&V{=)d$(q6CiA#Ax7a$Q}m=cx5{wXX9h z*T3q|RzXLo&6bVUMAmABH@7asQawP3BF_ zqfVp$BiZQf21{Uoa)=kLX&TRR{ zCkFXRM_w8uFFyk>B0u$zmxI8k$j|4<&qK&hTja$Hc{v0$L0*mnFC#xAk)Pe1pP7fG z+=jg;vZo#GDs7-MXoGREe~tkUeGA(g7>K;@25jHKCI`AB?rI^%Z>4QMA{EB*8;q=R~=eZU)Q*Tuq?9b%def9Nn{k{M$t;y2bHSJr`+AOVMhZkZj1ZZ!I)@f-?o7QS+UArUtoG@S! zKzot9fd;$eIxekwPl9gIdM>SfzXJWDbzNEm_eTG46`(a7@V`#mX*2aU- zj|~H8-a`8d4+6Be@F+n03rhjoWB3Z7eTHiQ?KRvB(0)T0Kzj~30PQ=x4A9=g4uJL_ zHUhKF_kOvj@j2YsAdB`CKzkci zg600kZ*Xak;|YNFIerCbuj4C#_B-AKXwTyjfc8D=V{AJaiFJr5i}ub4j1eQ{UP%4X zazA7XT-p1m_2YmqLo7OedddS1*=jon)FW}L;qv|Y5v>u84+ z(e~)FAD2AzYduMC%Q3y44KfYG8h5&s=cDMK8Y9mCEB)(ZM`hWvTca(aUBsh3R6rXD z93=A_jk@+ievNw=Cu3#3tVF$kfN_D&HH@qRovj7kx<|&{g?^u8tDj4FBR#tJ*$3!< zq3?7()mX|~&4W)OKGEps*W0?Yel?MC!aK-(o7vPyF+S7;kN>i#_8!up)X09Ii}tC> zug)8MkFwke|No@zyanS|ZKPqgmq~MD{eC8`y^#HBw*C@;v8^Kb9cqO>vN!r*)cHpd zQl`;dKHB%B>oKPN0lIMDKgMXVRqj!RjnIZFZRhw4nf7MTKmbdUB>Y5$b2C0y5+ zxy`>@UDiE~Rdgl87N9sZuF{xC*9F9-*q1Oi(p8A@i~Pzieg;1BH^hCqXkClS=q}%r zIZw2wtM+p@-6!L#J}>%&XSUth9vF*}9@zji{?ph`<35eAG`7;XN@FUGr!>*8viWgPNLWr%>B zEs!%^i&0Lxr{Aw$7%t02_61#){basd^L%r`J<_k%%kP5j5Ra4I7OfrTOmtm3C3$qd zSNiwC=C^LF*}M?cvfFvK(}Nq3sDIh>P~IDNkzOW*+7~ zij32m%R`E|LwVBN9aO%_b-fVb}i73sSI>pldh-Uc5hdDqfUrI ztqnyilKMdNNSgD}b)EIvlQsNDzm@43&n!`&N$IJz)F95MI#ap^`K11E8T#~@+p$L5 zAAM$~EJK(3WSMB5L03hK+~@kgI1{_)vXm3)6X_6LbBh1(*I|k=?on>kd66+cOTX&Z zeOcagmY1%k+}71v*nJ<%{zCf;b0Nt0gDMtn32gHLjU;_MxYIASUjJKT=~s5y8yHh7 zBi!A*K)-G}7))7Fe-5yu=ys9&75t`eOEkbLnbdHW}5?W)W^K^RKgw7x;yF-5#aW?dT z@_XAp?49zQ`C4bpb#U+Ni&&4kgmtxluzm(C`xkaC+QcYm%%%z!tpNS>#mbm>_+V|N zDr`pB@HKCPEeLeP+?lS0+@}98_O5?moAX=P)N~!>wlU97=52cDtt)49Zl~%QfklS2 ze}bJ)sjB^KfAoD`@Egw$PQg5n=+ruAU?=IPbu_x}=5|Eq3+ZY#R_aMOm$^8M4inPc=pl7cY4YhGXbt1q;aikT2aUK`>DINN)F6zfJ-pi}D`^5Cg zf$jILYtp8}(~*(GN59v1@zhTyKcq#Enf(29(98ke1XcnN9c{B~rvMBQ;#qp)-5j86 zXdBsnVw+;^m5d5p3(?+*=E6k!k37JkUs3VGtMx}5^7mLQ!~I$A7u(A4DE8X}rT?>P zGJY^8s$?()!IY=lC7Gxzl7Sa`tcv2z3NoIOQw`Ah0@Su?EujuTvZ45Of%@#f3+_EY zBftvy0Vtk$=RzyE6vrPfWe@79p}P?GU{=v1MOts54`2iAKq$~32nPlNg8t;uFb0SN5&)>VmI#akQh-zdLx}j~YZlyWAQzYjkX#-HrU8!vj{!4)S-_J( z9xxlAdZv6l2X`Lu0x%y~04xSx0$u@L16~K-0G0yFfe(R?fKPx`0L&Zl4u`QJmIJU#NSI>O@<5#WM-yTlSbl19f_QH=^HGk(f z@TpZjcjfwo2WQu-`F*pm$1i#5+Nk$iuKK9ejAa!9JG}DxzQgoP`rf%cKEB_3=G1GC zU7PyN(Ehn`))%HecOd!W%d0AAufFre)oB}=`v3E2zs(~oU*>$(uG_f8gpQYjK_6G| zT>bi2pO|_Dbjve#br@W4d;Z{GWhS0@e{UP~#q5{+ze4X3czW>KH>!lpp8X1*jrX6PSB;+E_n*D$g;8fB zYya@cV-%5x`o7JNRbY3_{==iWW|Y~{F?3qJ4h z{kB8TJm2Y!N4D<&EVBDcb0!A;zNhZ;*RR_j+t|FVf2|G+>wJ1+^_t$j?x@jZU(gBf z31chN+I8oKsU5Fh^LxGGwHc>defq$mm#XznTKoSob{FtbCfmA)ae@aKJh*FccMUGV zU4lz+cXxMp2F;)u+}#KF!F^zm!MX2B{psv8_ndQYe!J$`wR+X6`m{Tw(>Z=UN4A+Y z&t7c5?nD2`NdsbS_@~*#^zAaN9`Uq7={`}0^_@LtclO9N+w~~5d27bw9op=O@XM&n zm%?u!$!d5P+Zn%Fq`Bo5T)SKDOUX1x&!qNk z9Xa97Y{RSGPqWZFYQ8k3{z=>^y8n@M8PD%5(DLi}f9h5mnqz;oaOEy7?A`cw^9y4S z2fxaDARv0T({2C0(R}2DN0$<>dzPw6|3*=^H?+^UST~~Fq??%v7HD3#ey{T3xT z8nI2D>8*0@DtXE4Qpr{^p2b*q=fmNs^V3D_TK96yTv4WMp5Fgv@R>8kjt+^EYTf%- z@!I6eT{Q5wC4*xPUA}x?P;UF|1p8h2Pm`X`n$n|BuI&CZo&_(>a4Xa17MCMzxDtI_ zyr`d_`*isJ_q$42QkAO^(>}Lg(cK!c7ksFlEb_XVBl}!zu`*t%Usm;v{N_xGBrhgi znsGm={r-OPIhWT~Eb(gl`W9)YZ7zKKdEW1LVyywYV|$UO2S^YL(QQsC88vp*CA>t=b;7^J)*&BI*e$p;~6OqH5LETB`L@ z8>_ZJElBO4+GVw;YW92jvGk;tN-d9Cd9?;=oz#Y?O;=l`wnOc-+FiA`YLQ}V|EOhA zE2dUMEkLce+Bmg^YQL!+QoEw|OzoSRx1KmttL0VmQ){T!S#7A=47Js2JJrsp{i*g& zEplA_JGNR@wc=_u)mo|bQ5&zeNNtnaVYRDj&(*%G#nzK^8nt|C71SE31*#2Go2mAz z+Ag)TYWLLMt9kvR_o}F6Q!An7uhv?vui6B)#cG??j;LKzd!hD2Elzwr&#UEEtEkpk zt&7@lwOMLw)OM@gR(qosK`$B-sAW3SGHmV&^yQKC+?TcE>g!MbT_PGR^)rzWBS8J)(OKq&$0<|EugKC%6 zo~nISiGE9()~0^p*_4%9IF?K+TZror?$&F)59|`R&4ij@^YWB`kS61wX&6SS>BC3Sr>IO zg;jyQI)SP6WuXft9_PuL{KADg&-8?*HguthT|J=`Q(Y*fUQJPJ^&}UH5*j*R-Gy4M z@N9O2A1-ulwx`yr=`K`81KAVJSbf1J_8LB9gVuL(Sqleyvf>wYp}2KDp{gZZs9Jr` zzysl3sFasysrL3K+Y`m>*h}}2@9&`%Oy`3>Y3%e{+ZFnrUiw%>l+eW=7`uYq*ux@ z+Tq(jB-qJeQ!eHZPtM?3SPR{*wU98$blGW=Dyc(woZhphQJ3AyTetL#`JmUywtZbH zdqQWXxKMIG&p>PCxtP6zGVu=3bLy2L=R1Vn}nX80Qen1E*riS3He_hn3+t(W|#6qDL z;@8%$=+Hr)sl)0~nIF5P#4|Q?c5pfc4?3{lv%R$bK~0%_k><^%FLYS z86U_7285oN@!46=B6+gz-?wemvCu%3|7B?il^j{LpP93ll5EWnwIuEVXM4KPFT*_5 z`aX1_yVE=a>ubAh;M>r}b{*_O^~!h#j%1UDgl65~@>{FRkE5}ov>UjrwrAjn4K8$b zvM2QSXBP_4MsWG{(TfmUL>27|LTfm2ePe|zwUpb-Q!;rLZhs5g#(dU`26jSh{kyG& ze${=AGLQ5U#6lHShW#?>8KK#ptV{!3=wRsPEz`AX13&6}cm~?9zgnn7kY`{KT_P6p z>*xsuYa1*yT^qn6x+HY#3Y_3M6G!TJTGoxRo~$FST&QVt&j$IiLEm+!U=h{0)65Ay z_CJ4x>QgpPty-Gg%HIsV(A$l7p|hb^&n6ud%lc)MXU2Q#T4+F8&t>=Xwkq0dX1!n=XbBYRGocRZIA2wg(ZgL zufl0umbdz3wbEH)tAD14I4A5w87;IT^w3sipuN;2>#X*-=$- zRcWRtYoKK1GRr~7+q{lP)25_-^P z>ULyV3(|SciM07#sI;Eq*+wtUiA|x;N3peP8<;2b-da7eTk6!%J>gfyWesoZsnxoc z3pMEF3C+_pwAET1`qW%Jg3B7OlZrdg54}dQtcFcI17{?2p?s2~T_L6mb&l=Xt4}n_ z25QAWvwHKg>TT$rXrs&AvYs~el#kA>V|(av+`hwQP0*Rmx^lA%3uqUzh=)ns2HgzZ z6B%y1fw?z$2G;g-p|p8CGY)6Q$DuQ>ru@{<@-Y^>fmL*Za)kW#Or2xEVc@E!5GpGS60fLf!O3Dhox{y@kz7mBwW)R~bU- zbvavBKximF`{lLv3p+HnmSS0nb)Z>g(+MuLDD+nUTQe8B-`A5ho^`zsUDxOoZe4+) zXGmiX&ic@Uv$B<|)j>}(%xItdV~ZHI))RWN--W8`@*yi6*Ik10p7ZFsM%lo8kv*YW zoRgz#brM^spY8|joLY-rD1GQjGpe!+{ngG>YqJip z4XoYM6H3ZeU>{FMt)U6r&dDEo@jr>;2FBAt*YUHjb`f0YMCjQzsJ#n$5B8LA#mzFO zzV+c~kJjDQ7Lj$7XU1c?!Y#B!|6vi&hq%zW>YiHBQn}D!cLFLu>9x|hL)ifRgG9KGI!Zt0#( zsG5FQZ;Qydz!M7I=(1ku+#u_eZt<4Yp^_(*jvHK-BA$@_!i{AmtmX*?=Xaq*%RT!m zfG3w5x;of}i;KCe$8|je*K@0%G0$^nOs2~^qRQK6O=@60w{v?sHtTpR_);59(Wh5j z(FdUy=0?uYWjYf$IqbtPZOtj;dIsA2>nyalfoC<%+q#hNKu;*8ep+f-(-wO|ZF%`~ zM&}DVE|(T;S$4@qe8EV z=11JXm!Wsf&%BwhQRuzx2gk*Cxo5MZ{BQ$rYb#h+M9NoHc~)PZqjxrR5&Mq1fjvW4 zzmv=4KxEIYpbxi#wxPFz$&^nU%`;;`mO4H30@(Y+mEWl!XR|Kt7k$NZgbCZXMwqa@ zy~BD(kL)#B`z(#(N!9M!55V-LO?6)-VtS7ZS1LxNlEZW~TwZAz?9zT{%iPz`JilQP zCq|eQ-s*Kwn@rw*(!%`At1v9WL{-e9_;j^4w(zU@Q%3fs3@rI0-wd0qr{ zy?^d!+g_`6)lK*F?b%_xjuQAeZ#lPrEO(3MUCqO#)DQXknMc?1ZYpmud3y43U;j;B z1f6Jg$@{@iS`z!A*`!Bryf5_L*^;I4g zd3>Y^o+F)G4_4Cl1d-oT7lnO!Eh6x9T($o?&i2Ct)$UE&|F)j!I{&JXw>+e}{`0eL zh5uUD)^Gba1^MAP0lZ@UYdvNE>V|7yUitnt?qA2r_RBks z`+1$k*Bb51>&L(LOC`5oY@RgA`FS3U{dru^{wx2#Szklje$t}pHfUd7v;N=XZ2tz5 zmi6bjCjakor!+1kGd%`76FIU{x&;8EzW&3Ts@~(b!`*-`l^ZuLt zyi573$=6%F{%hU;CV#w+eQ)ypN%v|^;OBb&<2tq%i{*J(ui5`=eY&=NrInY0yoAI( z*A0E!zUW%-NBfh6`YKG^>oI|!^Z&>FX1?kk<6*yl*Zq&{;E?hblNagy~%6I z{_<-5ulaetvizhv#^rgqo1R`nzJ9LrU;EegLnY-WBtI+Zp8fD2>+P<**I(RzDEsfc z|2QA!EAJS2TmPN+-`tN*DStNkWA(x)6 zZ>;V+9S?8vvQgIS$7i>}KkNU;aUQO^cX{}K+i&ZX7fhaBUb?TJ_1M2&hF`QzF*pTu}I#My|5}~;_-OW_D?iv+h=d+v+es>!qt5$>uBD4(&oL6m!xgq zarztNL-nW2$8w;wx?QE!Z7r>C6KU(MCTpv%pR~Fqu&}hcS?R}>_tgKUgKqWSNUQfq zTD{xS>YbIfRPUIydi!vvw0i64PnEX5{?h6NN~;$jtzIK(^{Plc$N7|#R<9TqlvXb@ z{n*m#ebIN%R_`xq^&Uv8cT-xu)3T=O9g$XV5B@H#-WvLon*Kr zL}}~&R?v-qC2hTrrOkH-uS=Wv4E=-B?q|W$?q}=dML9(7ke%ccSwg;*1*F~Ia>zY0 zowW5PkX1CFx3u{p%6;;40r&WGX^%gU_PBj6h}AtJZ98^I+m4OWwqupFy7o5|Dr?*n zY2(J=aB17ogMKafQ2jj8uD^fu4;J?L6KUg4N;_{4;!e3j{ms(mUyjqHou}iZkO2(&NkRW+B*H|=aqI|#gJD2K`wW`osu@sDrt`omG*ce`A}AnHh)oR^XHN_e`aa( zCza(j|1Z+!kAYs&=Kqw_#h**--=x1!+W8qQS4jJtDK^g%Y3Iot9-l*Ft9SMLvL>pmu*D!xx%mA^{c&PDQ)97n&e zwDYfkwDT^tv~?wrwtu2aJ6;i_?T7dJ7yGi>j#tv^J;Fbw?Y|53w@5n=7RYXLwk)G@ zBc(mxbdv)W&n73!r`g>6L2`%s^JK{Wk+zOe@{AlLZ5@G9FHL>gN?S)WY$$CV)##U# z_tZ}>tzI%|_2SAiGMcn{Uv-f5Qq||Zw0bY`i3~aK=pT``U5jz7w7LVO)$Jy&ZhL8U z8_JTZTT5Eq%2-}n-2(KJNUQrs-#|W;SETiS!+Fx?nIvtV;nL>mFKwQV(&lL;ZJx$h zPue^c=x32uKaRBeUo*S9ucg&}D6Q@-X?4#?t9w*h-MzR&THUquCrGQ?4V&?J4Ia-c zm+J9sm`<)xKbf@cii4jrx$EbVwCm@N)UNTlD((6?FRji|Y2$+FZ=gR>+V#+ren)I6 zPbgkb+V)kKwtXd~URwGTlD2)hFq^dPOGQ7Le5QVQc~pMN=<=UQJCA2cyM7u=JAeJ8 zt*^K|A@fL^H>T^aJHX^=o5k9?#F?DWvV+gy=0-sP83L%TMW@&!pwurGHe~eQ%4jg6UK2fA? zcUZK)HMUCq*V5vbrPVtvt&v;?<>lpO z_3dpHn`C@x<73NR@?%Y_q~!-otG`iN{t{{V1BnMnt6x@Hem3H1rR67(mj5oLt8+tI{w`_x z%ZbmEmOnvSen;Z|((?02%l9E3Pg;H?Y59**xcaB1t zxk~+(^sC5w>K7%Rop^k?RPmT{g^VO^Ui-U*7JnwKe}n#c`UmI-)BlzJBKi~P52N1% zYs!PFS4ysx`K4_~MyaQKpH$Me!$(e4Kfbj69nSS9eDQJn{f)H8A4|)>CvBbA^vwD}51n=hNR z`I5_A8fSkS(&qCb{wb-8|0Qj{2h!%dDQ&(}a+1a!mNwruY4fd;Hs4Zd^UaYq-$ZHi z4U#!E&VE z#$}f_UvlE!#3MH3Jgc<)IMVX%cM5IZ57P1E`ORGPexcz-<%kL=lKc7~_o5|?5jLA!sSlPlyg`K#O} zZQLpuRpS;*%bUsL!|C^>--do;`sL(1<>!+2I?+ekdSc4^GLk$dzs7L!*V5uoq{VL$ z|3e0=e~|tHY3rLPgXAD-^#ggl4YrWKDeh0df;^;tarsofjqb+XlD01Uy=j~OxU~80 zcd0GDmH2w%%ZLw>FZFmY;vI=sk+z=v^s~q(>Zgz+Wo&83J1mbMj^^@zlQ!Q{X^&5$ zAHd_)>6eiE^>_jLIi%$$qd!9jYq0tQrR|^2vWILTt$t%^`=u)VGIE>x_WSDgxRNJ)%e+?e5ENy&I`dOuoPe4DKe5QVQ zc~pM%a`Qizm(;&Oe~lcf{(Ncsb)vNWFp$TaOFMu4rFOMXWvTbbWKAdEE1pc+yk7FS zd>`34OX{PNigc4U-ri@XUF*|8YS;MqORJMxT3#k;=XoM&^}+CFTdz#89 z+Ky^+wECsxco{?5c72Qx^4U3AA4(e^EN%QMd072v!~><(YbLb|ea?q>_lM(hh2s0= zuX35RarT}ot2dH(Uuow@Cu!$La~^Lb?fj@tKdH3!#g;Z-IH{%jd69`~1V6fYyYsb5^`e?B?%AN%)SZBxiR1LPY$9w48}Mskm=D6M{O zsgLQ(nn}i#DWra@BdeY}?aN2!V3-K%Kbfn)gRPQx@f;q*U<|?~I0wh#P>ec9pGl^A z;qd-!*S~?m7=**8yT|)uZLEU%FgwP(3c9#`NDoPdL|H#WxFSO9ZiLiEPS_@j$k&k9_C1F#1MU?Z%C9bLU^cpUfR8eEE1u^gty>c7K_cnWvn7Ho#~umI-36>VL;1vmhEU;sA4 z2>4Y`40b)<#ETe+ZLmBRM_6W# zSO}9~Tnvw20^B^W@DX0e3pfaSVI8cB#V{Wx!}xemZ`if{x)bN&G#rloF(anLu=uHk ztJ5F5qd!){BA5qLU_v~s&t13m?8XH+19M^~jEdp#Z8JCiIbOyyxF3JVcGw(CVnNJ| zsWB!-!p%+Hd~0zW4#V!)0UKd042PeaxH{MI0(QpMSPqM!FJ{1Vdf{aI?-;Je#W)4W zU^+~O-y6B{AMi2W!G72cOJN~QjB)VqhOXW-JdXQuG0w(uI1FQ9Wc=8`)q9Owa2+nd z8JH6@;r04%`~}>L+i^86#^Kl>yJ35*grzYHroluQ8~?25=D&ss{9Qj5zOL!|Pw+7A z#@v_%f3M;4f5TPPU4Ib{!+uyFYhW}Cj}NQ4@wadfZo`o{5X)C~`Nc68X2$Q8+~Xhc z2=2iZxBxq10OrB07#$4#nnJA1h)hOoK@=7DmS4@@~E$oQ$Kf4|c%{SQ7JK zR=i!#)w_(_a04#HnK%ZAU<+)3Rj@4nQ`Xi03(w+F+>RS@DbB?K*aPcgHOz{_i!t&#{t*_{jn0JMIZc8+SU69pW!{6hU2h3w!oTL5kHo4^16D)@L@Kp)w<1Cznov}66!K#=ZlVco=iZ6@1 z`Va8{?!fst9lK)(tc0a8JtoJK#a#V^xD4mvI2?w)m;t>o40bQ->UF?MSQ>L<7EF!_ z@MsY?elISS6)+Q~!nha>gY&uiK{y#lV;}5-HLwD{(C6^m>(K{z z2~T5R?20w80v5ttm=L`&EPl%4=6Qzqa1xHf*4PBAVR_7mDe-u2S9d=y!8te`%Op=kYl1z)d&}$KgQiiRG{u z=EO|+ExVidJs!s0I3K5DckF-_u@t7l#P}tftN#`s;cYyI`)~=)!SOg8Gh=Fuhtcs| zRyW@<{2hP8Dp(euWpVlU@Dv`xr8pOdU>|IRwXhPF##ERX!{O)5Zr+D@3)kZcyqVGE zUBoT84u@lZY=AW}CuYK@8C<I#e&3hd$U=Xgx zQ8)+#rGE4isSW1AtQa3-qF+jvUjk!cWW18XJ$@E9;wl`D{joawVIqu;_maDM*KrLl z#Rgatb7K~af?@G&GFR^?Zorke0B2xZY=$MU0LI6dc;Cm>zkzFU84kmKSQo2dTJ*t} zNnO2%co=u%T%3xnu?c3!^cWd`Byn|b;zjI;0ay|X;={yl+%4RVTX8CmMQ`-NCyCtn zySN*-Vj;|haWNV`NyvC?g^jT&=Eb-e4W}e<yxBzEh zckFp*CeC&_i zu{!!89}^iVKK*Pl-S~7E3BSj1@f-LDuExc9IJ(Q*jg7Dtmcl~#Et<=Jj~DO+uEd4d z30q-VEQ(1mE}n?$>L0*mI1l?^7c7YdF)D_`ol#u9%{U#$V_R&7Z@gUoQ#_9QaUssc zx>yb8MRwz-VMFxCvRD+8U|hTy$&EjSvvD%E#wJ(-3t%#gk9;zBq$d$w-TnAGj=>?= z4C`TD%!Y3xxH`}A81BQRI2Xs@5cJ1Nm<;3Nqwuc&ZQO&~a2k%oPS^@Rg>&QI;2AuE zGjSp|!8({8ljGH}uHHHP4S&UvI1qg?1A3wTa;d$pxuyS_moONEupKtXxj#bQ4-;uB zZr7V;Z2U%Si2j%xvtSeqiwD2C@jLO}SJ%Ie!?8a$M1L%eh4IuEH~tVV$N4xOhhtN$ zi%Bppp4FR!Z2OL405-zRm>Ms9a``844KBq&*bBdZbon3fGM>S;xC|rWw}0HYc{mNb zU|T%-!Q~yq={O!6qCdvKi1x?2Uog z4C`S9EQ!9D0TZG(hQ&{M^O~*W8Q#O=xF46`92|{v^gEDVRAU%7Ry#br1R$6-J0hOMwMR>g9d7qek9 zjE|A$LAG3!fSXQhhkrBht07DR=^^d2h(9PjDZpH{R_8_mv{>=;bGj3LAV<0 zVRbBl1u!F~#CRATzdd*JzsCo76HnnG+=An_XZwj^f|H8+31<&FE+<|Lx8BWEq*cZEEbF7aQ zuq5Weta$s0Ti0bgf_rcSuEaSw1&3l^Y>UmXI{IM&%z-H}5k|)dxb?AH-+EktGjIeB zz(8z+^{_e?$NZQ9Q=m6`;m1dA{?~XPZ{Tumv{2idYJBVP;H*@$vlwH~&k#h^MeGcEx&F9dlwPJaOOEJAe~$BzD90 zSRZR(Ni2w&FcrqZsMz{XH(wJhhWRi#CcsGe{jMAL3LoKRJcE018!pHBI1YzlH*Aj$ zuqKwmLYNU#qBnZs$2)GFukkKk#bdY+H{eQ~ffH~5_P_vagq5)j=EBUF7~^0#{CwN3 z^BLa53wQ#9F$fpoEF6V{urs#CI#?BpU>;0^NijM`z<0OYI$z*Tyod*I2mXpna0-sW zKG+4DVLdE|#V{MD!}u5zzu$E0`+$$|HlD&mxEa^tJe-EZuphR^7FZqqFhBZY3QUMz z7zSV8aO-`7m+=hl#;v#l7vKaOfjzJzHo%%#5({D`OoeeUDt^B1*7rBw#jAJ}_u@ue zg|l!H4#Hj-fQ_&cmd4ze1(RYtjDTOSxph9ndw3p?lkrv7MI~P9EW|d3pT~NSRRX`FJ{1m=#Ag6xb=O&hj
u~|jz+u=A+hKF8ffcYI=EPK(7`@Ow3@xm^UcBslj92h1?#1o63K!u79D&`j z12#l|ERBUR3#P$17!^NVa_f78f8sSfj{EU9{1s>6Bpir6u@yGPDp(ftVm3^Q@i07o zx#-sU9Pi^FcoKKwW?X`Ea5N6aKx~6`u^JY~{Fn}tVGN9j@BeV?e2KU45+26g7=){F zE>6Xv*caPiQ>=#Nu>j`42>A7aTi0&fieqpH24Ewsf@LuSroipzUEPg12}fZs?2OSd z0{(f{Z{b#4k0WpZ=0{(QgHiF~ zX;<$Q_QpW0hUGCo`eHncj$co?dhhT7-o$md9D8CXtcayBHb%imCtdy9_$w~K>gb0V zF(t;vDERV(tM?Eu;c48BTX6&qz^Ygdz0f{<$nK|CjyuodAnb*8uqqbAe3%}SV=Rn} zSB_C1m*5<%k2NqJM#ry5-S~HS7mTj2NPjz42z!*y1GyCPdtRXa5|31 zPS^@R9B_4B;Tb%F+i(Le#F;n}2V!Szjdiga7RUS;8Gr0|>$rrcaUTZbMqGuBu{OrW zC|G}=t6Kw0VnKYo*FAm*`(jtjf@v^3e%a&39l<>~4aZ?W?1p(U8$RFd>fFcQ@K>yd z)iD9a!oPO8@sIHep2gWX83VBm*2QX=2xH@$ov!{6X+*beJs4a|dC@$(K> z|8Km2CvXRD!WFmx`(t-(fHg5EWu@v~@Yn`7ejj#R>-qs0L&ny5wsK9#=ifx?npuD6L;a>U~sW4Iny;8+}rt+5G~#=@8q6XEwcZoUtA1OLEa48j>W0lQ*5 ztcv9@3#P#+7#1JRcJtrHgSZnH<7^y&J+MC3zY~cI*!31 z*a{nCO{|E%m;qy8M0_@#b>LCli_3974#7Uy7;9r8%!LWj8zbVkY0Qh)@hl$2b+{bI z;1Fzujj9oSQ{&1Da?Q=Fd}}N!uI2J+>6_B zK2FCz*ad5270iX1(Hp(+6SVM0_&Q&3_jU<8EAvb8!&%!iMONepmw2VKR)1(eU*IH~$kn zjfZg!F2zwe2wP%9EP(|u8OFyiaaO0vF&=?2DbTHCDpXSO9Zie2j^2 z$GG{Q<2gKr>v08+#i7_5o1i~d!W@_plVN=PGMeL$SMeNf#q~H9$6{w}jg_!8X2g^j z3BQkGzvB(uhrzf2XJB9KigmCm=Ef`-8>8Thk#61xcpUfRN?eG;upc(Xx>yABU_$i9 zw<9>dcn*)@dR&2HaVYk}&ghSoFb8JDm>3Da4Cnab6TFL;@H8I49k>x!;e4EqV{i!e z#7@`(8(=jok3}#KX2MjM0ApbU{5s5S*Bg9_xA8Kb#Df@&LAU}J;8YxogRmENz?N7K zt7BO#in%Z|roe<410&++p>DhW#>aREFXAcOkH6yvT#55=8ji-n*aJIabF7b5u^bl0 z+?WwlVtkB=;ql85w_UIC3Esj>cmfaLcHD@|aXwDLF*p!=VtZ_Xb+H!3#{(&cP9|q$BoPlF;DE7k6*b*CJb@aocm=`l+YD|dU_J|dE)K$8*bx1(0Or8>7!%+2b@M&Pb9fBb;|d&$L$NhB!O~b5 zQ(_|g-p9@N0dL?R7>q$U11DftY=>2`9A?2Z7zM-Pquy@*+jtOn;$obQ1F#3y#~PRq zvtvArj&FLo`JUn#Jc4U+8IH!m7=VqiBo@Tvm;k@_bo0H#Yj_^F;Rc+B<1i50U}Y?W znJ^Vb#veW0y!Y@r?#1mmAE#pT;H$K!Bpi_Nes7RA(<1nonBqv_w9KX!HA!b`XVH{mRt zgx#?NR!2X~hUqXGhQ}ve+`M=3Fz&{sI2Q+DFKmeZSO9Zie2j^21KoVj@f;q*^|%7Z z;!tdjO|Uc;#*~-{zjt=?eZU*|2L@vh&cF%S729D|EQeVz4MxGR_^6Yc|27`Powyih z;{fb|^|1!#!|WIjqvKy4-F%Pn1RlVxxE?3tXzYjqSOH67dQ6TH@M{M*@1J-L_uw|1 zhtse(24XF&j5#qA#=^+>qP?5<0UpQwxDprQFzkm-u`U+DJeU~c;6Lr$e1G9ZJcYmE zuQ(A$VtZ_X<*_)XMIQ`@pWC{5@8A{Oftzp^PQvck0jr}QX2WzC4a4J;Hg4X#co=u% zQk;u}uopH&e=LAGFh0h_x2@fL&+!}{!?m~!N8&(ifeo-Y=0_j=1wXfP^Zkui@GNe@ zbvOmbU?*&a6|od%z!Vq}zXiB?@8Naai`#KNPRBmj1#4p!%!QfJ8@=#lOE>RBJb?#r z6)wWz*dLo=JuHfOF$u=Sk1gDMukjL|#!a{eC*de;ht07Z7Q-}{6vN`D=5F5Gco}!% zW}J08QT#SZc@MBXq?=8H9 zC-4BS!bLb8$72_4i&d~JX2#T*5WO)Xerw{^^EW=jJ9q_8;UWATf5Vly5U1fd9E`oO zBL-l7tbygQ80N+-7#pMD_r`8JKHzh_k5};=9>(3c3D@8voQ30YIQGFV*a{nCO{|E; zF+cj?FZj6;#{nv@DH@gN3c5YCWc_5IQW?27HMDwe}6m?wwv!M-p0$g6F1{boQU19JyyZ8m=RNAJdBQSYB4|F#>;pT4`MI|;R;-UQ*kT~ z!d}=A{jmV%!1x#w-}tjWJcCDYEiS{+I2Z%45thV)m>d(}*P3p=cX$oY<2KxY({LOH zVjHZCWiS(_!pQiehMV^R-o*X*J1)eT*blp5U95(AFe}EvsQ6cPH}7LSg@^E0T!JHU zAhy5;SRC`C5B`FmtGW69#w&Ohx8ORQf@81~w!#Kj6Z4}l{(>>^@2YP8XLuHm;x62R zb8rgw#7BEw~P+;20c;J+T4S#Qf-sY0(GcU{w53*{$av ze1Q+}8lJ}^xCb}mT3n2?aRQFOcGw)tVKGdDNii&bs^r#r8!zKd+>EnvGWNiZSOY6y zG0cZaF&=)Z=;nQcm+=f9#GSYpXX6AMfqk(n*1@Wn8?#_+jDoK!xb-~3lXwtU<6<0v z1F$Q$!>U*g3uA6fgt761pPT;`{(&bk2v_3-9D(hyIhMm>m68*3Qrop5b7C)8Y_~2#SiJNgYPR1VC5o=%t%#P_XI!3^! zrQN)L;t||~%WxhJ#@^TnYhgjmi3uJ7I6n9k&)^YUi_35{4#og%ge9>cCdUN$ zwWOQ(9bUupxD7YpG#rP4*aj-~&94`*9m?z-2fO2V-yShyhq1YhXUij%hF{#>Oc4y_j3?2YinA@hI-a z&A1j9;Vc}7!>|oD#WGj~Q(wAJX@gg3>eYgS_;85&~ov}4GM1S zjep=t+=s!q0B2xd?22`;D(1#47#pMDs{(F4kMJZO#MQVMN8kW#j`gt^=EI~I4?pE+ z`|&cK!Ogf9C*x@BhyhpuOJY9Ej%hF{hQ&|$+&W(2BfNosU@!*Z3S59waV&Pm*4PmJ z(GN>tUd)E6F$w<2>(==XKF9lb1<&F^+=+{EHcr41*bbXx9juDEF$<=|MEE_ATi*wK zj`#5@p2Neq8<*f5oPZ;+4|c)YSOs%oX7olce3{#=?;)PR1GpVG;&PmigRwVuz?SHT zB`_T(!|?bems`hce1f;|5}v>VxE(j*a-5G-a10K_p4c8+U|B4RsWAzL!H+rJdT-$+ z+<}{L7EZ$M*a54fA7;aJ7!AYYlN@f|yLcFP<5HZ9gRmDiM1L%RIWRuP#J9d~zUO!j zkKu0IifeEwj>Li3729D|EQeVz4MxGR_#wMn&nvu-H}D)D!`-+Q=i*fCg`KfE*2iL) z50hd%{FKeD=M7%QGq@So;$$3+9WekaU`b4m$uRRVCO7XLyn?%M3(mnQ*b_TpO{|E%m;qy8M0}Rf&3g|I<8EAxvvC0S!1`DN z^I>+3htV-Ce#+qHy^WV~CvL{sI2ngwKkS69umRS@@>m@6U{;KSQSq%5Cs zaW`(oxi}R^;UH`&!>V3Gtd4$I6!T&tjEx`Cxbd&>4?KzcFc|0IG#rTou?x1vDp(c^ zVJ=LF-uOPXThB{8hsSU&F2m6{7+YWitb%2+0Or8>7!$+emsD;YckwFj#;rIPr(!Sc zjQ&^&b6`eHhVk)JN;mHtyo_gXGp@ynI1>9{7i@_Qu^8sVq!?!I1UG5PppU4u{0LO?3f;-VmN%9+^z2p9>QI?1n1yD?1>GqCgw+9`~_oRIQ*Q< z&3g+kVK4^a44i<0*ajP5P0WkgFeN6!uRdaWTY>a}h z61#aH;YmD*t8p=ozya7C>thkjg9*_a-zReOy~GQ60yp9+9FN1XEjGilSQJxZ5)6YM z6S{eC;Ux^lAe@HdFc8~dWh{f4Fcn6|9|_!i_wYLI#qBs3r{V}4fPvTs8=^lJz#JGK zW8&NRZXM6@93I26_BK2FCz*ad5270iX1(Hp(+Wn4G!Lp*^8a0M>Fq1YE2VJ*y$zL*-5 z;P*Igz7Kc<|G;1j!f7}TJ7FuVh@~(Crof2!EjIfXuj5|aj`MLk_Q5V#8>?V0%#0~8 zA%63A^S;Mtcn=TbZd{DBaRBzfx>yZMVIj42J%(HFeY}DDFc=r$4D5?tu?|+n+?WMpV-$Q9-Oc+5PvSvbjf-&v4#4JE zAB$l=Op5XFlfD@WtM6al;AK36n{h2p#?jaj1F!;?#PpaPBjDGlZr(rf8t%buI1i^` zZw$m*SQ&F-CX9uV@kJCj?*lxJ`*9^M#9`PE1F;QO#8Q|Svtde1gx|f~{2%Z+-p6CO z4_Dv<9E`oO0oKI)=!wry7^cCb7#2T;XI{LFJ8?74#>vd#AtX#dgwB7F?wyoHx=2X4YyI0?IB z2ds{MSQPW3zHJMcPcH{U)NLh15#sE8?%&lW<7ga=y)h8$Vl^y}#W4e>z=Y_HAGI(& zr9^s-Pw*~Y#d8>pLAV<2=aN=uHcrOTI2hYtQ>=^CusjyW{OF4rFa>&H82p%r?ZGE_ z7wzYlwod!`r5TJtxEdGZY@CdvaWJ;QrdSuNVSe<*444AFFbsao&HC{P-o>kU4v*nJ zT#buyHcrOTXg>$F?eC3&SQo2dc`T0k(HApd3iQG-_%RpTgZ6V$oA)kW#d8>pLAV+h z<7}Laqj50y#z3r#)v!Dk$NcDv888JVL~pd8quTmk;}g7#SMeMk!+jWxK{y*H<7ga= zy)h8mU{frQ#W6qnVg^is3DFxr=3sl!eqI}LeDErs!(+G)SL0%wjgxUS4#qav6zgI& zERV%81E#=)=#3wJSwB9(yJ$c6we8u5!5D&2^RKL@sT+RuSQ){CogG0w)x*c$_}4K~H{SRC`CFD689^ujRstft?U}<_tm6z$;}llVes65sQ^F$Vu@}>r!X!p9f?*8d!Unhgd2HYu z*072*IE|Ayfn_XV4*Red)0n^*Mlph64B^6h+KUaG!&$833{K+|R5e#DpgBZZZ ztK99G!&$833{K+|R+?&n7|lDF@ix1;KIvk zFV12eYgol8tl%V0U=j0}!#+%55)&B1ForOQ0c^a?ZLj~mf;!V@RQtR(jZ;{`GM2E2 zdF;hBrZ9;KjA0l<7{mZBtaIBlj}4r|8v5Tum}dGER&Ww0u!wogVIQV2i3yBh7(*Du z05)Fgwto(1(f{5;mFZJh!AYFJBIYrNeb|d>OkfP77{M@xaN#BFZ)~9dJ%>8eYgol8 ztl%V0U=j0}!#+%55)&B1C`K@hAzXMd?Z*brVGXM|gVQ*P6IjL)7BP=G?86i$F@Z4* zV+ey7z($1rg0oo18dh-zr*RS|u#6?lVITHl8WR}9C`K@hAza}7hk0z^9M-UkGdPWt zIDus>VGjGS7t@%+Bt|iUVGLmq1GvC@6!X}?Ih@5h`rqf6VtNJ3Si&ND?|Jl+)0n~} zCNPF!3}Fxh*xn7|l@F@!-3V1xHt=5QA4=zpJPis=Ajf76ecl>5e#DpgBZZZbGiQDEY`7xRh+^KPT~ZXv4lD7!(L2d3X>Sc2!=6)K@8x+ zrSu#n8p+)F^UlkV+a@4&|Yld9M-UkGdPWtIDus>VG;A#i)l<@5~CQwForOQ0c<>* z{*AL(#~M~~3M)8?6IjGN=CBV_m_+~kOJSymFo*$cTta(s7VB8UD*E4Vnq>L}ma&96 z?89D6V+xZP#R!Hmgh32o<5{#HXR(eotl|__a1tl5j3q2$9&^}-DNJGlV;IE(ytav4jQ!#?!Cf0bZ*45JvqForOQ0c>2%{>NFYV-2e~gVX4} zhc!ViV+nKEhrO7_6ngJvMadBiV+ey7z{YCYkF!|E8JtG{`&VVAm#~O=?8P*uFo{u& zU>HNVa1s3j8#sqG^uL!i&Gad(;3Q698B3VMKJ3LbrZ9<7j9?f;7{mZJRL}7BP=G?86i$F@Z6RVg!R2zy*CMd7eJ6n#WnJV-2e~g%zAc|9fL4rWY}f zy_m)nCNY6A3}Xm`7{JCe*xxvdb)3OzoWcrD;slnlg#P!@dYPWa6ecl&F^pmagBZYt zr?daDfpb{HD$d|EPGJShSi&ND@3r-k)0n~}Mlph64B`U~y-H#3S6464?j1Gw-s+KaPT#~M~~3M)8?-g|LHavpQohbc^A z0%I7)5C$=TjSJoO&fzT9aR#Sx3M*K~5*9I!y_m)nCNYW;3}XlvE?|FR1Lv@YRh+?T zoWuz%V+nKEhrO7_1jaCm5e#Ag7liiWEY`7xRrKDotB@yg0*jc(9QI)flbFC5hB1Ue z4B*1~v=?Wwjy0^}6jspxzFv{(dCXxSrZ9;KjA0l<7{mZJ{)GODvslL&oW?1vU>W`I z`Q@43i)l<@5~CQwFotkJ2LtE&h7Fv<8dlN&zTYI%C$NkqEMgveF^wrqVgh3r#t;TE zfQIW^1s#-s69`;Asn-j$rsJBK z(DB2x=WKr$2y9rbKA;BFPpS*g4+Nf2e})gMf2;Xh_;vNd^8y<_qdx7tz-uSfw`=(a z)UT?ys=5z1yj8s^5P0D(_4_*Ao}V>T`@Wbh_k49u^MC5|CTqt}RBOix)u#V1rhkU% zJJqk~^e(2qis{c{`uR+MM0bqU^Pp<;S5>S3Zl=FqwfYY-eWyCF`St1}>dVQOkuOre zuhTD3?^l1L&u45qeyLjh|3|g@YpSjHe%0#vJmsIHyhQo9YU|H3eY0xyw307Tt)2^1 zoA1~9e8uYjfjXu>q~4(W^?s%wR&D+dsW$&Rn0|x$UCs6!=U-HNj$`X-SFOHFRa-7d z{<%IEv3yds?K`2`{12!$|7R%wxcWoQAEDfy(^&Z+<@Q|0+Hp10H{d0dUr6~A`W(ZS zn^XTnt*PHttE#PkTK%3nMYivAeOvSURaTmR)ue-_g(VES+Ld4w&0 zO10&`r#_;7L$&QaPWfjk|EOBk>31@HKhy2`h_$m<{i$ltM}DB%bC92__WZ;8l|BFX zg?d__BmA3sN_|-UXZ4`^CG{ujXVgd4H>oGpYt&P!J+F9BeWhykU#40+pRImP6*Z#$ z!M?X;+jCmA_CBIoxqW}j%D+wdgQ~Ure%0E2R4u4)RBuzSQtdpp=L>co$5lIz?Ky&T z9;mkbH+10nrTS^rw)4HJ?N|H$m9^tqbxysK>91z`8m3>!^ncgS$2R{-^%nI3)sDw& zRol+EYW3RpoNT@)^z*7s|AlJP>#9w+?3^iMl+ z2WW{LzE!n)_b~lxrvJHW{p4k;eg|N~vsK$~&s1%@ z9|^kS)5EIey83PP4XV|*Rkiil=c5PIb?PJPTGiTd5#^_!=9d4fTGi>_QEjvP+IexAYU}x*7r6cGi>i%BpHd%G?Q?^z|J|x>&u!}0)SK0a_Rm4pw);)0 zZI^v+_?o&|wer`fR^Fo8_Ps>?srqcy#-r1EAN~pTG4+$`DRoM%tG`vhtmd?yFRB~V zd)2IZ59Jf;Ud`{L{GF7)jdJ_Eut&@LDZhbo``lpbdAa)c>M!*E`tQ_x)laDts;&R+ z>Yy%vK(+Ocs=KW|bwIs=>ARTTt@i8m*D<}5>1);dw2C$AUk3uO{qdi;^*^NA{9jY8 ze*0cdpZYoV3p(i|s_mCM)hE<<;Vr7&uidOxw7wh2SCcPNZ`1O}&vX0BcU3!%$5lIy zGip)2Teai=QPr*o?@(=g+^_x*bx561U#z}eU8T;eX98}0|E^knTDMb=o*Pa*I?bs^ z_pMWp?pvpxcd52t^XlcgokOZ^_ilB)x?Q#7@jBJE|M}|Ox_vqf1RmFXff~^BRF@6> zmq6fyuTX!d(_f^XulJjJ`xaQx`StP@__a=dy1Gy6?Ntv40;|*N$JCViH)>M-xEfWh zJfd2;)ibGv)Q?g=%JdI1eMAjv`LL=4-mKblSiKeKLD@t`Nsv+6$S5%~%6c-2J>RwZ zQPz=BB4m`cWE6WIY|EppA*0xHVk<{kMMepdQS3Tv^P>dFC}%Em%Tet4v(1lknv60} zMtO{k(jcRpBBRWaQBIOkX2~cg$S8F(%0pz78X4s{8Kp`_IYvgAA*0+!Mwup~93`Vn zkx`D2Q7UAV!(^06GRj?KlnFA*9b}X;8RZZer9?(KNJc4=Q3_;~JQ-z}jFKax43bg$ z$S60GQF_TJJ!F(L8D%>eB}GQ*BBLb9D4WPA2{K9>86`$WSx-iZl2O)?Q6glNwPchq z8D$L_B}7J9MMepdQG|>VAfudF#rf|l3uKhjWR!U_%41}d1{viP8D)-)a*~WPOGY_C zMyZog9wMXE$SB9jC{;4bF*3>w8Rb4Q$}}0}C>dpnjBB{IrEGD?w*QXr$`$tc5QlpGmlkc`qtM!AuU(o06^A)}DKbhI z86`0hkx_0Wqx6zdddMhgGRk%`N{WoqMMg=IQ8tlL5@eJ%GD?h$vYw0* zC8Mk(qeRFkYsn~KGRhhIvM35GD?k%a-57(C8Hc8qs)*|?jxg2lTnV6QKrZ! zN607@GRk2x$|M=(E;7ml8RZT#N|}suh>TJqqZ}lo6v-$BGD@C|GE7Fvkx>T8D1Bs< z8_6iWWRxB&Pe(GRj&qN|=nY zhKv#-qpTvM1j#5uMhTEn&gcUe=lpk-1v1KMGRiy|#r}OMTOOrBMzQC>R*o`9Mmb4F znI)r~AfwdDC=ZcQYGjn-WRxlyloA=`AQ`1dMk$a{@??}@GD?n&GDt@0Bct3%M(HJ^^pH`~WR&e> zloT1Ii;R*aqiiChB*-XjWRw^gWjz@sN=8{nMv0J7){;@eWRx{zln@zZ6&WQ+MiDYf zfQ)iRACNldzpE^eQBIRl=E*3Jkx?3Clv8AsIWo#gGRiC&-uOR-U7L zkaBd!Gb`_-{6@;r8PBY|m+~IU(HYOIJWcs_%F!9mtUN_|7v<=TXI7r1d=us9jAvG! zpuCN8bjC9)k5Rs!a&*QsE00pXj&gLyGb@i!zLs)y#xpAqQ@)0BbjC9)4^h5~a&*Qs zD-TjGl%q4AS$Tl+GkQK*MrS;;yx>lE#xu*O$@9#Q&Uj|!k5S&B9G&sZ%1==~M>#s< znU$ZU+{Q7>=!|EUZ9G$*@yv3aY~z?^bjCBwHOg%qvy9GoX1PlFG0M>y&#c_WGu0W- zEZcZy*~T%;=!|EUZ9KDb8^ zjAHM3SpP(sC!;(@Mrn{yPLWaO$S5btD6?dg6J(S+8Ra1|ioGvt?L|3GMyZlfj*(Gj z$SC)bQKrc#N69EtWRxRhlnNQ;Fd1c%jB*zlWrB=y2N|VIMma=ADUneQl2M9elmZzg zPevIgqvXgagJhIGGRlo)lwLAQ4;dv*M%hkANs&>y$S6rN$|f>Of{fBeMv0M8){{}9 zWR!Jeln5DREg2$hrHgDBjB%AvF=;}1t z)Mo~(BV<$GKU{qt*&Nb5ulv*LH}yTp)ittd@84C(roD&v4ziiioF|+1eqM@f+IxBt zvT5(*okuor)NIGWS-*NjbCqnqP4fiV{0q%FvN@sI-fOkx%{OX}kv{aw(qf7x%pnr4Sg@w zviVNU|426V)uGk)y)`R0-=*2Ur)JqKYqsyFSvKFJIYu_$p*cu4Z`VAh@2lGU=DRi9 zd#{$wLz?ZqSIee$(be{SGs|X4^SFA!d4a2wsy+jIi}`+?Zr>xbY~G=HUY~PWHs7bY zMm9g7S^KI}ZtAnP)jF?}%`wd>vUxyrglvv$J`~pf(|0Sse1#rJ{jtAiWw}PSzjI~z zaq`E=Yqz-b-$VX0@@L7{lRr;>8~J|A`n#MH&v%#q-;{rXa{GH*w!Rs%{T(jLbL5|r z&+l@V|2cV@{AFDHMG+)4f++5UYbr+wsY z5*w_V2J+eW}ab(=*9_U{YGpChj$e~G+-{3CLQWv%bXOWgXlQT}Pxx0Ag6D!2Si*8hFM-JJpbPbU)t59%-VE`DYy@Yzmx{vYc7f#ojRqxUY( z{0SCVtvC5rKFj>W)PKM#)}QMrzbxU__nhar^C#B3`G_7%TfP)^^Epi?3Q=y{ikKSPq&|0 zUCy%o-68uqpXIr{2dd;tbUFLEH0aL%9_sr!f4)q6*3+Jku>G&n<6=K|a(qAjO5G9q zQzE~Id{ozM$M?jm-15Ve{|n_ah_836%mN#)q4% zTyv6a_v+ef96u}y}`x)@Q=Rbf8{$~Cw%Q|_Z{z@zV^)P z`PbZD`*#AG^H+V_|7E?tG?&}B-kkaSzKiX>#@C)BzT@>>-}>M0Ti;3F`VRQox7}CY z{l5NsiLd;Kul`GX`~Q8u`R(7sXx_eG`P%adEo?6Tj&J={U-<^#`r3WRd&HOdcl;Lj zr~Nx1&Fiy&C!{&Q(KkL`?_2*necS(-@A%mF)SK&jt#5h$9`#~-w)*DZ;5$AU-}0Tl z_Uh@jY<;_Y<^SO;f4eWg%$Hx`TmP$l>)+rzp7;93r<;8JQEwNQwNHze<)W{?hkfg7 z_2ob&b3^OkP&R$lfc|GDJ2o~t7RcnshDHi|RC2aBRIoXB#A99kh5lWIv26doc0-Y zDzTCdcS^g{&hB(!XlQ8pI`{Ms4cpu;8+&qNqql4x9v&U&FJuR)sW_0$7luYh_UYca zEs)vQZ{>l^fpKsDWHJNA{){tO7t3V51+31VZE0th+8hO|-Dy_y4oqyxWe0A)Dtjxt zu6?_%eR$`83Tj_fVux>s!KMrTuPj_&lpP};V4yf8M9(_?B!uj7hc z*X-!Zj%UY)`iF;Z%Z_bn=}x!V#PqRDR4ckaqONd-?*8jtVH_784ZcI@=f zb#5CU9oBssk7*a!vVUwWJ5peCwX`MHJwDK%@83O~b-UZHfzf<+i?&odi?^utuNyjc z^pEVw-m=ZQ=En5c(7vI<&;ji});-zZJsCH8oorXDPH=X{IoH(TtUlYFw)G|ST*;1& z^bdR8-CH&uZ)#ju%Tn{bLmAhWZ5I?K#64ZO6W$5#4Q06ILGXc!%xmo!PzF;x$gs9;Z=fnYGhq z-KLwiH#@fM=$vKVn9ciCGqu=Ei=&0xb#)JWJEM)A(R0h_6}J|2-!9)Dg>&tXvvuqE z#->i*H9DYsO1sbQbL^Ft&a=#ITW$xHrL3WhN!rfkjXOuR@s6fy-BBxX#rWum9Z9z- zOO+ zLAOtwrGGW=$<1S9{kL*d+D1kPvmICL-?Jw>W~Yj7sP2iS4ZMm`&6((S<#;>&?Anp> zp}iy7!R5#DCTBk^yR2NR=XYz<+1sX5O+g8`|R{KrXy6m!Xe5wDeJVTrw7mv9|_WH5@ zJmb1^Bd|NWcW6XM;=(}Aj_0nz#>D}dt=O?*`NhMbP20F-INLvVeYXGRb8kkbe_Su$ zh0IuC#OX8cZi>@QoD`338_~<0bA|6d_dS`jxbDPd1IO8}p*x&fonz|Ws=Z`n#ZJFZO)Z@v)xx_ zHty21xxcV~%*HI8vcrR0M)&K5p|Mlzc1U|TI=gvBA0G2mRh}XuPi?~R_;gJ&h)PK%u+XqZ`9*4u-|sFyCJ)@ zlXG)<&V8%*LCbEb&%W2)lu<=eNkZ}_B; zv2nKF8M>bIy0>^O>C`>{d+qdP9lmS%sncpV!@Iou<3DuYIVVbsHiY}@>xT+C_v*BH zMDL{rv&BEE#(2B$zWtA?r6umGMSG)ujQiv2iVckF<$i4cKw)%DZ#&&H+a1f6E`d6b zx>xJPE8xa%?<3Mi=Z4lkZa(En;*H1gHs@2?VimUF;%6pbFLoN?th}T7v(m^d?xz&( zreZ*Y4>M!*so$mA|x9v+C6>qV#c%abz*8Tm%%kGi%hJESGruul|EaS)G?(o`R zgU04z=XNALI%IdA+eVfxr)Rpm(2DCvyv42;-Z;#`jCV9owDU-Z$fbL|WewHqPU7nR zo3l@H*-0PpM(DFv?Ctskda`;Km8ApS-u;vZd2pDmTiVNsZR5-Co|Z~BZX3U1bW|^t zBMdA{Me!C&+yTwqV{zxCTs$Smw#DPlC{FK>FP*K69~AsgGFrSXT-rYG$R&0SkKUqP zW%<#w4|Trd*EC8ebpFNmu$BH*`bXuJTha6+ru&cC2>0H(dt^Xwp;z2DAK0hoRzh!$ zMhER#O(3&pESuF$aBg$5`tft|Cda*_;U3&Z)^YFp>bv!b`*z~eVbf#1>>k@~nLBQ} z7lGwBF-skpzJ$K91T_nDjj8T+i7**7}4e>j^N(@zTHI?OMP3d`?9x?&7&?ty9gywR#3 zTFzD0e(lKEV(C&J*7M8#sJC*!jJpNReZTn$WsCdh)V+eHweF$f;=@sQ#9F-mYTvNy zqW54|pUSK_Aj?Lqr5)(rBKQYD|Cqb9IUU=^?GyOQjcKtVSD#ijZ_UzTx)W&3c;ar_X`>tvl1wKnxvtNWT;Mpks$rDw=z z+f~aiQGe*ZTG45iI+u0AWglO?j<&0i7#bbV?Cu}Ww%Nx={UGR$YyJZ2$_$Q=W^&H6 ze($=V2gUt8L1u5UXumtqhh6$1v~X+YK+KuvEDtI#&*lQ#GnebFB*d`=Td@t>u_JKh zmMuJS&lK!QaDtLf^zue>Jm&pJ>xyOLUbS&={c*1WOGO>t^4=Qa-YVkWI$FGSw0QNj zc=fb+ThiifN{hGB7O&-=2oxfR-=2oxfRU;2fMq|J(=ZKoc6_MuX-Ef@63yxq}@Ak?cSDmc>AKm>j~|NmCJj(w`1`?y#3ta zZE(j~cDOfF`(oYRmbZKRqP=b9+Pp?~c#Z7z8rkVp)ag~!=~dL}?aR)y?0K(|?Oyxa zSDx{D2Iyn9c-!LTG_zZW9B0_-`7-|yy&uk*YHl;6;Hb4 zAOF#fp6l)7gtw0qEi1RzYfob3sHdl1CUfQXYp&R=E!~#sx4pTmusxB<4C$v(y=P%P WUZ+TO2D(%FQ9y6IVvGM35Bz_53s)Hc literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/binding.Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/binding.Makefile new file mode 100644 index 0000000..d7430e6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/binding.Makefile @@ -0,0 +1,6 @@ +# This file is generated by gyp; do not edit. + +export builddir_name ?= ./build/. +.PHONY: all +all: + $(MAKE) bson diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/bson.target.mk b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/bson.target.mk new file mode 100644 index 0000000..5cba69d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/bson.target.mk @@ -0,0 +1,154 @@ +# This file is generated by gyp; do not edit. + +TOOLSET := target +TARGET := bson +DEFS_Debug := \ + '-D_DARWIN_USE_64_BIT_INODE=1' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' \ + '-DDEBUG' \ + '-D_DEBUG' + +# Flags passed to all source files. +CFLAGS_Debug := \ + -O0 \ + -gdwarf-2 \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -Wall \ + -Wendif-labels \ + -W \ + -Wno-unused-parameter + +# Flags passed to only C files. +CFLAGS_C_Debug := \ + -fno-strict-aliasing + +# Flags passed to only C++ files. +CFLAGS_CC_Debug := \ + -fno-rtti \ + -fno-threadsafe-statics \ + -fno-strict-aliasing + +# Flags passed to only ObjC files. +CFLAGS_OBJC_Debug := + +# Flags passed to only ObjC++ files. +CFLAGS_OBJCC_Debug := + +INCS_Debug := \ + -I/Users/SEmmer/.node-gyp/0.12.0/src \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include \ + -I$(srcdir)/node_modules/nan + +DEFS_Release := \ + '-D_DARWIN_USE_64_BIT_INODE=1' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' + +# Flags passed to all source files. +CFLAGS_Release := \ + -Os \ + -gdwarf-2 \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -Wall \ + -Wendif-labels \ + -W \ + -Wno-unused-parameter + +# Flags passed to only C files. +CFLAGS_C_Release := \ + -fno-strict-aliasing + +# Flags passed to only C++ files. +CFLAGS_CC_Release := \ + -fno-rtti \ + -fno-threadsafe-statics \ + -fno-strict-aliasing + +# Flags passed to only ObjC files. +CFLAGS_OBJC_Release := + +# Flags passed to only ObjC++ files. +CFLAGS_OBJCC_Release := + +INCS_Release := \ + -I/Users/SEmmer/.node-gyp/0.12.0/src \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include \ + -I$(srcdir)/node_modules/nan + +OBJS := \ + $(obj).target/$(TARGET)/ext/bson.o + +# Add to the list of files we specially track dependencies for. +all_deps += $(OBJS) + +# CFLAGS et al overrides must be target-local. +# See "Target-specific Variable Values" in the GNU Make manual. +$(OBJS): TOOLSET := $(TOOLSET) +$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) +$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) +$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) +$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) + +# Suffix rules, putting all outputs into $(obj). + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +# Try building from generated source, too. + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +# End of this set of suffix rules +### Rules for final target. +LDFLAGS_Debug := \ + -Wl,-search_paths_first \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -L$(builddir) + +LIBTOOLFLAGS_Debug := \ + -Wl,-search_paths_first + +LDFLAGS_Release := \ + -Wl,-search_paths_first \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -L$(builddir) + +LIBTOOLFLAGS_Release := \ + -Wl,-search_paths_first + +LIBS := \ + -undefined dynamic_lookup + +$(builddir)/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) +$(builddir)/bson.node: LIBS := $(LIBS) +$(builddir)/bson.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) +$(builddir)/bson.node: TOOLSET := $(TOOLSET) +$(builddir)/bson.node: $(OBJS) FORCE_DO_CMD + $(call do_cmd,solink_module) + +all_deps += $(builddir)/bson.node +# Add target alias +.PHONY: bson +bson: $(builddir)/bson.node + +# Short alias for building this executable. +.PHONY: bson.node +bson.node: $(builddir)/bson.node + +# Add executable to "all" target. +.PHONY: all +all: $(builddir)/bson.node + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/config.gypi b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/config.gypi new file mode 100644 index 0000000..098cf3e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/config.gypi @@ -0,0 +1,134 @@ +# Do not edit. File was generated by node-gyp's "configure" step +{ + "target_defaults": { + "cflags": [], + "default_configuration": "Release", + "defines": [], + "include_dirs": [], + "libraries": [] + }, + "variables": { + "clang": 1, + "host_arch": "x64", + "icu_small": "false", + "node_install_npm": "false", + "node_prefix": "/usr/local/Cellar/node/0.12.0", + "node_shared_cares": "false", + "node_shared_http_parser": "false", + "node_shared_libuv": "false", + "node_shared_openssl": "false", + "node_shared_v8": "false", + "node_shared_zlib": "false", + "node_tag": "", + "node_use_dtrace": "true", + "node_use_etw": "false", + "node_use_mdb": "false", + "node_use_openssl": "true", + "node_use_perfctr": "false", + "openssl_no_asm": 0, + "python": "/usr/local/opt/python/bin/python2.7", + "target_arch": "x64", + "uv_library": "static_library", + "uv_parent_path": "/deps/uv/", + "uv_use_dtrace": "true", + "v8_enable_gdbjit": 0, + "v8_enable_i18n_support": 0, + "v8_no_strict_aliasing": 1, + "v8_optimized_debug": 0, + "v8_random_seed": 0, + "v8_use_snapshot": "true", + "want_separate_host_toolset": 0, + "nodedir": "/Users/SEmmer/.node-gyp/0.12.0", + "copy_dev_lib": "true", + "standalone_static_library": 1, + "fallback_to_build": "true", + "module": "/Users/SEmmer/Developer/node_projects/mongoose-seed/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release/bson.node", + "module_name": "bson", + "module_path": "/Users/SEmmer/Developer/node_projects/mongoose-seed/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/Release", + "save_dev": "", + "browser": "", + "viewer": "man", + "rollback": "true", + "usage": "", + "globalignorefile": "/usr/local/etc/npmignore", + "init_author_url": "", + "shell": "/bin/bash", + "parseable": "", + "shrinkwrap": "true", + "init_license": "ISC", + "if_present": "", + "cache_max": "Infinity", + "init_author_email": "", + "sign_git_tag": "", + "cert": "", + "git_tag_version": "true", + "local_address": "", + "long": "", + "fetch_retries": "2", + "npat": "", + "registry": "https://registry.npmjs.org/", + "key": "", + "message": "%s", + "versions": "", + "globalconfig": "/usr/local/etc/npmrc", + "always_auth": "", + "spin": "true", + "cache_lock_retries": "10", + "cafile": "", + "heading": "npm", + "fetch_retry_mintimeout": "10000", + "proprietary_attribs": "true", + "access": "", + "json": "", + "description": "true", + "engine_strict": "", + "https_proxy": "", + "init_module": "/Users/SEmmer/.npm-init.js", + "userconfig": "/Users/SEmmer/.npmrc", + "node_version": "0.12.0", + "user": "501", + "save": "true", + "editor": "vi", + "tag": "latest", + "global": "", + "optional": "true", + "bin_links": "true", + "force": "", + "searchopts": "", + "depth": "Infinity", + "rebuild_bundle": "true", + "searchsort": "name", + "unicode": "true", + "fetch_retry_maxtimeout": "60000", + "ca": "", + "save_prefix": "^", + "strict_ssl": "true", + "tag_version_prefix": "v", + "dev": "", + "fetch_retry_factor": "10", + "group": "20", + "save_exact": "", + "cache_lock_stale": "60000", + "version": "", + "cache_min": "10", + "cache": "/Users/SEmmer/.npm", + "searchexclude": "", + "color": "true", + "save_optional": "", + "user_agent": "npm/2.9.0 node/v0.12.0 darwin x64", + "ignore_scripts": "", + "cache_lock_wait": "10000", + "production": "", + "save_bundle": "", + "init_version": "1.0.0", + "umask": "0022", + "git": "git", + "init_author_name": "", + "scope": "", + "onload_script": "", + "tmp": "/var/folders/n9/td6l5zvj3g155h0q3x8kn3t80000gn/T", + "unsafe_perm": "true", + "prefix": "/usr/local", + "link": "" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/gyp-mac-tool b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/gyp-mac-tool new file mode 100755 index 0000000..7abfed5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/build/gyp-mac-tool @@ -0,0 +1,512 @@ +#!/usr/bin/env python +# Generated by gyp. Do not edit. +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utility functions to perform Xcode-style build steps. + +These functions are executed via gyp-mac-tool when using the Makefile generator. +""" + +import fcntl +import fnmatch +import glob +import json +import os +import plistlib +import re +import shutil +import string +import subprocess +import sys +import tempfile + + +def main(args): + executor = MacTool() + exit_code = executor.Dispatch(args) + if exit_code is not None: + sys.exit(exit_code) + + +class MacTool(object): + """This class performs all the Mac tooling steps. The methods can either be + executed directly, or dispatched from an argument list.""" + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + return getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like copy-info-plist to CopyInfoPlist""" + return name_string.title().replace('-', '') + + def ExecCopyBundleResource(self, source, dest): + """Copies a resource file to the bundle/Resources directory, performing any + necessary compilation on each resource.""" + extension = os.path.splitext(source)[1].lower() + if os.path.isdir(source): + # Copy tree. + # TODO(thakis): This copies file attributes like mtime, while the + # single-file branch below doesn't. This should probably be changed to + # be consistent with the single-file branch. + if os.path.exists(dest): + shutil.rmtree(dest) + shutil.copytree(source, dest) + elif extension == '.xib': + return self._CopyXIBFile(source, dest) + elif extension == '.storyboard': + return self._CopyXIBFile(source, dest) + elif extension == '.strings': + self._CopyStringsFile(source, dest) + else: + shutil.copy(source, dest) + + def _CopyXIBFile(self, source, dest): + """Compiles a XIB file with ibtool into a binary plist in the bundle.""" + + # ibtool sometimes crashes with relative paths. See crbug.com/314728. + base = os.path.dirname(os.path.realpath(__file__)) + if os.path.relpath(source): + source = os.path.join(base, source) + if os.path.relpath(dest): + dest = os.path.join(base, dest) + + args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices', + '--output-format', 'human-readable-text', '--compile', dest, source] + ibtool_section_re = re.compile(r'/\*.*\*/') + ibtool_re = re.compile(r'.*note:.*is clipping its content') + ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) + current_section_header = None + for line in ibtoolout.stdout: + if ibtool_section_re.match(line): + current_section_header = line + elif not ibtool_re.match(line): + if current_section_header: + sys.stdout.write(current_section_header) + current_section_header = None + sys.stdout.write(line) + return ibtoolout.returncode + + def _CopyStringsFile(self, source, dest): + """Copies a .strings file using iconv to reconvert the input into UTF-16.""" + input_code = self._DetectInputEncoding(source) or "UTF-8" + + # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call + # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints + # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing + # semicolon in dictionary. + # on invalid files. Do the same kind of validation. + import CoreFoundation + s = open(source, 'rb').read() + d = CoreFoundation.CFDataCreate(None, s, len(s)) + _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) + if error: + return + + fp = open(dest, 'wb') + fp.write(s.decode(input_code).encode('UTF-16')) + fp.close() + + def _DetectInputEncoding(self, file_name): + """Reads the first few bytes from file_name and tries to guess the text + encoding. Returns None as a guess if it can't detect it.""" + fp = open(file_name, 'rb') + try: + header = fp.read(3) + except e: + fp.close() + return None + fp.close() + if header.startswith("\xFE\xFF"): + return "UTF-16" + elif header.startswith("\xFF\xFE"): + return "UTF-16" + elif header.startswith("\xEF\xBB\xBF"): + return "UTF-8" + else: + return None + + def ExecCopyInfoPlist(self, source, dest, *keys): + """Copies the |source| Info.plist to the destination directory |dest|.""" + # Read the source Info.plist into memory. + fd = open(source, 'r') + lines = fd.read() + fd.close() + + # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). + plist = plistlib.readPlistFromString(lines) + if keys: + plist = dict(plist.items() + json.loads(keys[0]).items()) + lines = plistlib.writePlistToString(plist) + + # Go through all the environment variables and replace them as variables in + # the file. + IDENT_RE = re.compile('[/\s]') + for key in os.environ: + if key.startswith('_'): + continue + evar = '${%s}' % key + evalue = os.environ[key] + lines = string.replace(lines, evar, evalue) + + # Xcode supports various suffices on environment variables, which are + # all undocumented. :rfc1034identifier is used in the standard project + # template these days, and :identifier was used earlier. They are used to + # convert non-url characters into things that look like valid urls -- + # except that the replacement character for :identifier, '_' isn't valid + # in a URL either -- oops, hence :rfc1034identifier was born. + evar = '${%s:identifier}' % key + evalue = IDENT_RE.sub('_', os.environ[key]) + lines = string.replace(lines, evar, evalue) + + evar = '${%s:rfc1034identifier}' % key + evalue = IDENT_RE.sub('-', os.environ[key]) + lines = string.replace(lines, evar, evalue) + + # Remove any keys with values that haven't been replaced. + lines = lines.split('\n') + for i in range(len(lines)): + if lines[i].strip().startswith("${"): + lines[i] = None + lines[i - 1] = None + lines = '\n'.join(filter(lambda x: x is not None, lines)) + + # Write out the file with variables replaced. + fd = open(dest, 'w') + fd.write(lines) + fd.close() + + # Now write out PkgInfo file now that the Info.plist file has been + # "compiled". + self._WritePkgInfo(dest) + + def _WritePkgInfo(self, info_plist): + """This writes the PkgInfo file from the data stored in Info.plist.""" + plist = plistlib.readPlist(info_plist) + if not plist: + return + + # Only create PkgInfo for executable types. + package_type = plist['CFBundlePackageType'] + if package_type != 'APPL': + return + + # The format of PkgInfo is eight characters, representing the bundle type + # and bundle signature, each four characters. If that is missing, four + # '?' characters are used instead. + signature_code = plist.get('CFBundleSignature', '????') + if len(signature_code) != 4: # Wrong length resets everything, too. + signature_code = '?' * 4 + + dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') + fp = open(dest, 'w') + fp.write('%s%s' % (package_type, signature_code)) + fp.close() + + def ExecFlock(self, lockfile, *cmd_list): + """Emulates the most basic behavior of Linux's flock(1).""" + # Rely on exception handling to report errors. + fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) + fcntl.flock(fd, fcntl.LOCK_EX) + return subprocess.call(cmd_list) + + def ExecFilterLibtool(self, *cmd_list): + """Calls libtool and filters out '/path/to/libtool: file: foo.o has no + symbols'.""" + libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$') + libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) + _, err = libtoolout.communicate() + for line in err.splitlines(): + if not libtool_re.match(line): + print >>sys.stderr, line + return libtoolout.returncode + + def ExecPackageFramework(self, framework, version): + """Takes a path to Something.framework and the Current version of that and + sets up all the symlinks.""" + # Find the name of the binary based on the part before the ".framework". + binary = os.path.basename(framework).split('.')[0] + + CURRENT = 'Current' + RESOURCES = 'Resources' + VERSIONS = 'Versions' + + if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): + # Binary-less frameworks don't seem to contain symlinks (see e.g. + # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). + return + + # Move into the framework directory to set the symlinks correctly. + pwd = os.getcwd() + os.chdir(framework) + + # Set up the Current version. + self._Relink(version, os.path.join(VERSIONS, CURRENT)) + + # Set up the root symlinks. + self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) + self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) + + # Back to where we were before! + os.chdir(pwd) + + def _Relink(self, dest, link): + """Creates a symlink to |dest| named |link|. If |link| already exists, + it is overwritten.""" + if os.path.lexists(link): + os.remove(link) + os.symlink(dest, link) + + def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning): + """Code sign a bundle. + + This function tries to code sign an iOS bundle, following the same + algorithm as Xcode: + 1. copy ResourceRules.plist from the user or the SDK into the bundle, + 2. pick the provisioning profile that best match the bundle identifier, + and copy it into the bundle as embedded.mobileprovision, + 3. copy Entitlements.plist from user or SDK next to the bundle, + 4. code sign the bundle. + """ + resource_rules_path = self._InstallResourceRules(resource_rules) + substitutions, overrides = self._InstallProvisioningProfile( + provisioning, self._GetCFBundleIdentifier()) + entitlements_path = self._InstallEntitlements( + entitlements, substitutions, overrides) + subprocess.check_call([ + 'codesign', '--force', '--sign', key, '--resource-rules', + resource_rules_path, '--entitlements', entitlements_path, + os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['FULL_PRODUCT_NAME'])]) + + def _InstallResourceRules(self, resource_rules): + """Installs ResourceRules.plist from user or SDK into the bundle. + + Args: + resource_rules: string, optional, path to the ResourceRules.plist file + to use, default to "${SDKROOT}/ResourceRules.plist" + + Returns: + Path to the copy of ResourceRules.plist into the bundle. + """ + source_path = resource_rules + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'ResourceRules.plist') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], 'ResourceRules.plist') + shutil.copy2(source_path, target_path) + return target_path + + def _InstallProvisioningProfile(self, profile, bundle_identifier): + """Installs embedded.mobileprovision into the bundle. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple containing two dictionary: variables substitutions and values + to overrides when generating the entitlements file. + """ + source_path, provisioning_data, team_id = self._FindProvisioningProfile( + profile, bundle_identifier) + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'embedded.mobileprovision') + shutil.copy2(source_path, target_path) + substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.') + return substitutions, provisioning_data['Entitlements'] + + def _FindProvisioningProfile(self, profile, bundle_identifier): + """Finds the .mobileprovision file to use for signing the bundle. + + Checks all the installed provisioning profiles (or if the user specified + the PROVISIONING_PROFILE variable, only consult it) and select the most + specific that correspond to the bundle identifier. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple of the path to the selected provisioning profile, the data of + the embedded plist in the provisioning profile and the team identifier + to use for code signing. + + Raises: + SystemExit: if no .mobileprovision can be used to sign the bundle. + """ + profiles_dir = os.path.join( + os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles') + if not os.path.isdir(profiles_dir): + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + provisioning_profiles = None + if profile: + profile_path = os.path.join(profiles_dir, profile + '.mobileprovision') + if os.path.exists(profile_path): + provisioning_profiles = [profile_path] + if not provisioning_profiles: + provisioning_profiles = glob.glob( + os.path.join(profiles_dir, '*.mobileprovision')) + valid_provisioning_profiles = {} + for profile_path in provisioning_profiles: + profile_data = self._LoadProvisioningProfile(profile_path) + app_id_pattern = profile_data.get( + 'Entitlements', {}).get('application-identifier', '') + for team_identifier in profile_data.get('TeamIdentifier', []): + app_id = '%s.%s' % (team_identifier, bundle_identifier) + if fnmatch.fnmatch(app_id, app_id_pattern): + valid_provisioning_profiles[app_id_pattern] = ( + profile_path, profile_data, team_identifier) + if not valid_provisioning_profiles: + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + # If the user has multiple provisioning profiles installed that can be + # used for ${bundle_identifier}, pick the most specific one (ie. the + # provisioning profile whose pattern is the longest). + selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) + return valid_provisioning_profiles[selected_key] + + def _LoadProvisioningProfile(self, profile_path): + """Extracts the plist embedded in a provisioning profile. + + Args: + profile_path: string, path to the .mobileprovision file + + Returns: + Content of the plist embedded in the provisioning profile as a dictionary. + """ + with tempfile.NamedTemporaryFile() as temp: + subprocess.check_call([ + 'security', 'cms', '-D', '-i', profile_path, '-o', temp.name]) + return self._LoadPlistMaybeBinary(temp.name) + + def _LoadPlistMaybeBinary(self, plist_path): + """Loads into a memory a plist possibly encoded in binary format. + + This is a wrapper around plistlib.readPlist that tries to convert the + plist to the XML format if it can't be parsed (assuming that it is in + the binary format). + + Args: + plist_path: string, path to a plist file, in XML or binary format + + Returns: + Content of the plist as a dictionary. + """ + try: + # First, try to read the file using plistlib that only supports XML, + # and if an exception is raised, convert a temporary copy to XML and + # load that copy. + return plistlib.readPlist(plist_path) + except: + pass + with tempfile.NamedTemporaryFile() as temp: + shutil.copy2(plist_path, temp.name) + subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) + return plistlib.readPlist(temp.name) + + def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): + """Constructs a dictionary of variable substitutions for Entitlements.plist. + + Args: + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + app_identifier_prefix: string, value for AppIdentifierPrefix + + Returns: + Dictionary of substitutions to apply when generating Entitlements.plist. + """ + return { + 'CFBundleIdentifier': bundle_identifier, + 'AppIdentifierPrefix': app_identifier_prefix, + } + + def _GetCFBundleIdentifier(self): + """Extracts CFBundleIdentifier value from Info.plist in the bundle. + + Returns: + Value of CFBundleIdentifier in the Info.plist located in the bundle. + """ + info_plist_path = os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['INFOPLIST_PATH']) + info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) + return info_plist_data['CFBundleIdentifier'] + + def _InstallEntitlements(self, entitlements, substitutions, overrides): + """Generates and install the ${BundleName}.xcent entitlements file. + + Expands variables "$(variable)" pattern in the source entitlements file, + add extra entitlements defined in the .mobileprovision file and the copy + the generated plist to "${BundlePath}.xcent". + + Args: + entitlements: string, optional, path to the Entitlements.plist template + to use, defaults to "${SDKROOT}/Entitlements.plist" + substitutions: dictionary, variable substitutions + overrides: dictionary, values to add to the entitlements + + Returns: + Path to the generated entitlements file. + """ + source_path = entitlements + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['PRODUCT_NAME'] + '.xcent') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], + 'Entitlements.plist') + shutil.copy2(source_path, target_path) + data = self._LoadPlistMaybeBinary(target_path) + data = self._ExpandVariables(data, substitutions) + if overrides: + for key in overrides: + if key not in data: + data[key] = overrides[key] + plistlib.writePlist(data, target_path) + return target_path + + def _ExpandVariables(self, data, substitutions): + """Expands variables "$(variable)" in data. + + Args: + data: object, can be either string, list or dictionary + substitutions: dictionary, variable substitutions to perform + + Returns: + Copy of data where each references to "$(variable)" has been replaced + by the corresponding value found in substitutions, or left intact if + the key was not found. + """ + if isinstance(data, str): + for key, value in substitutions.iteritems(): + data = data.replace('$(%s)' % key, value) + return data + if isinstance(data, list): + return [self._ExpandVariables(v, substitutions) for v in data] + if isinstance(data, dict): + return dict((k, self._ExpandVariables(data[k], + substitutions)) for k in data) + return data + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/.npmignore new file mode 100644 index 0000000..eb115f1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/.npmignore @@ -0,0 +1,3 @@ +build/ +./bson.node +.lock-wscript \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/Makefile new file mode 100644 index 0000000..435999e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/Makefile @@ -0,0 +1,28 @@ +NODE = node +name = all +JOBS = 1 + +all: + rm -rf build .lock-wscript bson.node + node-waf configure build + cp -R ./build/Release/bson.node . || true + +all_debug: + rm -rf build .lock-wscript bson.node + node-waf --debug configure build + cp -R ./build/Release/bson.node . || true + +clang: + rm -rf build .lock-wscript bson.node + CXX=clang node-waf configure build + cp -R ./build/Release/bson.node . || true + +clang_debug: + rm -rf build .lock-wscript bson.node + CXX=clang node-waf --debug configure build + cp -R ./build/Release/bson.node . || true + +clean: + rm -rf build .lock-wscript bson.node + +.PHONY: all \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.cc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.cc new file mode 100644 index 0000000..90e2ef9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.cc @@ -0,0 +1,1072 @@ +//=========================================================================== + +#include +#include +#include +#include +#include + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-parameter" +#endif + +#include + +// this and the above block must be around the v8.h header otherwise +// v8 is not happy +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#include +#include +#include + +#include +#include +#include +#include +#include + +#if defined(__sun) || defined(_AIX) + #include +#endif + +#include "bson.h" + +using namespace v8; +using namespace node; + +void die(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +//=========================================================================== + +void DataStream::WriteObjectId(const Handle& object, const Handle& key) +{ + uint16_t buffer[12]; + object->Get(key)->ToString()->Write(buffer, 0, 12); + for(uint32_t i = 0; i < 12; ++i) + { + *p++ = (char) buffer[i]; + } +} + +void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) +{ + va_list args; + va_start(args, format); + char* string = (char*) malloc(allocationSize); + if(string == NULL) die("Failed to allocate ThrowAllocatedStringException"); + vsprintf(string, format, args); + va_end(args); + throw string; +} + +void DataStream::CheckKey(const Local& keyName) +{ + size_t keyLength = keyName->Utf8Length(); + if(keyLength == 0) return; + + // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it + char* keyStringBuffer = (char*) alloca(keyLength + 1); + // Write the key to the allocated buffer + keyName->WriteUtf8(keyStringBuffer); + // Check for the zero terminator + char* terminator = strchr(keyStringBuffer, 0x00); + + // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere + if(terminator != &keyStringBuffer[keyLength]) { + ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); + } + + if(keyStringBuffer[0] == '$') + { + ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); + } + + if(strchr(keyStringBuffer, '.') != NULL) + { + ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); + } +} + +template void BSONSerializer::SerializeDocument(const Handle& value) +{ + void* documentSize = this->BeginWriteSize(); + Local object = bson->GetSerializeObject(value); + + // Get the object property names + Local propertyNames = object->GetPropertyNames(); + + // Length of the property + int propertyLength = propertyNames->Length(); + for(int i = 0; i < propertyLength; ++i) + { + const Local& propertyName = propertyNames->Get(i)->ToString(); + if(checkKeys) this->CheckKey(propertyName); + + const Local& propertyValue = object->Get(propertyName); + + if(serializeFunctions || !propertyValue->IsFunction()) + { + void* typeLocation = this->BeginWriteType(); + this->WriteString(propertyName); + SerializeValue(typeLocation, propertyValue); + } + } + + this->WriteByte(0); + this->CommitSize(documentSize); +} + +template void BSONSerializer::SerializeArray(const Handle& value) +{ + void* documentSize = this->BeginWriteSize(); + + Local array = Local::Cast(value->ToObject()); + uint32_t arrayLength = array->Length(); + + for(uint32_t i = 0; i < arrayLength; ++i) + { + void* typeLocation = this->BeginWriteType(); + this->WriteUInt32String(i); + SerializeValue(typeLocation, array->Get(i)); + } + + this->WriteByte(0); + this->CommitSize(documentSize); +} + +// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. +// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) +// and ensures that there is always consistency between bytes counted and bytes written by design. +template void BSONSerializer::SerializeValue(void* typeLocation, const Handle constValue) +{ + // Turn into local value + Local value = NanNew(constValue); + + // Check for toBSON function + if(value->IsObject()) { + Local object = value->ToObject(); + + // NanNew("toBSON") + // NanNew(BSON::_toBSONString) + + if(object->Has(NanNew("toBSON"))) { + const Local& toBSON = object->Get(NanNew("toBSON")); + if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); + value = Local::Cast(toBSON)->Call(object, 0, NULL); + } + } + + // Process all the values + if(value->IsNumber()) + { + double doubleValue = value->NumberValue(); + int intValue = (int) doubleValue; + if(intValue == doubleValue) + { + this->CommitType(typeLocation, BSON_TYPE_INT); + this->WriteInt32(intValue); + } + else + { + this->CommitType(typeLocation, BSON_TYPE_NUMBER); + this->WriteDouble(doubleValue); + } + } + else if(value->IsString()) + { + this->CommitType(typeLocation, BSON_TYPE_STRING); + this->WriteLengthPrefixedString(value->ToString()); + } + else if(value->IsBoolean()) + { + this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); + this->WriteBool(value); + } + else if(value->IsArray()) + { + this->CommitType(typeLocation, BSON_TYPE_ARRAY); + SerializeArray(value); + } + else if(value->IsDate()) + { + this->CommitType(typeLocation, BSON_TYPE_DATE); + this->WriteInt64(value); + } + else if(value->IsRegExp()) + { + this->CommitType(typeLocation, BSON_TYPE_REGEXP); + const Handle& regExp = Handle::Cast(value); + + this->WriteString(regExp->GetSource()); + + int flags = regExp->GetFlags(); + if(flags & RegExp::kGlobal) this->WriteByte('s'); + if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); + if(flags & RegExp::kMultiline) this->WriteByte('m'); + this->WriteByte(0); + } + else if(value->IsFunction()) + { + this->CommitType(typeLocation, BSON_TYPE_CODE); + this->WriteLengthPrefixedString(value->ToString()); + } + else if(value->IsObject()) + { + const Local& object = value->ToObject(); + if(object->Has(NanNew(bson->_bsontypeString))) + { + const Local& constructorString = object->Get(NanNew(bson->_bsontypeString))->ToString(); + if(NanNew(bson->longString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_LONG); + this->WriteInt32(object, NanNew(bson->_longLowString)); + this->WriteInt32(object, NanNew(bson->_longHighString)); + } + else if(NanNew(bson->timestampString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); + this->WriteInt32(object, NanNew(bson->_longLowString)); + this->WriteInt32(object, NanNew(bson->_longHighString)); + } + else if(NanNew(bson->objectIDString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_OID); + this->WriteObjectId(object, NanNew(bson->_objectIDidString)); + } + else if(NanNew(bson->binaryString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_BINARY); + + uint32_t length = object->Get(NanNew(bson->_binaryPositionString))->Uint32Value(); + Local bufferObj = object->Get(NanNew(bson->_binaryBufferString))->ToObject(); + + this->WriteInt32(length); + this->WriteByte(object, NanNew(bson->_binarySubTypeString)); // write subtype + // If type 0x02 write the array length aswell + if(object->Get(NanNew(bson->_binarySubTypeString))->Int32Value() == 0x02) { + this->WriteInt32(length); + } + // Write the actual data + this->WriteData(Buffer::Data(bufferObj), length); + } + else if(NanNew(bson->doubleString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_NUMBER); + this->WriteDouble(object, NanNew(bson->_doubleValueString)); + } + else if(NanNew(bson->symbolString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_SYMBOL); + this->WriteLengthPrefixedString(object->Get(NanNew(bson->_symbolValueString))->ToString()); + } + else if(NanNew(bson->codeString)->StrictEquals(constructorString)) + { + const Local& function = object->Get(NanNew(bson->_codeCodeString))->ToString(); + const Local& scope = object->Get(NanNew(bson->_codeScopeString))->ToObject(); + + // For Node < 0.6.X use the GetPropertyNames + #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 + uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); + #else + uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); + #endif + + if(propertyNameLength > 0) + { + this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); + void* codeWidthScopeSize = this->BeginWriteSize(); + this->WriteLengthPrefixedString(function->ToString()); + SerializeDocument(scope); + this->CommitSize(codeWidthScopeSize); + } + else + { + this->CommitType(typeLocation, BSON_TYPE_CODE); + this->WriteLengthPrefixedString(function->ToString()); + } + } + else if(NanNew(bson->dbrefString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_OBJECT); + + void* dbRefSize = this->BeginWriteSize(); + + void* refType = this->BeginWriteType(); + this->WriteData("$ref", 5); + SerializeValue(refType, object->Get(NanNew(bson->_dbRefNamespaceString))); + + void* idType = this->BeginWriteType(); + this->WriteData("$id", 4); + SerializeValue(idType, object->Get(NanNew(bson->_dbRefOidString))); + + const Local& refDbValue = object->Get(NanNew(bson->_dbRefDbString)); + if(!refDbValue->IsUndefined()) + { + void* dbType = this->BeginWriteType(); + this->WriteData("$db", 4); + SerializeValue(dbType, refDbValue); + } + + this->WriteByte(0); + this->CommitSize(dbRefSize); + } + else if(NanNew(bson->minKeyString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); + } + else if(NanNew(bson->maxKeyString)->StrictEquals(constructorString)) + { + this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); + } + } + else if(Buffer::HasInstance(value)) + { + this->CommitType(typeLocation, BSON_TYPE_BINARY); + + #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 + Local buffer = ObjectWrap::Unwrap(value->ToObject()); + uint32_t length = object->length(); + #else + uint32_t length = Buffer::Length(value->ToObject()); + #endif + + this->WriteInt32(length); + this->WriteByte(0); + this->WriteData(Buffer::Data(value->ToObject()), length); + } + else + { + this->CommitType(typeLocation, BSON_TYPE_OBJECT); + SerializeDocument(value); + } + } + else if(value->IsNull() || value->IsUndefined()) + { + this->CommitType(typeLocation, BSON_TYPE_NULL); + } +} + +// Data points to start of element list, length is length of entire document including '\0' but excluding initial size +BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) +: bson(aBson), + pStart(data), + p(data), + pEnd(data + length - 1) +{ + if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); +} + +BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) +: bson(parentSerializer.bson), + pStart(parentSerializer.p), + p(parentSerializer.p), + pEnd(parentSerializer.p + length - 1) +{ + parentSerializer.p += length; + if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); + if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); +} + +Handle BSONDeserializer::ReadCString() +{ + char* start = p; + while(*p++ && (p < pEnd)) { } + if(p > pEnd) { + return NanNull(); + } + return NanNew(start, (int32_t) (p-start-1) ); +} + +int32_t BSONDeserializer::ReadRegexOptions() +{ + int32_t options = 0; + for(;;) + { + switch(*p++) + { + case '\0': return options; + case 's': options |= RegExp::kGlobal; break; + case 'i': options |= RegExp::kIgnoreCase; break; + case 'm': options |= RegExp::kMultiline; break; + } + } +} + +uint32_t BSONDeserializer::ReadIntegerString() +{ + uint32_t value = 0; + while(*p) + { + if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); + value = value * 10 + *p++ - '0'; + } + ++p; + return value; +} + +Local BSONDeserializer::ReadString() +{ + uint32_t length = ReadUInt32(); + char* start = p; + p += length; + return NanNew(start, length-1); +} + +Local BSONDeserializer::ReadObjectId() +{ + uint16_t objectId[12]; + for(size_t i = 0; i < 12; ++i) + { + objectId[i] = *reinterpret_cast(p++); + } + return NanNew(objectId, 12); +} + +Handle BSONDeserializer::DeserializeDocument(bool promoteLongs) +{ + uint32_t length = ReadUInt32(); + if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); + + BSONDeserializer documentDeserializer(*this, length-4); + return documentDeserializer.DeserializeDocumentInternal(promoteLongs); +} + +Handle BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) +{ + Local returnObject = NanNew(); + + while(HasMoreData()) + { + BsonType type = (BsonType) ReadByte(); + const Handle& name = ReadCString(); + if(name->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); + // name->Is + const Handle& value = DeserializeValue(type, promoteLongs); + returnObject->ForceSet(name, value); + } + if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); + + // From JavaScript: + // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + if(returnObject->Has(NanNew(bson->_dbRefIdRefString))) + { + Local argv[] = { returnObject->Get(NanNew(bson->_dbRefRefString)), returnObject->Get(NanNew(bson->_dbRefIdRefString)), returnObject->Get(NanNew(bson->_dbRefDbRefString)) }; + return NanNew(bson->dbrefConstructor)->NewInstance(3, argv); + } + else + { + return returnObject; + } +} + +Handle BSONDeserializer::DeserializeArray(bool promoteLongs) +{ + uint32_t length = ReadUInt32(); + if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); + + BSONDeserializer documentDeserializer(*this, length-4); + return documentDeserializer.DeserializeArrayInternal(promoteLongs); +} + +Handle BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) +{ + Local returnArray = NanNew(); + + while(HasMoreData()) + { + BsonType type = (BsonType) ReadByte(); + uint32_t index = ReadIntegerString(); + const Handle& value = DeserializeValue(type, promoteLongs); + returnArray->Set(index, value); + } + if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); + + return returnArray; +} + +Handle BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) +{ + switch(type) + { + case BSON_TYPE_STRING: + return ReadString(); + + case BSON_TYPE_INT: + return NanNew(ReadInt32()); + + case BSON_TYPE_NUMBER: + return NanNew(ReadDouble()); + + case BSON_TYPE_NULL: + return NanNull(); + + case BSON_TYPE_UNDEFINED: + return NanNull(); + + case BSON_TYPE_TIMESTAMP: + { + int32_t lowBits = ReadInt32(); + int32_t highBits = ReadInt32(); + Local argv[] = { NanNew(lowBits), NanNew(highBits) }; + return NanNew(bson->timestampConstructor)->NewInstance(2, argv); + } + + case BSON_TYPE_BOOLEAN: + return (ReadByte() != 0) ? NanTrue() : NanFalse(); + + case BSON_TYPE_REGEXP: + { + const Handle& regex = ReadCString(); + if(regex->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); + int32_t options = ReadRegexOptions(); + return NanNew(regex->ToString(), (RegExp::Flags) options); + } + + case BSON_TYPE_CODE: + { + const Local& code = ReadString(); + const Local& scope = NanNew(); + Local argv[] = { code, scope }; + return NanNew(bson->codeConstructor)->NewInstance(2, argv); + } + + case BSON_TYPE_CODE_W_SCOPE: + { + ReadUInt32(); + const Local& code = ReadString(); + const Handle& scope = DeserializeDocument(promoteLongs); + Local argv[] = { code, scope->ToObject() }; + return NanNew(bson->codeConstructor)->NewInstance(2, argv); + } + + case BSON_TYPE_OID: + { + Local argv[] = { ReadObjectId() }; + return NanNew(bson->objectIDConstructor)->NewInstance(1, argv); + } + + case BSON_TYPE_BINARY: + { + uint32_t length = ReadUInt32(); + uint32_t subType = ReadByte(); + if(subType == 0x02) { + length = ReadInt32(); + } + + Local buffer = NanNewBufferHandle(p, length); + p += length; + + Handle argv[] = { buffer, NanNew(subType) }; + return NanNew(bson->binaryConstructor)->NewInstance(2, argv); + } + + case BSON_TYPE_LONG: + { + // Read 32 bit integers + int32_t lowBits = (int32_t) ReadInt32(); + int32_t highBits = (int32_t) ReadInt32(); + + // Promote long is enabled + if(promoteLongs) { + // If value is < 2^53 and >-2^53 + if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { + // Adjust the pointer and read as 64 bit value + p -= 8; + // Read the 64 bit value + int64_t finalValue = (int64_t) ReadInt64(); + return NanNew(finalValue); + } + } + + // Decode the Long value + Local argv[] = { NanNew(lowBits), NanNew(highBits) }; + return NanNew(bson->longConstructor)->NewInstance(2, argv); + } + + case BSON_TYPE_DATE: + return NanNew((double) ReadInt64()); + + case BSON_TYPE_ARRAY: + return DeserializeArray(promoteLongs); + + case BSON_TYPE_OBJECT: + return DeserializeDocument(promoteLongs); + + case BSON_TYPE_SYMBOL: + { + const Local& string = ReadString(); + Local argv[] = { string }; + return NanNew(bson->symbolConstructor)->NewInstance(1, argv); + } + + case BSON_TYPE_MIN_KEY: + return NanNew(bson->minKeyConstructor)->NewInstance(); + + case BSON_TYPE_MAX_KEY: + return NanNew(bson->maxKeyConstructor)->NewInstance(); + + default: + ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); + } + + return NanNull(); +} + +Persistent BSON::constructor_template; + +BSON::BSON() : ObjectWrap() +{ + // Setup pre-allocated comparision objects + NanAssignPersistent(_bsontypeString, NanNew("_bsontype")); + NanAssignPersistent(_longLowString, NanNew("low_")); + NanAssignPersistent(_longHighString, NanNew("high_")); + NanAssignPersistent(_objectIDidString, NanNew("id")); + NanAssignPersistent(_binaryPositionString, NanNew("position")); + NanAssignPersistent(_binarySubTypeString, NanNew("sub_type")); + NanAssignPersistent(_binaryBufferString, NanNew("buffer")); + NanAssignPersistent(_doubleValueString, NanNew("value")); + NanAssignPersistent(_symbolValueString, NanNew("value")); + NanAssignPersistent(_dbRefRefString, NanNew("$ref")); + NanAssignPersistent(_dbRefIdRefString, NanNew("$id")); + NanAssignPersistent(_dbRefDbRefString, NanNew("$db")); + NanAssignPersistent(_dbRefNamespaceString, NanNew("namespace")); + NanAssignPersistent(_dbRefDbString, NanNew("db")); + NanAssignPersistent(_dbRefOidString, NanNew("oid")); + NanAssignPersistent(_codeCodeString, NanNew("code")); + NanAssignPersistent(_codeScopeString, NanNew("scope")); + NanAssignPersistent(_toBSONString, NanNew("toBSON")); + + NanAssignPersistent(longString, NanNew("Long")); + NanAssignPersistent(objectIDString, NanNew("ObjectID")); + NanAssignPersistent(binaryString, NanNew("Binary")); + NanAssignPersistent(codeString, NanNew("Code")); + NanAssignPersistent(dbrefString, NanNew("DBRef")); + NanAssignPersistent(symbolString, NanNew("Symbol")); + NanAssignPersistent(doubleString, NanNew("Double")); + NanAssignPersistent(timestampString, NanNew("Timestamp")); + NanAssignPersistent(minKeyString, NanNew("MinKey")); + NanAssignPersistent(maxKeyString, NanNew("MaxKey")); +} + +void BSON::Initialize(v8::Handle target) +{ + // Grab the scope of the call from Node + NanScope(); + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("BSON")); + + // Instance methods + NODE_SET_PROTOTYPE_METHOD(t, "calculateObjectSize", CalculateObjectSize); + NODE_SET_PROTOTYPE_METHOD(t, "serialize", BSONSerialize); + NODE_SET_PROTOTYPE_METHOD(t, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); + NODE_SET_PROTOTYPE_METHOD(t, "deserialize", BSONDeserialize); + NODE_SET_PROTOTYPE_METHOD(t, "deserializeStream", BSONDeserializeStream); + + NanAssignPersistent(constructor_template, t); + + target->ForceSet(NanNew("BSON"), t->GetFunction()); +} + +// Create a new instance of BSON and passing it the existing context +NAN_METHOD(BSON::New) +{ + NanScope(); + + // Check that we have an array + if(args.Length() == 1 && args[0]->IsArray()) + { + // Cast the array to a local reference + Local array = Local::Cast(args[0]); + + if(array->Length() > 0) + { + // Create a bson object instance and return it + BSON *bson = new BSON(); + + uint32_t foundClassesMask = 0; + + // Iterate over all entries to save the instantiate functions + for(uint32_t i = 0; i < array->Length(); i++) { + // Let's get a reference to the function + Local func = Local::Cast(array->Get(i)); + Local functionName = func->GetName()->ToString(); + + // Save the functions making them persistant handles (they don't get collected) + if(functionName->StrictEquals(NanNew(bson->longString))) { + NanAssignPersistent(bson->longConstructor, func); + foundClassesMask |= 1; + } else if(functionName->StrictEquals(NanNew(bson->objectIDString))) { + NanAssignPersistent(bson->objectIDConstructor, func); + foundClassesMask |= 2; + } else if(functionName->StrictEquals(NanNew(bson->binaryString))) { + NanAssignPersistent(bson->binaryConstructor, func); + foundClassesMask |= 4; + } else if(functionName->StrictEquals(NanNew(bson->codeString))) { + NanAssignPersistent(bson->codeConstructor, func); + foundClassesMask |= 8; + } else if(functionName->StrictEquals(NanNew(bson->dbrefString))) { + NanAssignPersistent(bson->dbrefConstructor, func); + foundClassesMask |= 0x10; + } else if(functionName->StrictEquals(NanNew(bson->symbolString))) { + NanAssignPersistent(bson->symbolConstructor, func); + foundClassesMask |= 0x20; + } else if(functionName->StrictEquals(NanNew(bson->doubleString))) { + NanAssignPersistent(bson->doubleConstructor, func); + foundClassesMask |= 0x40; + } else if(functionName->StrictEquals(NanNew(bson->timestampString))) { + NanAssignPersistent(bson->timestampConstructor, func); + foundClassesMask |= 0x80; + } else if(functionName->StrictEquals(NanNew(bson->minKeyString))) { + NanAssignPersistent(bson->minKeyConstructor, func); + foundClassesMask |= 0x100; + } else if(functionName->StrictEquals(NanNew(bson->maxKeyString))) { + NanAssignPersistent(bson->maxKeyConstructor, func); + foundClassesMask |= 0x200; + } + } + + // Check if we have the right number of constructors otherwise throw an error + if(foundClassesMask != 0x3ff) { + delete bson; + return NanThrowError("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); + } else { + bson->Wrap(args.This()); + NanReturnValue(args.This()); + } + } + else + { + return NanThrowError("No types passed in"); + } + } + else + { + return NanThrowTypeError("Argument passed in must be an array of types"); + } +} + +//------------------------------------------------------------------------------------------------ +//------------------------------------------------------------------------------------------------ +//------------------------------------------------------------------------------------------------ +//------------------------------------------------------------------------------------------------ + +NAN_METHOD(BSON::BSONDeserialize) +{ + NanScope(); + + // Fail if the first argument is not a string or a buffer + if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) + return NanThrowError("First Argument must be a Buffer or String."); + + // Promote longs + bool promoteLongs = true; + + // If we have an options object + if(args.Length() == 2 && args[1]->IsObject()) { + Local options = args[1]->ToObject(); + + if(options->Has(NanNew("promoteLongs"))) { + promoteLongs = options->Get(NanNew("promoteLongs"))->ToBoolean()->Value(); + } + } + + // Define pointer to data + Local obj = args[0]->ToObject(); + + // Unpack the BSON parser instance + BSON *bson = ObjectWrap::Unwrap(args.This()); + + // If we passed in a buffer, let's unpack it, otherwise let's unpack the string + if(Buffer::HasInstance(obj)) + { +#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 + Local buffer = ObjectWrap::Unwrap(obj); + char* data = buffer->data(); + size_t length = buffer->length(); +#else + char* data = Buffer::Data(obj); + size_t length = Buffer::Length(obj); +#endif + + // Validate that we have at least 5 bytes + if(length < 5) return NanThrowError("corrupt bson message < 5 bytes long"); + + try + { + BSONDeserializer deserializer(bson, data, length); + // deserializer.promoteLongs = promoteLongs; + NanReturnValue(deserializer.DeserializeDocument(promoteLongs)); + } + catch(char* exception) + { + Local error = NanNew(exception); + free(exception); + return NanThrowError(error); + } + + } + else + { + // The length of the data for this encoding + ssize_t len = DecodeBytes(args[0], BINARY); + + // Validate that we have at least 5 bytes + if(len < 5) return NanThrowError("corrupt bson message < 5 bytes long"); + + // Let's define the buffer size + char* data = (char *)malloc(len); + if(data == NULL) die("Failed to allocate char buffer for BSON serialization"); + DecodeWrite(data, len, args[0], BINARY); + + try + { + BSONDeserializer deserializer(bson, data, len); + // deserializer.promoteLongs = promoteLongs; + Handle result = deserializer.DeserializeDocument(promoteLongs); + free(data); + NanReturnValue(result); + + } + catch(char* exception) + { + Local error = NanNew(exception); + free(exception); + free(data); + return NanThrowError(error); + } + } +} + +Local BSON::GetSerializeObject(const Handle& argValue) +{ + Local object = argValue->ToObject(); + if(object->Has(NanNew(_toBSONString))) + { + const Local& toBSON = object->Get(NanNew(_toBSONString)); + if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); + + Local result = Local::Cast(toBSON)->Call(object, 0, NULL); + if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); + return result->ToObject(); + } + else + { + return object; + } +} + +NAN_METHOD(BSON::BSONSerialize) +{ + NanScope(); + + if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); + if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); + if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); + if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); + if(args.Length() > 4) return NanThrowError("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); + + // Check if we have an array as the object + if(args[0]->IsArray()) return NanThrowError("Only javascript objects supported"); + + // Unpack the BSON parser instance + BSON *bson = ObjectWrap::Unwrap(args.This()); + + // Calculate the total size of the document in binary form to ensure we only allocate memory once + // With serialize function + bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); + + char *serialized_object = NULL; + size_t object_size; + try + { + Local object = bson->GetSerializeObject(args[0]); + + BSONSerializer counter(bson, false, serializeFunctions); + counter.SerializeDocument(object); + object_size = counter.GetSerializeSize(); + + // Allocate the memory needed for the serialization + serialized_object = (char *)malloc(object_size); + if(serialized_object == NULL) die("Failed to allocate memory for object"); + + // Check if we have a boolean value + bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); + BSONSerializer data(bson, checkKeys, serializeFunctions, serialized_object); + data.SerializeDocument(object); + } + catch(char *err_msg) + { + free(serialized_object); + Local error = NanNew(err_msg); + free(err_msg); + return NanThrowError(error); + } + + // If we have 3 arguments + if(args.Length() == 3 || args.Length() == 4) + { + Local buffer = NanNewBufferHandle(serialized_object, object_size); + free(serialized_object); + NanReturnValue(buffer); + } + else + { + Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); + free(serialized_object); + NanReturnValue(bin_value); + } +} + +NAN_METHOD(BSON::CalculateObjectSize) +{ + NanScope(); + // Ensure we have a valid object + if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One argument required - [object]"); + if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("Two arguments required - [object, boolean]"); + if(args.Length() > 3) return NanThrowError("One or two arguments required - [object] or [object, boolean]"); + + // Unpack the BSON parser instance + BSON *bson = ObjectWrap::Unwrap(args.This()); + bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); + BSONSerializer countSerializer(bson, false, serializeFunctions); + countSerializer.SerializeDocument(args[0]); + + // Return the object size + NanReturnValue(NanNew((uint32_t) countSerializer.GetSerializeSize())); +} + +NAN_METHOD(BSON::SerializeWithBufferAndIndex) +{ + NanScope(); + + //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { + // Ensure we have the correct values + if(args.Length() > 5) return NanThrowError("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); + if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return NanThrowError("Four parameters required [object, boolean, Buffer, int]"); + if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return NanThrowError("Four parameters required [object, boolean, Buffer, int, boolean]"); + + uint32_t index; + size_t object_size; + + try + { + BSON *bson = ObjectWrap::Unwrap(args.This()); + + Local obj = args[2]->ToObject(); + char* data = Buffer::Data(obj); + size_t length = Buffer::Length(obj); + + index = args[3]->Uint32Value(); + bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); + bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); + + BSONSerializer dataSerializer(bson, checkKeys, serializeFunctions, data+index); + dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); + object_size = dataSerializer.GetSerializeSize(); + + if(object_size + index > length) return NanThrowError("Serious error - overflowed buffer!!"); + } + catch(char *exception) + { + Local error = NanNew(exception); + free(exception); + return NanThrowError(error); + } + + NanReturnValue(NanNew((uint32_t) (index + object_size - 1))); +} + +NAN_METHOD(BSON::BSONDeserializeStream) +{ + NanScope(); + + // At least 3 arguments required + if(args.Length() < 5) return NanThrowError("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); + + // If the number of argumets equals 3 + if(args.Length() >= 5) + { + if(!Buffer::HasInstance(args[0])) return NanThrowError("First argument must be Buffer instance"); + if(!args[1]->IsUint32()) return NanThrowError("Second argument must be a positive index number"); + if(!args[2]->IsUint32()) return NanThrowError("Third argument must be a positive number of documents to deserialize"); + if(!args[3]->IsArray()) return NanThrowError("Fourth argument must be an array the size of documents to deserialize"); + if(!args[4]->IsUint32()) return NanThrowError("Sixth argument must be a positive index number"); + } + + // If we have 4 arguments + if(args.Length() == 6 && !args[5]->IsObject()) return NanThrowError("Fifth argument must be an object with options"); + + // Define pointer to data + Local obj = args[0]->ToObject(); + uint32_t numberOfDocuments = args[2]->Uint32Value(); + uint32_t index = args[1]->Uint32Value(); + uint32_t resultIndex = args[4]->Uint32Value(); + bool promoteLongs = true; + + // Check for the value promoteLongs in the options object + if(args.Length() == 6) { + Local options = args[5]->ToObject(); + + // Check if we have the promoteLong variable + if(options->Has(NanNew("promoteLongs"))) { + promoteLongs = options->Get(NanNew("promoteLongs"))->ToBoolean()->Value(); + } + } + + // Unpack the BSON parser instance + BSON *bson = ObjectWrap::Unwrap(args.This()); + + // Unpack the buffer variable +#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 + Local buffer = ObjectWrap::Unwrap(obj); + char* data = buffer->data(); + size_t length = buffer->length(); +#else + char* data = Buffer::Data(obj); + size_t length = Buffer::Length(obj); +#endif + + // Fetch the documents + Local documents = args[3]->ToObject(); + + BSONDeserializer deserializer(bson, data+index, length-index); + for(uint32_t i = 0; i < numberOfDocuments; i++) + { + try + { + documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); + } + catch (char* exception) + { + Local error = NanNew(exception); + free(exception); + return NanThrowError(error); + } + } + + // Return new index of parsing + NanReturnValue(NanNew((uint32_t) (index + deserializer.GetSerializeSize()))); +} + +// Exporting function +extern "C" void init(Handle target) +{ + NanScope(); + BSON::Initialize(target); +} + +NODE_MODULE(bson, BSON::Initialize); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.h new file mode 100644 index 0000000..a7feff7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/bson.h @@ -0,0 +1,278 @@ +//=========================================================================== + +#ifndef BSON_H_ +#define BSON_H_ + +//=========================================================================== + +#ifdef __arm__ +#define USE_MISALIGNED_MEMORY_ACCESS 0 +#else +#define USE_MISALIGNED_MEMORY_ACCESS 1 +#endif + +#include +#include +#include +#include "nan.h" + +using namespace v8; +using namespace node; + +//=========================================================================== + +enum BsonType +{ + BSON_TYPE_NUMBER = 1, + BSON_TYPE_STRING = 2, + BSON_TYPE_OBJECT = 3, + BSON_TYPE_ARRAY = 4, + BSON_TYPE_BINARY = 5, + BSON_TYPE_UNDEFINED = 6, + BSON_TYPE_OID = 7, + BSON_TYPE_BOOLEAN = 8, + BSON_TYPE_DATE = 9, + BSON_TYPE_NULL = 10, + BSON_TYPE_REGEXP = 11, + BSON_TYPE_CODE = 13, + BSON_TYPE_SYMBOL = 14, + BSON_TYPE_CODE_W_SCOPE = 15, + BSON_TYPE_INT = 16, + BSON_TYPE_TIMESTAMP = 17, + BSON_TYPE_LONG = 18, + BSON_TYPE_MAX_KEY = 0x7f, + BSON_TYPE_MIN_KEY = 0xff +}; + +//=========================================================================== + +template class BSONSerializer; + +class BSON : public ObjectWrap { +public: + BSON(); + ~BSON() {} + + static void Initialize(Handle target); + static NAN_METHOD(BSONDeserializeStream); + + // JS based objects + static NAN_METHOD(BSONSerialize); + static NAN_METHOD(BSONDeserialize); + + // Calculate size of function + static NAN_METHOD(CalculateObjectSize); + static NAN_METHOD(SerializeWithBufferAndIndex); + + // Constructor used for creating new BSON objects from C++ + static Persistent constructor_template; + +private: + static NAN_METHOD(New); + static Handle deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item); + + // BSON type instantiate functions + Persistent longConstructor; + Persistent objectIDConstructor; + Persistent binaryConstructor; + Persistent codeConstructor; + Persistent dbrefConstructor; + Persistent symbolConstructor; + Persistent doubleConstructor; + Persistent timestampConstructor; + Persistent minKeyConstructor; + Persistent maxKeyConstructor; + + // Equality Objects + Persistent longString; + Persistent objectIDString; + Persistent binaryString; + Persistent codeString; + Persistent dbrefString; + Persistent symbolString; + Persistent doubleString; + Persistent timestampString; + Persistent minKeyString; + Persistent maxKeyString; + + // Equality speed up comparison objects + Persistent _bsontypeString; + Persistent _longLowString; + Persistent _longHighString; + Persistent _objectIDidString; + Persistent _binaryPositionString; + Persistent _binarySubTypeString; + Persistent _binaryBufferString; + Persistent _doubleValueString; + Persistent _symbolValueString; + + Persistent _dbRefRefString; + Persistent _dbRefIdRefString; + Persistent _dbRefDbRefString; + Persistent _dbRefNamespaceString; + Persistent _dbRefDbString; + Persistent _dbRefOidString; + + Persistent _codeCodeString; + Persistent _codeScopeString; + Persistent _toBSONString; + + Local GetSerializeObject(const Handle& object); + + template friend class BSONSerializer; + friend class BSONDeserializer; +}; + +//=========================================================================== + +class CountStream +{ +public: + CountStream() : count(0) { } + + void WriteByte(int value) { ++count; } + void WriteByte(const Handle&, const Handle&) { ++count; } + void WriteBool(const Handle& value) { ++count; } + void WriteInt32(int32_t value) { count += 4; } + void WriteInt32(const Handle& value) { count += 4; } + void WriteInt32(const Handle& object, const Handle& key) { count += 4; } + void WriteInt64(int64_t value) { count += 8; } + void WriteInt64(const Handle& value) { count += 8; } + void WriteDouble(double value) { count += 8; } + void WriteDouble(const Handle& value) { count += 8; } + void WriteDouble(const Handle&, const Handle&) { count += 8; } + void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; } + void WriteLengthPrefixedString(const Local& value) { count += value->Utf8Length()+5; } + void WriteObjectId(const Handle& object, const Handle& key) { count += 12; } + void WriteString(const Local& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator + void WriteData(const char* data, size_t length) { count += length; } + + void* BeginWriteType() { ++count; return NULL; } + void CommitType(void*, BsonType) { } + void* BeginWriteSize() { count += 4; return NULL; } + void CommitSize(void*) { } + + size_t GetSerializeSize() const { return count; } + + // Do nothing. CheckKey is implemented for DataStream + void CheckKey(const Local&) { } + +private: + size_t count; +}; + +class DataStream +{ +public: + DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { } + + void WriteByte(int value) { *p++ = value; } + void WriteByte(const Handle& object, const Handle& key) { *p++ = object->Get(key)->Int32Value(); } +#if USE_MISALIGNED_MEMORY_ACCESS + void WriteInt32(int32_t value) { *reinterpret_cast(p) = value; p += 4; } + void WriteInt64(int64_t value) { *reinterpret_cast(p) = value; p += 8; } + void WriteDouble(double value) { *reinterpret_cast(p) = value; p += 8; } +#else + void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; } + void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; } + void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; } +#endif + void WriteBool(const Handle& value) { WriteByte(value->BooleanValue() ? 1 : 0); } + void WriteInt32(const Handle& value) { WriteInt32(value->Int32Value()); } + void WriteInt32(const Handle& object, const Handle& key) { WriteInt32(object->Get(key)); } + void WriteInt64(const Handle& value) { WriteInt64(value->IntegerValue()); } + void WriteDouble(const Handle& value) { WriteDouble(value->NumberValue()); } + void WriteDouble(const Handle& object, const Handle& key) { WriteDouble(object->Get(key)); } + void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; } + void WriteLengthPrefixedString(const Local& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); } + void WriteObjectId(const Handle& object, const Handle& key); + void WriteString(const Local& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator. + void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; } + + void* BeginWriteType() { void* returnValue = p; p++; return returnValue; } + void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast(beginPoint) = value; } + void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; } + +#if USE_MISALIGNED_MEMORY_ACCESS + void CommitSize(void* beginPoint) { *reinterpret_cast(beginPoint) = (int32_t) (p - (char*) beginPoint); } +#else + void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); } +#endif + + size_t GetSerializeSize() const { return p - destinationBuffer; } + + void CheckKey(const Local& keyName); + +protected: + char *const destinationBuffer; // base, never changes + char* p; // cursor into buffer +}; + +template class BSONSerializer : public T +{ +private: + typedef T Inherited; + +public: + BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } + BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } + + void SerializeDocument(const Handle& value); + void SerializeArray(const Handle& value); + void SerializeValue(void* typeLocation, const Handle value); + +private: + bool checkKeys; + bool serializeFunctions; + BSON* bson; +}; + +//=========================================================================== + +class BSONDeserializer +{ +public: + BSONDeserializer(BSON* aBson, char* data, size_t length); + BSONDeserializer(BSONDeserializer& parentSerializer, size_t length); + + Handle DeserializeDocument(bool promoteLongs); + + bool HasMoreData() const { return p < pEnd; } + Handle ReadCString(); + uint32_t ReadIntegerString(); + int32_t ReadRegexOptions(); + Local ReadString(); + Local ReadObjectId(); + + unsigned char ReadByte() { return *reinterpret_cast(p++); } +#if USE_MISALIGNED_MEMORY_ACCESS + int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } + uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } + int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast(p); p += 8; return returnValue; } + double ReadDouble() { double returnValue = *reinterpret_cast(p); p += 8; return returnValue; } +#else + int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } + uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } + int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } + double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } +#endif + + size_t GetSerializeSize() const { return p - pStart; } + +private: + Handle DeserializeArray(bool promoteLongs); + Handle DeserializeValue(BsonType type, bool promoteLongs); + Handle DeserializeDocumentInternal(bool promoteLongs); + Handle DeserializeArrayInternal(bool promoteLongs); + + BSON* bson; + char* const pStart; + char* p; + char* const pEnd; +}; + +//=========================================================================== + +#endif // BSON_H_ + +//=========================================================================== diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/index.js new file mode 100644 index 0000000..a4196ff --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/index.js @@ -0,0 +1,31 @@ +var bson = null; + +try { + // Load the precompiled win32 binary + if(process.platform == "win32" && process.arch == "x64") { + bson = require('./win32/x64/bson'); + } else if(process.platform == "win32" && process.arch == "ia32") { + bson = require('./win32/ia32/bson'); + } else { + bson = require('../build/Release/bson'); + } +} catch(err) { + // Attempt to load the release bson version + try { + bson = require('../build/Release/bson'); + } catch (err) { + console.dir(err) + console.error("js-bson: Failed to load c++ bson extension, using pure JS version"); + throw new Error("js-bson: Failed to load c++ bson extension, using pure JS version"); + } +} + +exports.BSON = bson.BSON; + +// Just add constants tot he Native BSON parser +exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; +exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/wscript b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/wscript new file mode 100644 index 0000000..40f5317 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/ext/wscript @@ -0,0 +1,39 @@ +import Options +from os import unlink, symlink, popen +from os.path import exists + +srcdir = "." +blddir = "build" +VERSION = "0.1.0" + +def set_options(opt): + opt.tool_options("compiler_cxx") + opt.add_option( '--debug' + , action='store_true' + , default=False + , help='Build debug variant [Default: False]' + , dest='debug' + ) + +def configure(conf): + conf.check_tool("compiler_cxx") + conf.check_tool("node_addon") + conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops']) + + # conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra']) + # conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE') + +def build(bld): + obj = bld.new_task_gen("cxx", "shlib", "node_addon") + obj.target = "bson" + obj.source = ["bson.cc"] + # obj.uselib = "NODE" + +def shutdown(): + # HACK to get compress.node out of build directory. + # better way to do this? + if Options.commands['clean']: + if exists('bson.node'): unlink('bson.node') + else: + if exists('build/default/bson.node') and not exists('bson.node'): + symlink('build/default/bson.node', 'bson.node') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/index.js new file mode 100644 index 0000000..f545f27 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/index.js @@ -0,0 +1,14 @@ +var BSON = require('./ext').BSON; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = BSON; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary.js new file mode 100644 index 0000000..5d0acfa --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * Module dependencies. + * @ignore + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, 'binary', offset); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + return this.buffer; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary_parser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary_parser.js new file mode 100644 index 0000000..d2fc811 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/binary_parser.js @@ -0,0 +1,385 @@ +/** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/code.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +module.exports = Code; +module.exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/db_ref.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +module.exports = DBRef; +module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/double.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +} + +module.exports = Double; +module.exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/long.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/long.js @@ -0,0 +1,856 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/max_key.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/min_key.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/objectid.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/objectid.js new file mode 100644 index 0000000..1d4894a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/objectid.js @@ -0,0 +1,274 @@ +/** + * Module dependencies. + * @ignore + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + if(!(this instanceof ObjectID)) return new ObjectID(id); + if((id instanceof ObjectID)) return id; + + this._bsontype = 'ObjectID'; + var __id = null; + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if(!valid && id != null){ + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if(valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {string} return the 12 byte id binary string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' != typeof time) { + time = parseInt(Date.now()/1000,10); + } + + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals (otherID) { + if(otherID == null) return false; + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if(id == null) return false; + + if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) { + return false; + } else { + // Check specifically for hex correctness + if(typeof id == 'string' && id.length == 24) return checkForHexRegExp.test(id); + return true; + } +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/symbol.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +module.exports = Symbol; +module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/timestamp.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/.bin/node-pre-gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/.bin/node-pre-gyp new file mode 120000 index 0000000..599cb3a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/.bin/node-pre-gyp @@ -0,0 +1 @@ +../node-pre-gyp/bin/node-pre-gyp.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/.dntrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/.dntrc new file mode 100644 index 0000000..47971da --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/.dntrc @@ -0,0 +1,30 @@ +## DNT config file +## see https://github.com/rvagg/dnt + +NODE_VERSIONS="\ + master \ + v0.11.13 \ + v0.10.30 \ + v0.10.29 \ + v0.10.28 \ + v0.10.26 \ + v0.10.25 \ + v0.10.24 \ + v0.10.23 \ + v0.10.22 \ + v0.10.21 \ + v0.10.20 \ + v0.10.19 \ + v0.8.28 \ + v0.8.27 \ + v0.8.26 \ + v0.8.24 \ +" +OUTPUT_PREFIX="nan-" +TEST_CMD=" \ + cd /dnt/ && \ + npm install && \ + node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ + node_modules/.bin/tap --gc test/js/*-test.js \ +" + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/CHANGELOG.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/CHANGELOG.md new file mode 100644 index 0000000..8e8f052 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/CHANGELOG.md @@ -0,0 +1,294 @@ +# NAN ChangeLog + +**Version 1.8.4: current Node 12: 0.12.2, Node 10: 0.10.38, io.js: 1.8.1** + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 + +### 1.7.0 Feb 28 2015 + + - Feature: Made NanCallback::Call accept optional target 8d54da7 + - Feature: Support atom-shell 0.21 0b7f1bb + +### 1.6.2 Feb 6 2015 + + - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 + +### 1.6.1 Jan 23 2015 + + - Build: version bump + +### 1.5.3 Jan 23 2015 + + - Build: repackage + +### 1.6.0 Jan 23 2015 + + - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af + - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 + - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 + +### 1.5.2 Jan 23 2015 + + - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 + - Bugfix: Readded missing String constructors 18d828f + - Bugfix: Add overload handling NanNew(..) 5ef813b + - Bugfix: Fix uv_work_cb versioning 997e4ae + - Bugfix: Add function factory and test 4eca89c + - Bugfix: Add object template factory and test cdcb951 + - Correctness: Lifted an io.js related typedef c9490be + - Correctness: Make explicit downcasts of String lengths 00074e6 + - Windows: Limit the scope of disabled warning C4530 83d7deb + +### 1.5.1 Jan 15 2015 + + - Build: version bump + +### 1.4.3 Jan 15 2015 + + - Build: version bump + +### 1.4.2 Jan 15 2015 + + - Feature: Support io.js 0dbc5e8 + +### 1.5.0 Jan 14 2015 + + - Feature: Support io.js b003843 + - Correctness: Improved NanNew internals 9cd4f6a + - Feature: Implement progress to NanAsyncWorker 8d6a160 + +### 1.4.1 Nov 8 2014 + + - Bugfix: Handle DEBUG definition correctly + - Bugfix: Accept int as Boolean + +### 1.4.0 Nov 1 2014 + + - Feature: Added NAN_GC_CALLBACK 6a5c245 + - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 + - Correctness: Added constness to references in NanHasInstance 02c61cd + - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 + - Windoze: Shut Visual Studio up when compiling 8d558c1 + - License: Switch to plain MIT from custom hacked MIT license 11de983 + - Build: Added test target to Makefile e232e46 + - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 + - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 + - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 + +### 1.3.0 Aug 2 2014 + + - Added NanNew(std::string) + - Added NanNew(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) + - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) + - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + +### 1.2.0 Jun 5 2014 + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +### 1.1.2 May 28 2014 + + - Release to fix more stuff-ups in 1.1.1 + +### 1.1.1 May 28 2014 + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +### 1.1.0 May 25 2014 + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +### 1.0.0 May 4 2014 + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +### 0.8.0 Jan 9 2014 + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +### 0.7.1 Jan 9 2014 + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +### 0.7.0 Dec 17 2013 + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +### 0.6.0 Nov 21 2013 + + - Introduce NanNewLocal(v8::Handle value) for use in place of + v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 + +### 0.5.2 Nov 16 2013 + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +### 0.5.1 Nov 12 2013 + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +### 0.5.0 Nov 11 2013 + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +### 0.4.4 Nov 2 2013 + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +### 0.4.3 Nov 2 2013 + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +### 0.4.2 Nov 2 2013 + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +### 0.4.1 Sep 16 2013 + + - Added explicit `#include ` as it was removed from node.h for v0.11.8 + +### 0.4.0 Sep 2 2013 + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +### 0.3.2 Aug 30 2013 + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +### 0.3.1 Aug 20 2013 + + - fix "not all control paths return a value" compile warning on some platforms + +### 0.3.0 Aug 19 2013 + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local) to NanThrowError(Handle) + - Fixed leak in NanAsyncWorker when errmsg is used + +### 0.2.2 Aug 5 2013 + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +### 0.2.1 Aug 5 2013 + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +### 0.2.0 Aug 5 2013 + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle, v8::Handle) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +### 0.1.0 Jul 21 2013 + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent&, Handle)` + - Added `Local NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local[])` + - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/LICENSE.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/LICENSE.md new file mode 100644 index 0000000..95c2eb5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2015 NAN contributors +----------------------------------- + +*NAN contributors listed at * + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/README.md new file mode 100644 index 0000000..26f6947 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/README.md @@ -0,0 +1,1402 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** + +***Current version: 1.8.4*** + +*(See [CHANGELOG.md](https://github.com/iojs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) + +[![Build Status](https://api.travis-ci.org/iojs/nan.svg?branch=master)](http://travis-ci.org/iojs/nan) +[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Porting](#porting)** + * **[Governance & Contributing](#governance)** + + +## News & Updates + +### Apr-2015: 1.8.0 release + +* Support V8 4.2 +* Removed support for creating `Signature`s with arguments +* Backported thread local storage routines for libuv + +### Feb-2015: 1.7.0 release + +* Made `NanCallback::Call` accept optional target +* Support atom-shell 0.21 + +Node 0.12.0 is out and supported by NAN. So is atom-shell 0.21. `NanCallback::Call` now accepts an optional `target` argument like `NanMakeCallback`. + +### Jan-2015: 1.6.0 release + +* Deprecated `NanNewContextHandle` in favor of `NanNew` +* Added `NanSetCounterFunction`, `NanSetCreateHistogramFunction`, `NanSetAddHistogramSampleFunction` +* Added `NanIdleNotification`, `NanLowMemoryNotification`, `NanContextDisposedNotification` +* Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` + +### Jan-2015: 1.5.0 release + +* Support [io.js](https://github.com/iojs/io.js) thanks to [Ben Noordhuis](bnoordhuis) +* Rewritten NanNew internals thanks to [David Siegel](agnat) +* NanAsyncWorker now supports progress reporting thanks to [Brett Lawson](brett19) + +### Aug-2014: 1.3.0 release + +* `NanCString()` and `NanRawString()` have been deprecated in favour of new NanAsciiString, NanUtf8String and NanUcs2String. These classes manage the underlying memory for you in a safer way than just handing off an allocated array. You should now `*NanAsciiString(handle)` to access the raw `char` data, you can also allocate on the heap if you need to keep a reference. +* Two more NanMakeCallback overloads have been added to for parity with Node core. +* You can now `NanNew(std::string)` (use `NanNew(std::string&)` to pass by reference) +* NanSetTemplate, NanSetPrototypeTemplate and NanSetInstanceTemplate have been added. + +### May-2014: 1.1.0 release + +* We've deprecated `NanSymbol()`, you should just use `NanNew()` now. +* `NanNull()`, `NanUndefined()`, `NanTrue()`, `NanFalse()` all return `Local`s now. +* `nan_isolate` is gone, it was intended to be internal-only but if you were using it then you should switch to `v8::Isolate::GetCurrent()`. +* `NanNew()` has received some additional overload-love so you should be able to give it many kinds of values without specifying the ``. +* Lots of small fixes and additions to expand the V8 API coverage, *use the source, Luke*. + + +### May-2014: Major changes for V8 3.25 / Node 0.11.13 + +Node 0.11.11 and 0.11.12 were both broken releases for native add-ons, you simply can't properly compile against either of them for different reasons. But we now have a 0.11.13 release that jumps a couple of versions of V8 ahead and includes some more, major (traumatic) API changes. + +Because we are now nearing Node 0.12 and estimate that the version of V8 we are using in Node 0.11.13 will be close to the API we get for 0.12, we have taken the opportunity to not only *fix* NAN for 0.11.13 but make some major changes to improve the NAN API. + +We have **removed support for Node 0.11 versions prior to 0.11.13**. As usual, our tests are run against (and pass) the last 5 versions of Node 0.8 and Node 0.10. We also include Node 0.11.13 obviously. + +The major change is something that [Benjamin Byholm](kkoopa) has put many hours in to. We now have a fantastic new `NanNew(args)` interface for creating new `Local`s, this replaces `NanNewLocal()` and much more. If you look in [./nan.h](nan.h) you'll see a large number of overloaded versions of this method. In general you should be able to `NanNew(arguments)` for any type you want to make a `Local` from. This includes `Persistent` types, so we now have a `Local NanNew(const Persistent arg)` to replace `NanPersistentToLocal()`. + +We also now have `NanUndefined()`, `NanNull()`, `NanTrue()` and `NanFalse()`. Mainly because of the new requirement for an `Isolate` argument for each of the native V8 versions of this. + +V8 has now introduced an `EscapableHandleScope` from which you `scope.Escape(Local value)` to *return* a value from a one scope to another. This replaces the standard `HandleScope` and `scope.Close(Local value)`, although `HandleScope` still exists for when you don't need to return a handle to the caller. For NAN we are exposing it as `NanEscapableScope()` and `NanEscapeScope()`, while `NanScope()` is still how you create a new scope that doesn't need to return handles. For older versions of Node/V8, it'll still map to the older `HandleScope` functionality. + +`NanFromV8String()` was deprecated and has now been removed. You should use `NanCString()` or `NanRawString()` instead. + +Because `node::MakeCallback()` now takes an `Isolate`, and because it doesn't exist in older versions of Node, we've introduced `NanMakeCallback()`. You should *always* use this when calling a JavaScript function from C++. + +There's lots more, check out the Changelog in nan.h or look through [#86](https://github.com/iojs/nan/pull/86) for all the gory details. + +### Dec-2013: NanCString and NanRawString + +Two new functions have been introduced to replace the functionality that's been provided by `NanFromV8String` until now. NanCString has sensible defaults so it's super easy to fetch a null-terminated c-style string out of a `v8::String`. `NanFromV8String` is still around and has defaults that allow you to pass a single handle to fetch a `char*` while `NanRawString` requires a little more attention to arguments. + +### Nov-2013: Node 0.11.9+ breaking V8 change + +The version of V8 that's shipping with Node 0.11.9+ has changed the signature for new `Local`s to: `v8::Local::New(isolate, value)`, i.e. introducing the `isolate` argument and therefore breaking all new `Local` declarations for previous versions. NAN 0.6+ now includes a `NanNewLocal(value)` that can be used in place to work around this incompatibility and maintain compatibility with 0.8->0.11.9+ (minus a few early 0.11 releases). + +For example, if you wanted to return a `null` on a callback you will have to change the argument from `v8::Local::New(v8::Null())` to `NanNewLocal(v8::Null())`. + +### Nov-2013: Change to binding.gyp `"include_dirs"` for NAN + +Inclusion of NAN in a project's binding.gyp is now greatly simplified. You can now just use `" +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: + +``` python +"include_dirs" : [ + "` when compiling your addon. + + +## Example + +See **[LevelDOWN](https://github.com/rvagg/node-leveldown/pull/48)** for a full example of **NAN** in use. + +For a simpler example, see the **[async pi estimation example](https://github.com/iojs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + +Compare to the current 0.10 version of this example, found in the [node-addon-examples](https://github.com/iojs/node-addon-examples/tree/master/9_async_work) repository and also a 0.11 version of the same found [here](https://github.com/kkoopa/node-addon-examples/tree/5c01f58fc993377a567812597e54a83af69686d7/9_async_work). + +Note that there is no embedded version sniffing going on here and also the async work is made much simpler, see below for details on the `NanAsyncWorker` class. + +```c++ +// addon.cc +#include +#include +// ... + +using v8::FunctionTemplate; +using v8::Handle; +using v8::Object; +using v8::String; + +void InitAll(Handle exports) { + exports->Set(NanNew("calculateSync"), + NanNew(CalculateSync)->GetFunction()); + + exports->Set(NanNew("calculateAsync"), + NanNew(CalculateAsync)->GetFunction()); +} + +NODE_MODULE(addon, InitAll) +``` + +```c++ +// sync.h +#include +#include + +NAN_METHOD(CalculateSync); +``` + +```c++ +// sync.cc +#include +#include +#include "./sync.h" +// ... + +using v8::Number; + +// Simple synchronous access to the `Estimate()` function +NAN_METHOD(CalculateSync) { + NanScope(); + + // expect a number as the first argument + int points = args[0]->Uint32Value(); + double est = Estimate(points); + + NanReturnValue(NanNew(est)); +} +``` + +```c++ +// async.h +#include +#include + +NAN_METHOD(CalculateAsync); +``` + +```c++ +// async.cc +#include +#include +#include "./async.h" + +// ... + +using v8::Function; +using v8::Local; +using v8::Null; +using v8::Number; +using v8::Value; + +class PiWorker : public NanAsyncWorker { + public: + PiWorker(NanCallback *callback, int points) + : NanAsyncWorker(callback), points(points) {} + ~PiWorker() {} + + // Executed inside the worker-thread. + // It is not safe to access V8, or V8 data structures + // here, so everything we need for input and output + // should go on `this`. + void Execute () { + estimate = Estimate(points); + } + + // Executed when the async work is complete + // this function will be run inside the main event loop + // so it is safe to use V8 again + void HandleOKCallback () { + NanScope(); + + Local argv[] = { + NanNull() + , NanNew(estimate) + }; + + callback->Call(2, argv); + }; + + private: + int points; + double estimate; +}; + +// Asynchronous access to the `Estimate()` function +NAN_METHOD(CalculateAsync) { + NanScope(); + + int points = args[0]->Uint32Value(); + NanCallback *callback = new NanCallback(args[1].As()); + + NanAsyncQueueWorker(new PiWorker(callback, points)); + NanReturnUndefined(); +} +``` + + +## API + + * NAN_METHOD + * NAN_GETTER + * NAN_SETTER + * NAN_PROPERTY_GETTER + * NAN_PROPERTY_SETTER + * NAN_PROPERTY_ENUMERATOR + * NAN_PROPERTY_DELETER + * NAN_PROPERTY_QUERY + * NAN_INDEX_GETTER + * NAN_INDEX_SETTER + * NAN_INDEX_ENUMERATOR + * NAN_INDEX_DELETER + * NAN_INDEX_QUERY + * NAN_GC_CALLBACK + * NAN_WEAK_CALLBACK + * NAN_DEPRECATED + * NAN_INLINE + * NanNew + * NanUndefined + * NanNull + * NanTrue + * NanFalse + * NanReturnValue + * NanReturnUndefined + * NanReturnNull + * NanReturnEmptyString + * NanReturnThis + * NanReturnHolder + * NanScope + * NanEscapableScope + * NanEscapeScope + * NanLocker + * NanUnlocker + * NanGetInternalFieldPointer + * NanSetInternalFieldPointer + * NanObjectWrapHandle + * NanSymbol + * NanGetPointerSafe + * NanSetPointerSafe + * NanRawString + * NanCString + * NanAsciiString + * NanUtf8String + * NanUcs2String + * NanBooleanOptionValue + * NanUInt32OptionValue + * NanError, NanTypeError, NanRangeError + * NanThrowError, NanThrowTypeError, NanThrowRangeError, NanThrowError(Handle), NanThrowError(Handle, int) + * NanNewBufferHandle(char *, size_t, FreeCallback, void *), NanNewBufferHandle(char *, uint32_t), NanNewBufferHandle(uint32_t) + * NanBufferUse(char *, uint32_t) + * NanNewContextHandle + * NanGetCurrentContext + * NanHasInstance + * NanDisposePersistent + * NanAssignPersistent + * NanMakeWeakPersistent + * NanSetTemplate + * NanSetPrototypeTemplate + * NanSetInstanceTemplate + * NanMakeCallback + * NanEncode + * NanDecodeBytes + * NanDecodeWrite + * NanCompileScript + * NanRunScript + * NanAdjustExternalMemory + * NanAddGCEpilogueCallback + * NanAddGCPrologueCallback + * NanRemoveGCEpilogueCallback + * NanRemoveGCPrologueCallback + * NanGetHeapStatistics + * NanSetCounterFunction + * NanSetCreateHistogramFunction + * NanSetAddHistogramSampleFunction + * NanIdleNotification + * NanLowMemoryNotification + * NanContextDisposedNotification + * NanCallback + * NanAsyncWorker + * NanAsyncQueueWorker + + +### NAN_METHOD(methodname) + +Use `NAN_METHOD` to define your V8 accessible methods: + +```c++ +// .h: +class Foo : public node::ObjectWrap { + ... + + static NAN_METHOD(Bar); + static NAN_METHOD(Baz); +} + + +// .cc: +NAN_METHOD(Foo::Bar) { + ... +} + +NAN_METHOD(Foo::Baz) { + ... +} +``` + +The reason for this macro is because of the method signature change in 0.11: + +```c++ +// 0.10 and below: +Handle name(const Arguments& args) + +// 0.11 and above +void name(const FunctionCallbackInfo& args) +``` + +The introduction of `FunctionCallbackInfo` brings additional complications: + + +### NAN_GETTER(methodname) + +Use `NAN_GETTER` to declare your V8 accessible getters. You get a `Local` `property` and an appropriately typed `args` object that can act like the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_GETTER`. + + +### NAN_SETTER(methodname) + +Use `NAN_SETTER` to declare your V8 accessible setters. Same as `NAN_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_GETTER(cbname) +Use `NAN_PROPERTY_GETTER` to declare your V8 accessible property getters. You get a `Local` `property` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_GETTER`. + + +### NAN_PROPERTY_SETTER(cbname) +Use `NAN_PROPERTY_SETTER` to declare your V8 accessible property setters. Same as `NAN_PROPERTY_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_ENUMERATOR(cbname) +Use `NAN_PROPERTY_ENUMERATOR` to declare your V8 accessible property enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_PROPERTY_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_ENUMERATOR`. + + +### NAN_PROPERTY_DELETER(cbname) +Use `NAN_PROPERTY_DELETER` to declare your V8 accessible property deleters. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_DELETER`. + + +### NAN_PROPERTY_QUERY(cbname) +Use `NAN_PROPERTY_QUERY` to declare your V8 accessible property queries. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_QUERY`. + + +### NAN_INDEX_GETTER(cbname) +Use `NAN_INDEX_GETTER` to declare your V8 accessible index getters. You get a `uint32_t` `index` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_GETTER`. + + +### NAN_INDEX_SETTER(cbname) +Use `NAN_INDEX_SETTER` to declare your V8 accessible index setters. Same as `NAN_INDEX_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_INDEX_ENUMERATOR(cbname) +Use `NAN_INDEX_ENUMERATOR` to declare your V8 accessible index enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_INDEX_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_ENUMERATOR`. + + +### NAN_INDEX_DELETER(cbname) +Use `NAN_INDEX_DELETER` to declare your V8 accessible index deleters. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_DELETER`. + + +### NAN_INDEX_QUERY(cbname) +Use `NAN_INDEX_QUERY` to declare your V8 accessible index queries. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_QUERY`. + + +### NAN_GC_CALLBACK(cbname) +Use `NAN_GC_CALLBACK` to declare your callbacks for `NanAddGCEpilogueCallback` and `NanAddGCPrologueCallback`. You get arguments `GCType type` and `GCCallbackFlags flags`. + +```c++ +static Persistent callback; + +NAN_GC_CALLBACK(gcPrologueCallback) { + Local argv[] = {NanNew("prologue")}; + NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv); +} + +NAN_METHOD(Hook) { + NanScope(); + NanAssignPersistent(callback, args[0].As()); + NanAddGCPrologueCallback(gcPrologueCallback); + NanReturnValue(args.Holder()); +} +``` + + +### NAN_WEAK_CALLBACK(cbname) + +Use `NAN_WEAK_CALLBACK` to define your V8 WeakReference callbacks. There is an argument object `const _NanWeakCallbackData &data` allowing access to the weak object and the supplied parameter through its `GetValue` and `GetParameter` methods. You can even access the weak callback info object through the `GetCallbackInfo()`method, but you probably should not. `Revive()` keeps the weak object alive until the next GC round. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + int *parameter = data.GetParameter(); + NanMakeCallback(NanGetCurrentContext()->Global(), data.GetValue(), 0, NULL); + if ((*parameter)++ == 0) { + data.Revive(); + } else { + delete parameter; + } +} +``` + + +### NAN_DEPRECATED +Declares a function as deprecated. + +```c++ +static NAN_DEPRECATED NAN_METHOD(foo) { + ... +} +``` + + +### NAN_INLINE +Inlines a function. + +```c++ +NAN_INLINE int foo(int bar) { + ... +} +``` + + +### Local<T> NanNew<T>( ... ) + +Use `NanNew` to construct almost all v8 objects (bound `Script`s are constructed with `NanCompileScript(Handle)`) and make new local handles. + +```c++ +Local s = NanNew("value"); + +... + +Persistent o; + +... + +Local lo = NanNew(o); + +``` + + +### Local<Primitive> NanUndefined() + +Use instead of `Undefined()` + + +### Local<Primitive> NanNull() + +Use instead of `Null()` + + +### Local<Boolean> NanTrue() + +Use instead of `True()` + + +### Local<Boolean> NanFalse() + +Use instead of `False()` + + +### NanReturnValue(Handle<Value>) + +Use `NanReturnValue` when you want to return a value from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Bar) { + ... + + NanReturnValue(NanNew("FooBar!")); +} +``` + +No `return` statement required. + +For convenience, `NanReturnValue` also accepts common primitives directly by implicitly performing an overloaded `NanNew(T)`. + +```c++ +NanReturnValue("FooBar!"); +NanReturnValue(true); +NanReturnValue(12); +NanReturnValue(3.14); +``` + + +### NanReturnUndefined() + +Use `NanReturnUndefined` when you don't want to return anything from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnUndefined(); +} +``` + + +### NanReturnNull() + +Use `NanReturnNull` when you want to return `Null` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnNull(); +} +``` + + +### NanReturnEmptyString() + +Use `NanReturnEmptyString` when you want to return an empty `String` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnEmptyString(); +} +``` + + +### NanReturnThis() + +Use `NanReturnThis` when you want to return `This` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnThis(); +} +``` + + +### NanReturnHolder() + +Use `NanReturnHolder` when you want to return `Holder` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnHolder(); +} +``` + + +### NanScope() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanScope()` necessary, use it in place of `HandleScope scope` when you do not wish to return handles (`Handle` or `Local`) to the surrounding scope (or in functions directly exposed to V8, as they do not return values in the normal sense): + +```c++ +NAN_METHOD(Foo::Bar) { + NanScope(); + + NanReturnValue(NanNew("FooBar!")); +} +``` + +This method is not directly exposed to V8, nor does it return a handle, so it uses an unescapable scope: + +```c++ +bool Foo::Bar() { + NanScope(); + + Local val = NanFalse(); + ... + return val->Value(); +} +``` + + +### NanEscapableScope() + +The separation of handle scopes into escapable and inescapable scopes makes `NanEscapableScope()` necessary, use it in place of `HandleScope scope` when you later wish to return a handle (`Handle` or `Local`) from the scope, this is for internal functions not directly exposed to V8: + +```c++ +Handle Foo::Bar() { + NanEscapableScope(); + + return NanEscapeScope(NanNew("FooBar!")); +} +``` + + +### Local<T> NanEscapeScope(Handle<T> value); +Use together with `NanEscapableScope` to escape the scope. Corresponds to `HandleScope::Close` or `EscapableHandleScope::Escape`. + + +### NanLocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanLocker()` necessary, use it in place of `Locker locker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### NanUnlocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanUnlocker()` necessary, use it in place of `Unlocker unlocker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### void * NanGetInternalFieldPointer(Handle<Object>, int) + +Gets a pointer to the internal field with at `index` from a V8 `Object` handle. + +```c++ +Local obj; +... +NanGetInternalFieldPointer(obj, 0); +``` + +### void NanSetInternalFieldPointer(Handle<Object>, int, void *) + +Sets the value of the internal field at `index` on a V8 `Object` handle. + +```c++ +static Persistent dataWrapperCtor; +... +Local wrapper = NanNew(dataWrapperCtor)->NewInstance(); +NanSetInternalFieldPointer(wrapper, 0, this); +``` + + +### Local<Object> NanObjectWrapHandle(const node::ObjectWrap &obj) + +When you want to fetch the V8 object handle from a native object you've wrapped with Node's `ObjectWrap`, you should use `NanObjectWrapHandle`: + +```c++ +NanObjectWrapHandle(iterator)->Get(NanNew("end")) +``` + + +### ~~Local<String> NanSymbol(const char *)~~ + +Deprecated. Use `NanNew` instead. +~~Use to create string symbol objects (i.e. `v8::String::NewSymbol(x)`), for getting and setting object properties, or names of objects.~~ + +```c++ +bool foo = false; +if (obj->Has(NanNew("foo"))) + foo = optionsObj->Get(NanNew("foo"))->BooleanValue() +``` + + +### Type NanGetPointerSafe(Type *[, Type]) + +A helper for getting values from optional pointers. If the pointer is `NULL`, the function returns the optional default value, which defaults to `0`. Otherwise, the function returns the value the pointer points to. + +```c++ +char *plugh(uint32_t *optional) { + char res[] = "xyzzy"; + uint32_t param = NanGetPointerSafe(optional, 0x1337); + switch (param) { + ... + } + NanSetPointerSafe(optional, 0xDEADBEEF); +} +``` + + +### bool NanSetPointerSafe(Type *, Type) + +A helper for setting optional argument pointers. If the pointer is `NULL`, the function simply returns `false`. Otherwise, the value is assigned to the variable the pointer points to. + +```c++ +const char *plugh(size_t *outputsize) { + char res[] = "xyzzy"; + if !(NanSetPointerSafe(outputsize, strlen(res) + 1)) { + ... + } + + ... +} +``` + + +### ~~void* NanRawString(Handle<Value>, enum Nan::Encoding, size_t *, void *, size_t, int)~~ + +Deprecated. Use something else. + +~~When you want to convert a V8 `String` to a `char*` buffer, use `NanRawString`. You have to supply an encoding as well as a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows setting `String::WriteOptions`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:~~ + +```c++ +size_t count; +void* decoded = NanRawString(args[1], Nan::BASE64, &count, NULL, 0, String::HINT_MANY_WRITES_EXPECTED); +... +delete[] reinterpret_cast(decoded); +``` + + +### ~~char* NanCString(Handle<Value>, size_t *[, char *, size_t, int])~~ + +Deprecated. Use `String::Utf8Value` or `NanUtf8String` instead. + +~~When you want to convert a V8 `String` to a null-terminated C `char*` use `NanCString`. The resulting `char*` will be UTF-8-encoded, and you need to supply a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows optionally setting `String::WriteOptions`, which default to `v8::String::NO_OPTIONS`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:~~ + +```c++ +size_t count; +char* name = NanCString(args[0], &count); +... +delete[] name; +``` + + +### NanAsciiString + +Contrary to the name, this is not actually an ASCII string, it is a one-byte string with no particular encoding. Do not use unless you actually need this incorrect legacy behavior. Consider fixing your broken code instead. If you actually have a proper ASCII-string, use UTF-8, which is a proper superset of ASCII. +Convert a `String` to zero-terminated, sort-of Ascii-encoded `char *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanAsciiString(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanAsciiString baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanAsciiString *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanAsciiString(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + +### NanUtf8String + +Equivalent to `String::Utf8Value`, it only exists for the sake of completeness. +Convert a `String` to zero-terminated, Utf8-encoded `char *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUtf8String(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanUtf8String baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanUtf8String *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanUtf8String(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + + +### NanUcs2String + +Equivalent to `String::Value`, it only exists for the sake of completeness. +Convert a `String` to zero-terminated, Ucs2-encoded `uint16_t *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUcs2String(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanUcs2String baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanUcs2String *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanUcs2String(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + +### bool NanBooleanOptionValue(Handle<Value>, Handle<String>[, bool]) + +When you have an "options" object that you need to fetch properties from, boolean options can be fetched with this pair. They check first if the object exists (`IsEmpty`), then if the object has the given property (`Has`) then they get and convert/coerce the property to a `bool`. + +The optional last parameter is the *default* value, which is `false` if left off: + +```c++ +// `foo` is false unless the user supplies a truthy value for it +bool foo = NanBooleanOptionValue(optionsObj, NanNew("foo")); +// `bar` is true unless the user supplies a falsy value for it +bool bar = NanBooleanOptionValueDefTrue(optionsObj, NanNew("bar"), true); +``` + + +### uint32_t NanUInt32OptionValue(Handle<Value>, Handle<String>, uint32_t) + +Similar to `NanBooleanOptionValue`, use `NanUInt32OptionValue` to fetch an integer option from your options object. Can be any kind of JavaScript `Number` and it will be coerced to an unsigned 32-bit integer. + +Requires all 3 arguments as a default is not optional: + +```c++ +uint32_t count = NanUInt32OptionValue(optionsObj, NanNew("count"), 1024); +``` + + +### NanError(message), NanTypeError(message), NanRangeError(message) + +For making `Error`, `TypeError` and `RangeError` objects. + +```c++ +Local res = NanError("you must supply a callback argument"); +``` + + +### NanThrowError(message), NanThrowTypeError(message), NanThrowRangeError(message), NanThrowError(Local<Value>), NanThrowError(Local<Value>, int) + +For throwing `Error`, `TypeError` and `RangeError` objects. + +```c++ +NanThrowError("you must supply a callback argument"); +``` + +Can also handle any custom object you may want to throw. If used with the error code argument, it will add the supplied error code to the error object as a property called `code`. + + +### Local<Object> NanNewBufferHandle(char *, uint32_t), Local<Object> NanNewBufferHandle(uint32_t) + +The `Buffer` API has changed a little in Node 0.11, this helper provides consistent access to `Buffer` creation: + +```c++ +NanNewBufferHandle((char*)value.data(), value.size()); +``` + +Can also be used to initialize a `Buffer` with just a `size` argument. + +Can also be supplied with a `NanFreeCallback` and a hint for the garbage collector. + + +### Local<Object> NanBufferUse(char*, uint32_t) + +`Buffer::New(char*, uint32_t)` prior to 0.11 would make a copy of the data. +While it was possible to get around this, it required a shim by passing a +callback. So the new API `Buffer::Use(char*, uint32_t)` was introduced to remove +needing to use this shim. + +`NanBufferUse` uses the `char*` passed as the backing data, and will free the +memory automatically when the weak callback is called. Keep this in mind, as +careless use can lead to "double free or corruption" and other cryptic failures. + + +### bool NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>) + +Can be used to check the type of an object to determine it is of a particular class you have already defined and have a `Persistent` handle for. + + +### ~~Local<Context> NanNewContextHandle([ExtensionConfiguration*, Handle<ObjectTemplate>, Handle<Value>])~~ + +Deprecated. Use `NanNew` instead. + +~~Creates a new `Local` handle.~~ + +```c++ +Local ftmpl = NanNew(); +Local otmpl = ftmpl->InstanceTemplate(); +Local ctx = NanNewContextHandle(NULL, otmpl); +``` + + +### Local<Context> NanGetCurrentContext() + +Gets the current context. + +```c++ +Local ctx = NanGetCurrentContext(); +``` + + +### void NanDisposePersistent(Persistent<T> &) + +Use `NanDisposePersistent` to dispose a `Persistent` handle. + +```c++ +NanDisposePersistent(persistentHandle); +``` + + +### NanAssignPersistent(handle, object) + +Use `NanAssignPersistent` to assign a non-`Persistent` handle to a `Persistent` one. You can no longer just declare a `Persistent` handle and assign directly to it later, you have to `Reset` it in Node 0.11, so this makes it easier. + +In general it is now better to place anything you want to protect from V8's garbage collector as properties of a generic `Object` and then assign that to a `Persistent`. This works in older versions of Node also if you use `NanAssignPersistent`: + +```c++ +Persistent persistentHandle; + +... + +Local obj = NanNew(); +obj->Set(NanNew("key"), keyHandle); // where keyHandle might be a Local +NanAssignPersistent(persistentHandle, obj) +``` + + +### _NanWeakCallbackInfo<T, P>* NanMakeWeakPersistent(Handle<T>, P*, _NanWeakCallbackInfo<T, P>::Callback) + +Creates a weak persistent handle with the supplied parameter and `NAN_WEAK_CALLBACK`. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + +... + +} + +Local func; + +... + +int *parameter = new int(0); +NanMakeWeakPersistent(func, parameter, &weakCallback); +``` + + +### NanSetTemplate(templ, name, value [, attributes]) + +Use to add properties on object and function templates. + + +### NanSetPrototypeTemplate(templ, name, value [, attributes]) + +Use to add prototype properties on function templates. + + +### NanSetInstanceTemplate(templ, name, value [, attributes]) + +Use to add instance properties on function templates. + + +### NanMakeCallback(target, func, argc, argv) + +Use instead of `node::MakeCallback` to call javascript functions. This (or `NanCallback`) is the only proper way of calling functions. You must _*never, ever*_ directly use `Function::Call`, it will lead to run-time failures. + + +### NanEncode(const void*, size_t[, enum Nan::Encoding]) + +Replaces `node::Encode`. + + +### NanDecodeBytes(v8::Handle<v8::Value>[, enum Nan::Encoding]) + +Replaces `node::DecodeBytes`. + + +### NanDecodeWrite(char *, size_t, v8::Handle<v8::Value>[, enum Nan::Encoding]) + +Replaces `node::DecodeWrite`. + + +### NanCompileScript(Handle s [, const ScriptOrigin& origin]) + +Use to create new scripts bound to the current context. + + +### NanRunScript(script) + +Use to run both bound and unbound scripts. + + +### NanAdjustExternalMemory(int change_in_bytes) + +Simply does `AdjustAmountOfExternalAllocatedMemory`, note that the argument and returned value have type `int`. + + +### NanAddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCEpilogueCallback` + + +### NanAddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCPrologueCallback` + + +### NanRemoveGCEpilogueCallback(GCEpilogueCallback callback) + +Simply does `RemoveGCEpilogueCallback` + + +### NanRemoveGCPrologueCallback(GCPrologueCallback callback) + +Simply does `RemoveGCPrologueCallback` + + +### NanGetHeapStatistics(HeapStatistics *heap_statistics) + +Simply does `GetHeapStatistics` + + +### NanSetCounterFunction(CounterLookupCallback cb) + +Simply does `SetCounterFunction` + + +### NanSetCreateHistogramFunction(CreateHistogramCallback cb) + +Simply does `SetCreateHistogramFunction` + + +### NanSetAddHistogramSampleFunction(AddHistogramSampleCallback cb) + +Simply does `SetAddHistogramSampleFunction` + + +### NanIdleNotification(int idle_time_in_ms) + +Simply does `IdleNotification` + + +### NanLowMemoryNotification() + +Simply does `LowMemoryNotification` + + +### NanContextDisposedNotification() + +Simply does `ContextDisposedNotification` + + +### NanCallback + +Because of the difficulties imposed by the changes to `Persistent` handles in V8 in Node 0.11, creating `Persistent` versions of your `Handle` is annoyingly tricky. `NanCallback` makes it easier by taking your handle, making it persistent until the `NanCallback` is deleted and even providing a handy `Call()` method to fetch and execute the callback `Function`. + +```c++ +Local callbackHandle = args[0].As(); +NanCallback *callback = new NanCallback(callbackHandle); +// pass `callback` around and it's safe from GC until you: +delete callback; +``` + +You can execute the callback like so: + +```c++ +// no arguments: +callback->Call(0, NULL); + +// an error argument: +Handle argv[] = { + NanError(NanNew("fail!")) +}; +callback->Call(1, argv); + +// a success argument: +Handle argv[] = { + NanNull(), + NanNew("w00t!") +}; +callback->Call(2, argv); +``` + +`NanCallback` also has a `Local GetFunction()` method that you can use +to fetch a local handle to the underlying callback function, as well as a +`void SetFunction(Handle)` for setting the callback on the +`NanCallback`. You can check if a `NanCallback` is empty with the `bool IsEmpty()` method. Additionally a generic constructor is available for using +`NanCallback` without performing heap allocations. + + +### NanAsyncWorker + +`NanAsyncWorker` is an abstract class that you can subclass to have much of the annoying async queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the async work is in progress. + +See a rough outline of the implementation: + +```c++ +class NanAsyncWorker { +public: + NanAsyncWorker (NanCallback *callback); + + // Clean up persistent handles and delete the *callback + virtual ~NanAsyncWorker (); + + // Check the `ErrorMessage()` and call HandleOKCallback() + // or HandleErrorCallback depending on whether it has been set or not + virtual void WorkComplete (); + + // You must implement this to do some async work. If there is an + // error then use `SetErrorMessage()` to set an error message and the callback will + // be passed that string in an Error object + virtual void Execute (); + + // Save a V8 object in a Persistent handle to protect it from GC + void SaveToPersistent(const char *key, Local &obj); + + // Fetch a stored V8 object (don't call from within `Execute()`) + Local GetFromPersistent(const char *key); + + // Get the error message (or NULL) + const char *ErrorMessage(); + + // Set an error message + void SetErrorMessage(const char *msg); + +protected: + // Default implementation calls the callback function with no arguments. + // Override this to return meaningful data + virtual void HandleOKCallback (); + + // Default implementation calls the callback function with an Error object + // wrapping the `errmsg` string + virtual void HandleErrorCallback (); +}; +``` + + +### NanAsyncQueueWorker(NanAsyncWorker *) + +`NanAsyncQueueWorker` will run a `NanAsyncWorker` asynchronously via libuv. Both the *execute* and *after_work* steps are taken care of for you—most of the logic for this is embedded in `NanAsyncWorker`. + + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + +## Porting + +Follows is a guide to porting your C++ node to NAN. + + + + + + + + + + + + + + + + + +
AspectWithout NANWith NAN
Function declaration
class MyClass : public ObjectWrap {
+    ....
+    static Handle ToString(const Arguments& args);
+    ....
+}
class MyClass : public ObjectWrap {
+    ....
+    static NAN_METHOD(ToString);
+    ....
+}
Function definition
Handle
+MyClass::ToString(const Arguments& args)
+{
+	HandleScope scope;
+	....
+}
+NAN_METHOD(MyClass::ToString)
+{
+  NanScope();
+  ....
+}
Return a value
return scope.Close(result);
NanReturnValue(result);
Return undefined
return Undefined();
NanReturnUndefined();
Throw an error
return ThrowException(
+  Exception::Error(
+    String::New("Error text...")));
return NanThrowError("Error text...");
New v8 string literal
String::NewSymbol("my text")
NanNew("my text")
+ +## Contributors + + + +## Governance & Contributing + +NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +### Developer's Certificate of Origin 1.0 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or +* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or +* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. + + +### WG Members / Collaborators + + + + + + + + + +
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
David SiegelGitHub/agnat-
+ +## Licence & copyright + +Copyright (c) 2015 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/appveyor.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/appveyor.yml new file mode 100644 index 0000000..3429453 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/appveyor.yml @@ -0,0 +1,38 @@ +# http://www.appveyor.com/docs/appveyor-yml + +# Test against these versions of Io.js and Node.js. +environment: + matrix: + # node.js + - nodejs_version: "0.8" + - nodejs_version: "0.10" + - nodejs_version: "0.12" + # io.js + - nodejs_version: "1" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node 0.STABLE.latest + - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} + - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} + - IF NOT %nodejs_version% == 1 npm -g install npm + - IF NOT %nodejs_version% == 1 set PATH=%APPDATA%\npm;%PATH% + # Typical npm stuff. + - npm install + - IF %nodejs_version% == 0.8 node node_modules\node-gyp\bin\node-gyp.js rebuild --directory test + - IF NOT %nodejs_version% == 0.8 npm run rebuild-tests + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - IF NOT %nodejs_version% == 1 npm test + - IF %nodejs_version% == 1 iojs node_modules\tap\bin\tap.js --gc test\js\*-test.js + +# Don't actually build. +build: off + +# Set build version format here instead of in the admin panel. +version: "{build}" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/include_dirs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/include_dirs.js new file mode 100644 index 0000000..4f1dfb4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/include_dirs.js @@ -0,0 +1 @@ +console.log(require('path').relative('.', __dirname)); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan.h new file mode 100644 index 0000000..fb025a9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan.h @@ -0,0 +1,2322 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors: + * - Rod Vagg + * - Benjamin Byholm + * - Trevor Norris + * - Nathan Rajlich + * - Brett Lawson + * - Ben Noordhuis + * - David Siegel + * + * MIT License + * + * Version 1.8.4: current Node 12: 0.12.2, Node 10: 0.10.38, io.js: 1.8.1 + * + * See https://github.com/rvagg/nan for the latest update to this file + **********************************************************************************/ + +#ifndef NAN_H_ +#define NAN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# pragma warning( pop ) +#else +# include +#endif + +#if defined(__GNUC__) && !(defined(DEBUG) && DEBUG) +# define NAN_INLINE inline __attribute__((always_inline)) +#elif defined(_MSC_VER) && !(defined(DEBUG) && DEBUG) +# define NAN_INLINE __forceinline +#else +# define NAN_INLINE inline +#endif + +#if defined(__GNUC__) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __declspec(deprecated) +#else +# define NAN_DEPRECATED +#endif + +#define NODE_0_10_MODULE_VERSION 11 +#define NODE_0_12_MODULE_VERSION 12 +#define ATOM_0_21_MODULE_VERSION 41 +#define IOJS_1_0_MODULE_VERSION 42 +#define IOJS_1_1_MODULE_VERSION 43 + +#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) +typedef v8::InvocationCallback NanFunctionCallback; +typedef v8::Script NanUnboundScript; +typedef v8::Script NanBoundScript; +#else +typedef v8::FunctionCallback NanFunctionCallback; +typedef v8::UnboundScript NanUnboundScript; +typedef v8::Script NanBoundScript; +#endif + +#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) +typedef v8::String::ExternalAsciiStringResource + NanExternalOneByteStringResource; +#else +typedef v8::String::ExternalOneByteStringResource + NanExternalOneByteStringResource; +#endif + +#include "nan_new.h" // NOLINT(build/include) + +// uv helpers +#ifdef UV_VERSION_MAJOR +#ifndef UV_VERSION_PATCH +#define UV_VERSION_PATCH 0 +#endif +#define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ + (UV_VERSION_MINOR << 8) | \ + (UV_VERSION_PATCH)) +#else +#define NAUV_UVVERSION 0x000b00 +#endif + + +#if NAUV_UVVERSION < 0x000b17 +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async, int) +#else +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async) +#endif + +#if NAUV_UVVERSION >= 0x000b0b + +typedef uv_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t *key) { + return uv_key_create(key); +} + +inline void nauv_key_delete(nauv_key_t *key) { + uv_key_delete(key); +} + +inline void* nauv_key_get(nauv_key_t *key) { + return uv_key_get(key); +} + +inline void nauv_key_set(nauv_key_t *key, void *value) { + uv_key_set(key, value); +} + +#else + +/* Implement thread local storage for older versions of libuv. + * This is essentially a backport of libuv commit 5d2434bf + * written by Ben Noordhuis, adjusted for names and inline. + */ + +#ifndef WIN32 + +#include + +typedef pthread_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + return -pthread_key_create(key, NULL); +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (pthread_key_delete(*key)) + abort(); +} + +inline void* nauv_key_get(nauv_key_t* key) { + return pthread_getspecific(*key); +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (pthread_setspecific(*key, value)) + abort(); +} + +#else + +#include + +typedef struct { + DWORD tls_index; +} nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + key->tls_index = TlsAlloc(); + if (key->tls_index == TLS_OUT_OF_INDEXES) + return UV_ENOMEM; + return 0; +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (TlsFree(key->tls_index) == FALSE) + abort(); + key->tls_index = TLS_OUT_OF_INDEXES; +} + +inline void* nauv_key_get(nauv_key_t* key) { + void* value = TlsGetValue(key->tls_index); + if (value == NULL) + if (GetLastError() != ERROR_SUCCESS) + abort(); + return value; +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (TlsSetValue(key->tls_index, value) == FALSE) + abort(); +} + +#endif +#endif + +// some generic helpers + +template NAN_INLINE bool NanSetPointerSafe( + T *var + , T val +) { + if (var) { + *var = val; + return true; + } else { + return false; + } +} + +template NAN_INLINE T NanGetPointerSafe( + T *var + , T fallback = reinterpret_cast(0) +) { + if (var) { + return *var; + } else { + return fallback; + } +} + +NAN_INLINE bool NanBooleanOptionValue( + v8::Local optionsObj + , v8::Handle opt, bool def +) { + if (def) { + return optionsObj.IsEmpty() + || !optionsObj->Has(opt) + || optionsObj->Get(opt)->BooleanValue(); + } else { + return !optionsObj.IsEmpty() + && optionsObj->Has(opt) + && optionsObj->Get(opt)->BooleanValue(); + } +} + +NAN_INLINE bool NanBooleanOptionValue( + v8::Local optionsObj + , v8::Handle opt +) { + return NanBooleanOptionValue(optionsObj, opt, false); +} + +NAN_INLINE uint32_t NanUInt32OptionValue( + v8::Local optionsObj + , v8::Handle opt + , uint32_t def +) { + return !optionsObj.IsEmpty() + && optionsObj->Has(opt) + && optionsObj->Get(opt)->IsNumber() + ? optionsObj->Get(opt)->Uint32Value() + : def; +} + +template +v8::Local NanNew(v8::Handle); + +template +NAN_INLINE v8::Local _NanEnsureLocal(v8::Handle val) { + return NanNew(val); +} + +template +NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { + return val; +} + +template +NAN_INLINE v8::Local _NanEnsureLocal(T val) { + return NanNew(val); +} + +/* io.js 1.0 */ +#if NODE_MODULE_VERSION >= IOJS_1_0_MODULE_VERSION \ + || NODE_VERSION_AT_LEAST(0, 11, 15) + NAN_INLINE + void NanSetCounterFunction(v8::CounterLookupCallback cb) { + v8::Isolate::GetCurrent()->SetCounterFunction(cb); + } + + NAN_INLINE + void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); + } + + NAN_INLINE + void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); + } + + NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { + return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); + } + + NAN_INLINE void NanLowMemoryNotification() { + v8::Isolate::GetCurrent()->LowMemoryNotification(); + } + + NAN_INLINE void NanContextDisposedNotification() { + v8::Isolate::GetCurrent()->ContextDisposedNotification(); + } +#else + NAN_INLINE + void NanSetCounterFunction(v8::CounterLookupCallback cb) { + v8::V8::SetCounterFunction(cb); + } + + NAN_INLINE + void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::V8::SetCreateHistogramFunction(cb); + } + + NAN_INLINE + void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::V8::SetAddHistogramSampleFunction(cb); + } + + NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { + return v8::V8::IdleNotification(idle_time_in_ms); + } + + NAN_INLINE void NanLowMemoryNotification() { + v8::V8::LowMemoryNotification(); + } + + NAN_INLINE void NanContextDisposedNotification() { + v8::V8::ContextDisposedNotification(); + } +#endif + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) +// Node 0.11+ (0.11.12 and below won't compile with these) + +# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& +# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args +# define _NAN_METHOD_RETURN_TYPE void + +# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& +# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args +# define _NAN_GETTER_RETURN_TYPE void + +# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& +# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args +# define _NAN_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args +# define _NAN_PROPERTY_GETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args +# define _NAN_PROPERTY_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args +# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void + +# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_DELETER_ARGS \ + _NAN_PROPERTY_DELETER_ARGS_TYPE args +# define _NAN_PROPERTY_DELETER_RETURN_TYPE void + +# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args +# define _NAN_PROPERTY_QUERY_RETURN_TYPE void + +# define _NAN_INDEX_GETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args +# define _NAN_INDEX_GETTER_RETURN_TYPE void + +# define _NAN_INDEX_SETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args +# define _NAN_INDEX_SETTER_RETURN_TYPE void + +# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args +# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void + +# define _NAN_INDEX_DELETER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args +# define _NAN_INDEX_DELETER_RETURN_TYPE void + +# define _NAN_INDEX_QUERY_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args +# define _NAN_INDEX_QUERY_RETURN_TYPE void + +# define NanScope() v8::HandleScope scope(v8::Isolate::GetCurrent()) +# define NanEscapableScope() \ + v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()) + +# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val)) +# define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) +# define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) +# define NanReturnValue(value) return args.GetReturnValue().Set(_NanEnsureLocal(value)) +# define NanReturnUndefined() return +# define NanReturnHolder() NanReturnValue(args.Holder()) +# define NanReturnThis() NanReturnValue(args.This()) +# define NanReturnNull() return args.GetReturnValue().SetNull() +# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() + + NAN_INLINE v8::Local NanObjectWrapHandle(const node::ObjectWrap *obj) { + return const_cast(obj)->handle(); + } + + NAN_INLINE v8::Local NanUndefined() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanNull() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanTrue() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanFalse() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE int NanAdjustExternalMemory(int bc) { + return static_cast( + v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , const char *name + , v8::Handle value) { + templ->Set(v8::Isolate::GetCurrent(), name, value); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + NAN_INLINE v8::Local NanGetCurrentContext() { + return v8::Isolate::GetCurrent()->GetCurrentContext(); + } + + NAN_INLINE void* NanGetInternalFieldPointer( + v8::Handle object + , int index) { + return object->GetAlignedPointerFromInternalField(index); + } + + NAN_INLINE void NanSetInternalFieldPointer( + v8::Handle object + , int index + , void* value) { + object->SetAlignedPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) + + NAN_INLINE void NanAddGCEpilogueCallback( + v8::Isolate::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); + } + + NAN_INLINE void NanRemoveGCEpilogueCallback( + v8::Isolate::GCEpilogueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); + } + + NAN_INLINE void NanAddGCPrologueCallback( + v8::Isolate::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); + } + + NAN_INLINE void NanRemoveGCPrologueCallback( + v8::Isolate::GCPrologueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); + } + + NAN_INLINE void NanGetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( + const char* data, int length = -1) { + return NanNew(data, length); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , v8::Handle obj) { + handle.Reset(v8::Isolate::GetCurrent(), obj); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , const v8::Persistent& obj) { + handle.Reset(v8::Isolate::GetCurrent(), obj); + } + + template + class _NanWeakCallbackData; + + template + struct _NanWeakCallbackInfo { + typedef void (*Callback)(const _NanWeakCallbackData& data); + NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) + : parameter(param), callback(cb) { + NanAssignPersistent(persistent, handle); + } + + NAN_INLINE ~_NanWeakCallbackInfo() { + persistent.Reset(); + } + + P* const parameter; + Callback const callback; + v8::Persistent persistent; + }; + + template + class _NanWeakCallbackData { + public: + NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) + : info_(info) { } + + NAN_INLINE v8::Local GetValue() const { + return NanNew(info_->persistent); + } + + NAN_INLINE P* GetParameter() const { return info_->parameter; } + + NAN_INLINE bool IsNearDeath() const { + return info_->persistent.IsNearDeath(); + } + + NAN_INLINE void Revive() const; + + NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { + return info_; + } + + NAN_DEPRECATED NAN_INLINE void Dispose() const { + } + + private: + _NanWeakCallbackInfo* info_; + }; + + template + static void _NanWeakCallbackDispatcher( + const v8::WeakCallbackData > &data) { + _NanWeakCallbackInfo *info = data.GetParameter(); + _NanWeakCallbackData wcbd(info); + info->callback(wcbd); + if (wcbd.IsNearDeath()) { + delete wcbd.GetCallbackInfo(); + } + } + + template + NAN_INLINE void _NanWeakCallbackData::Revive() const { + info_->persistent.SetWeak(info_, &_NanWeakCallbackDispatcher); + } + +template +NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( + v8::Handle handle + , P* parameter + , typename _NanWeakCallbackInfo::Callback callback) { + _NanWeakCallbackInfo *cbinfo = + new _NanWeakCallbackInfo(handle, parameter, callback); + cbinfo->persistent.SetWeak(cbinfo, &_NanWeakCallbackDispatcher); + return cbinfo; +} + +# define NAN_WEAK_CALLBACK(name) \ + template \ + static void name(const _NanWeakCallbackData &data) + +# define _NAN_ERROR(fun, errmsg) fun(NanNew(errmsg)) + +# define _NAN_THROW_ERROR(fun, errmsg) \ + do { \ + NanScope(); \ + v8::Isolate::GetCurrent()->ThrowException(_NAN_ERROR(fun, errmsg)); \ + } while (0); + + NAN_INLINE v8::Local NanError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE void NanThrowError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE void NanThrowError(v8::Handle error) { + NanScope(); + v8::Isolate::GetCurrent()->ThrowException(error); + } + + NAN_INLINE v8::Local NanError( + const char *msg + , const int errorNumber + ) { + v8::Local err = v8::Exception::Error(NanNew(msg)); + v8::Local obj = err.As(); + obj->Set(NanNew("code"), NanNew(errorNumber)); + return err; + } + + NAN_INLINE void NanThrowError( + const char *msg + , const int errorNumber + ) { + NanThrowError(NanError(msg, errorNumber)); + } + + NAN_INLINE v8::Local NanTypeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE void NanThrowTypeError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanRangeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::RangeError, errmsg); + } + + NAN_INLINE void NanThrowRangeError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); + } + + template NAN_INLINE void NanDisposePersistent( + v8::Persistent &handle + ) { + handle.Reset(); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + char *data + , size_t length + , node::smalloc::FreeCallback callback + , void *hint + ) { + return node::Buffer::New( + v8::Isolate::GetCurrent(), data, length, callback, hint); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + const char *data + , uint32_t size + ) { + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); + } + + NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { + return node::Buffer::New(v8::Isolate::GetCurrent(), size); + } + + NAN_INLINE v8::Local NanBufferUse( + char* data + , uint32_t size + ) { + return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); + } + + NAN_INLINE bool NanHasInstance( + const v8::Persistent& function_template + , v8::Handle value + ) { + return NanNew(function_template)->HasInstance(value); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( + v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle() + ) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return v8::Local::New( + isolate + , v8::Context::New(isolate, extensions, tmpl, obj) + ); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + , const v8::ScriptOrigin& origin + ) { + v8::ScriptCompiler::Source source(s, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + ) { + v8::ScriptCompiler::Source source(s); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + NAN_INLINE v8::Local NanRunScript( + v8::Handle script + ) { + return script->BindToCurrentContext()->Run(); + } + + NAN_INLINE v8::Local NanRunScript( + v8::Handle script + ) { + return script->Run(); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle func + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv)); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle symbol + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv)); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , const char* method + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv)); + } + + template + NAN_INLINE void NanSetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(0, data); + } + + template + NAN_INLINE T *NanGetIsolateData( + v8::Isolate *isolate + ) { + return static_cast(isolate->GetData(0)); + } + + class NanAsciiString { + public: + NAN_INLINE explicit NanAsciiString(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new char[size + 1]; + size = toStr->WriteOneByte(reinterpret_cast(buf)); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanAsciiString() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanAsciiString(const NanAsciiString&); + void operator=(const NanAsciiString&); + + char *buf; + int size; + }; + + class NanUtf8String { + public: + NAN_INLINE explicit NanUtf8String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Utf8Length(); + buf = new char[size + 1]; + toStr->WriteUtf8(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanUtf8String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUtf8String(const NanUtf8String&); + void operator=(const NanUtf8String&); + + char *buf; + int size; + }; + + class NanUcs2String { + public: + NAN_INLINE explicit NanUcs2String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new uint16_t[size + 1]; + toStr->Write(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE uint16_t* operator*() { return buf; } + NAN_INLINE const uint16_t* operator*() const { return buf; } + + NAN_INLINE ~NanUcs2String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUcs2String(const NanUcs2String&); + void operator=(const NanUcs2String&); + + uint16_t *buf; + int size; + }; + +#else +// Node 0.8 and 0.10 + +# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& +# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args +# define _NAN_METHOD_RETURN_TYPE v8::Handle + +# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & +# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args +# define _NAN_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & +# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args +# define _NAN_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args +# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args +# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args +# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args +# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args +# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args +# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args +# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args +# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args +# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args +# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle + + NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( + const char* data, int length = -1) { + return v8::String::NewSymbol(data, length); + } + +# define NanScope() v8::HandleScope scope +# define NanEscapableScope() v8::HandleScope scope +# define NanEscapeScope(val) scope.Close(val) +# define NanLocker() v8::Locker locker +# define NanUnlocker() v8::Unlocker unlocker +# define NanReturnValue(value) return scope.Close(_NanEnsureLocal(value)) +# define NanReturnHolder() NanReturnValue(args.Holder()) +# define NanReturnThis() NanReturnValue(args.This()) +# define NanReturnUndefined() return v8::Undefined() +# define NanReturnNull() return v8::Null() +# define NanReturnEmptyString() return v8::String::Empty() + + NAN_INLINE v8::Local NanObjectWrapHandle(const node::ObjectWrap *obj) { + return v8::Local::New(obj->handle_); + } + + NAN_INLINE v8::Local NanUndefined() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Undefined())); + } + + NAN_INLINE v8::Local NanNull() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Null())); + } + + NAN_INLINE v8::Local NanTrue() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::True())); + } + + NAN_INLINE v8::Local NanFalse() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::False())); + } + + NAN_INLINE int NanAdjustExternalMemory(int bc) { + return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , const char *name + , v8::Handle value) { + templ->Set(name, value); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + NAN_INLINE v8::Local NanGetCurrentContext() { + return v8::Context::GetCurrent(); + } + + NAN_INLINE void* NanGetInternalFieldPointer( + v8::Handle object + , int index) { + return object->GetPointerFromInternalField(index); + } + + NAN_INLINE void NanSetInternalFieldPointer( + v8::Handle object + , int index + , void* value) { + object->SetPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::GCType type, v8::GCCallbackFlags flags) + + NAN_INLINE void NanAddGCEpilogueCallback( + v8::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); + } + NAN_INLINE void NanRemoveGCEpilogueCallback( + v8::GCEpilogueCallback callback) { + v8::V8::RemoveGCEpilogueCallback(callback); + } + NAN_INLINE void NanAddGCPrologueCallback( + v8::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCPrologueCallback(callback, gc_type_filter); + } + NAN_INLINE void NanRemoveGCPrologueCallback( + v8::GCPrologueCallback callback) { + v8::V8::RemoveGCPrologueCallback(callback); + } + NAN_INLINE void NanGetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::V8::GetHeapStatistics(heap_statistics); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , v8::Handle obj) { + handle.Dispose(); + handle = v8::Persistent::New(obj); + } + + template + class _NanWeakCallbackData; + + template + struct _NanWeakCallbackInfo { + typedef void (*Callback)(const _NanWeakCallbackData &data); + NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) + : parameter(param) + , callback(cb) + , persistent(v8::Persistent::New(handle)) { } + + NAN_INLINE ~_NanWeakCallbackInfo() { + persistent.Dispose(); + persistent.Clear(); + } + + P* const parameter; + Callback const callback; + v8::Persistent persistent; + }; + + template + class _NanWeakCallbackData { + public: + NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) + : info_(info) { } + + NAN_INLINE v8::Local GetValue() const { + return NanNew(info_->persistent); + } + + NAN_INLINE P* GetParameter() const { return info_->parameter; } + + NAN_INLINE bool IsNearDeath() const { + return info_->persistent.IsNearDeath(); + } + + NAN_INLINE void Revive() const; + + NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { + return info_; + } + + NAN_DEPRECATED NAN_INLINE void Dispose() const { + } + + private: + _NanWeakCallbackInfo* info_; + }; + + template + static void _NanWeakPersistentDispatcher( + v8::Persistent object, void *data) { + _NanWeakCallbackInfo* info = + static_cast<_NanWeakCallbackInfo*>(data); + _NanWeakCallbackData wcbd(info); + info->callback(wcbd); + if (wcbd.IsNearDeath()) { + delete wcbd.GetCallbackInfo(); + } + } + + template + NAN_INLINE void _NanWeakCallbackData::Revive() const { + info_->persistent.MakeWeak( + info_ + , &_NanWeakPersistentDispatcher); + } + + template + NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( + v8::Handle handle + , P* parameter + , typename _NanWeakCallbackInfo::Callback callback) { + _NanWeakCallbackInfo *cbinfo = + new _NanWeakCallbackInfo(handle, parameter, callback); + cbinfo->persistent.MakeWeak( + cbinfo + , &_NanWeakPersistentDispatcher); + return cbinfo; + } + +# define NAN_WEAK_CALLBACK(name) \ + template \ + static void name(const _NanWeakCallbackData &data) + +# define _NAN_ERROR(fun, errmsg) \ + fun(v8::String::New(errmsg)) + +# define _NAN_THROW_ERROR(fun, errmsg) \ + do { \ + NanScope(); \ + return v8::Local::New( \ + v8::ThrowException(_NAN_ERROR(fun, errmsg))); \ + } while (0); + + NAN_INLINE v8::Local NanError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE v8::Local NanThrowError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE v8::Local NanThrowError( + v8::Handle error + ) { + NanScope(); + return v8::Local::New(v8::ThrowException(error)); + } + + NAN_INLINE v8::Local NanError( + const char *msg + , const int errorNumber + ) { + v8::Local err = v8::Exception::Error(v8::String::New(msg)); + v8::Local obj = err.As(); + obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); + return err; + } + + NAN_INLINE v8::Local NanThrowError( + const char *msg + , const int errorNumber + ) { + return NanThrowError(NanError(msg, errorNumber)); + } + + NAN_INLINE v8::Local NanTypeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanThrowTypeError( + const char* errmsg + ) { + _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanRangeError( + const char* errmsg + ) { + return _NAN_ERROR(v8::Exception::RangeError, errmsg); + } + + NAN_INLINE v8::Local NanThrowRangeError( + const char* errmsg + ) { + _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); + } + + template + NAN_INLINE void NanDisposePersistent( + v8::Persistent &handle) { // NOLINT(runtime/references) + handle.Dispose(); + handle.Clear(); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + char *data + , size_t length + , node::Buffer::free_callback callback + , void *hint + ) { + return NanNew( + node::Buffer::New(data, length, callback, hint)->handle_); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + const char *data + , uint32_t size + ) { +#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION + return NanNew(node::Buffer::New(data, size)->handle_); +#else + return NanNew( + node::Buffer::New(const_cast(data), size)->handle_); +#endif + } + + NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { + return NanNew(node::Buffer::New(size)->handle_); + } + + NAN_INLINE void FreeData(char *data, void *hint) { + delete[] data; + } + + NAN_INLINE v8::Local NanBufferUse( + char* data + , uint32_t size + ) { + return NanNew( + node::Buffer::New(data, size, FreeData, NULL)->handle_); + } + + NAN_INLINE bool NanHasInstance( + const v8::Persistent& function_template + , v8::Handle value + ) { + return function_template->HasInstance(value); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( + v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle() + ) { + v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local lctx = NanNew(ctx); + ctx.Dispose(); + return lctx; + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + , const v8::ScriptOrigin& origin + ) { + return v8::Script::Compile(s, const_cast(&origin)); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + ) { + return v8::Script::Compile(s); + } + + NAN_INLINE v8::Local NanRunScript(v8::Handle script) { + return script->Run(); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle func + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, func, argc, argv)); +# else + v8::TryCatch try_catch; + v8::Local result = func->Call(target, argc, argv); + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + return result; +# endif + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle symbol + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, symbol, argc, argv)); +# else + v8::Local callback = target->Get(symbol).As(); + return NanMakeCallback(target, callback, argc, argv); +# endif + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , const char* method + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, method, argc, argv)); +# else + return NanMakeCallback(target, NanNew(method), argc, argv); +# endif + } + + template + NAN_INLINE void NanSetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(data); + } + + template + NAN_INLINE T *NanGetIsolateData( + v8::Isolate *isolate + ) { + return static_cast(isolate->GetData()); + } + + class NanAsciiString { + public: + NAN_INLINE explicit NanAsciiString(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new char[size + 1]; + size = toStr->WriteAscii(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanAsciiString() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanAsciiString(const NanAsciiString&); + void operator=(const NanAsciiString&); + + char *buf; + int size; + }; + + class NanUtf8String { + public: + NAN_INLINE explicit NanUtf8String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Utf8Length(); + buf = new char[size + 1]; + toStr->WriteUtf8(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanUtf8String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUtf8String(const NanUtf8String&); + void operator=(const NanUtf8String&); + + char *buf; + int size; + }; + + class NanUcs2String { + public: + NAN_INLINE explicit NanUcs2String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new uint16_t[size + 1]; + toStr->Write(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE uint16_t* operator*() { return buf; } + NAN_INLINE const uint16_t* operator*() const { return buf; } + + NAN_INLINE ~NanUcs2String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUcs2String(const NanUcs2String&); + void operator=(const NanUcs2String&); + + uint16_t *buf; + int size; + }; + +#endif // NODE_MODULE_VERSION + +typedef void (*NanFreeCallback)(char *data, void *hint); + +#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) +#define NAN_GETTER(name) \ + _NAN_GETTER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_GETTER_ARGS) +#define NAN_SETTER(name) \ + _NAN_SETTER_RETURN_TYPE name( \ + v8::Local property \ + , v8::Local value \ + , _NAN_SETTER_ARGS) +#define NAN_PROPERTY_GETTER(name) \ + _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_GETTER_ARGS) +#define NAN_PROPERTY_SETTER(name) \ + _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ + v8::Local property \ + , v8::Local value \ + , _NAN_PROPERTY_SETTER_ARGS) +#define NAN_PROPERTY_ENUMERATOR(name) \ + _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) +#define NAN_PROPERTY_DELETER(name) \ + _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_DELETER_ARGS) +#define NAN_PROPERTY_QUERY(name) \ + _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_QUERY_ARGS) +# define NAN_INDEX_GETTER(name) \ + _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) +#define NAN_INDEX_SETTER(name) \ + _NAN_INDEX_SETTER_RETURN_TYPE name( \ + uint32_t index \ + , v8::Local value \ + , _NAN_INDEX_SETTER_ARGS) +#define NAN_INDEX_ENUMERATOR(name) \ + _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) +#define NAN_INDEX_DELETER(name) \ + _NAN_INDEX_DELETER_RETURN_TYPE name( \ + uint32_t index \ + , _NAN_INDEX_DELETER_ARGS) +#define NAN_INDEX_QUERY(name) \ + _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) + +class NanCallback { + public: + NanCallback() { + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(handle, obj); + } + + explicit NanCallback(const v8::Handle &fn) { + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(handle, obj); + SetFunction(fn); + } + + ~NanCallback() { + if (handle.IsEmpty()) return; + NanDisposePersistent(handle); + } + + bool operator==(const NanCallback &other) const { + NanScope(); + v8::Local a = NanNew(handle)->Get(kCallbackIndex); + v8::Local b = NanNew(other.handle)->Get(kCallbackIndex); + return a->StrictEquals(b); + } + + bool operator!=(const NanCallback &other) const { + return !this->operator==(other); + } + + NAN_INLINE void SetFunction(const v8::Handle &fn) { + NanScope(); + NanNew(handle)->Set(kCallbackIndex, fn); + } + + NAN_INLINE v8::Local GetFunction() const { + NanEscapableScope(); + return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex) + .As()); + } + + NAN_INLINE bool IsEmpty() const { + NanScope(); + return NanNew(handle)->Get(kCallbackIndex)->IsUndefined(); + } + + NAN_INLINE v8::Handle + Call(v8::Handle target + , int argc + , v8::Handle argv[]) const { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, target, argc, argv); +#else + return Call_(target, argc, argv); +#endif + } + + NAN_INLINE v8::Handle + Call(int argc, v8::Handle argv[]) const { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv); +#else + return Call_(v8::Context::GetCurrent()->Global(), argc, argv); +#endif + } + + private: + v8::Persistent handle; + static const uint32_t kCallbackIndex = 0; + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Handle Call_(v8::Isolate *isolate + , v8::Handle target + , int argc + , v8::Handle argv[]) const { +#else + v8::Handle Call_(v8::Handle target + , int argc + , v8::Handle argv[]) const { +#endif + NanEscapableScope(); +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Local callback = NanNew(handle)-> + Get(kCallbackIndex).As(); + return NanEscapeScope(node::MakeCallback( + isolate + , target + , callback + , argc + , argv + )); +#else +#if NODE_VERSION_AT_LEAST(0, 8, 0) + v8::Local callback = handle-> + Get(kCallbackIndex).As(); + return NanEscapeScope(node::MakeCallback( + target + , callback + , argc + , argv + )); +#else + v8::Local callback = handle-> + Get(kCallbackIndex).As(); + return NanEscapeScope(NanMakeCallback( + target, callback, argc, argv)); +#endif +#endif + } +}; + +/* abstract */ class NanAsyncWorker { + public: + explicit NanAsyncWorker(NanCallback *callback_) + : callback(callback_), errmsg_(NULL) { + request.data = this; + + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(persistentHandle, obj); + } + + virtual ~NanAsyncWorker() { + NanScope(); + + if (!persistentHandle.IsEmpty()) + NanDisposePersistent(persistentHandle); + if (callback) + delete callback; + if (errmsg_) + delete[] errmsg_; + } + + virtual void WorkComplete() { + NanScope(); + + if (errmsg_ == NULL) + HandleOKCallback(); + else + HandleErrorCallback(); + delete callback; + callback = NULL; + } + + NAN_INLINE void SaveToPersistent( + const char *key, const v8::Local &obj) { + v8::Local handle = NanNew(persistentHandle); + handle->Set(NanNew(key), obj); + } + + v8::Local GetFromPersistent(const char *key) const { + NanEscapableScope(); + v8::Local handle = NanNew(persistentHandle); + return NanEscapeScope(handle->Get(NanNew(key)).As()); + } + + virtual void Execute() = 0; + + uv_work_t request; + + virtual void Destroy() { + delete this; + } + + protected: + v8::Persistent persistentHandle; + NanCallback *callback; + + virtual void HandleOKCallback() { + callback->Call(0, NULL); + } + + virtual void HandleErrorCallback() { + NanScope(); + + v8::Local argv[] = { + v8::Exception::Error(NanNew(ErrorMessage())) + }; + callback->Call(1, argv); + } + + void SetErrorMessage(const char *msg) { + if (errmsg_) { + delete[] errmsg_; + } + + size_t size = strlen(msg) + 1; + errmsg_ = new char[size]; + memcpy(errmsg_, msg, size); + } + + const char* ErrorMessage() const { + return errmsg_; + } + + private: + char *errmsg_; +}; + +/* abstract */ class NanAsyncProgressWorker : public NanAsyncWorker { + public: + explicit NanAsyncProgressWorker(NanCallback *callback_) + : NanAsyncWorker(callback_), asyncdata_(NULL), asyncsize_(0) { + async = new uv_async_t; + uv_async_init( + uv_default_loop() + , async + , AsyncProgress_ + ); + async->data = this; + + uv_mutex_init(&async_lock); + } + + virtual ~NanAsyncProgressWorker() { + uv_mutex_destroy(&async_lock); + + if (asyncdata_) { + delete[] asyncdata_; + } + } + + void WorkProgress() { + uv_mutex_lock(&async_lock); + char *data = asyncdata_; + size_t size = asyncsize_; + asyncdata_ = NULL; + uv_mutex_unlock(&async_lock); + + // Dont send progress events after we've already completed. + if (callback) { + HandleProgressCallback(data, size); + } + delete[] data; + } + + class ExecutionProgress { + friend class NanAsyncProgressWorker; + public: + // You could do fancy generics with templates here. + void Send(const char* data, size_t size) const { + that_->SendProgress_(data, size); + } + + private: + explicit ExecutionProgress(NanAsyncProgressWorker* that) : that_(that) {} + // Prohibit copying and assignment. + ExecutionProgress(const ExecutionProgress&); + void operator=(const ExecutionProgress&); + #if __cplusplus >= 201103L + // Prohibit C++11 move semantics. + ExecutionProgress(ExecutionProgress&&) = delete; + void operator=(ExecutionProgress&&) = delete; + #endif + NanAsyncProgressWorker* const that_; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void HandleProgressCallback(const char *data, size_t size) = 0; + + virtual void Destroy() { + uv_close(reinterpret_cast(async), AsyncClose_); + } + + private: + void Execute() /*final override*/ { + ExecutionProgress progress(this); + Execute(progress); + } + + void SendProgress_(const char *data, size_t size) { + char *new_data = new char[size]; + memcpy(new_data, data, size); + + uv_mutex_lock(&async_lock); + char *old_data = asyncdata_; + asyncdata_ = new_data; + asyncsize_ = size; + uv_mutex_unlock(&async_lock); + + if (old_data) { + delete[] old_data; + } + uv_async_send(async); + } + + NAN_INLINE static NAUV_WORK_CB(AsyncProgress_) { + NanAsyncProgressWorker *worker = + static_cast(async->data); + worker->WorkProgress(); + } + + NAN_INLINE static void AsyncClose_(uv_handle_t* handle) { + NanAsyncProgressWorker *worker = + static_cast(handle->data); + delete reinterpret_cast(handle); + delete worker; + } + + uv_async_t *async; + uv_mutex_t async_lock; + char *asyncdata_; + size_t asyncsize_; +}; + +NAN_INLINE void NanAsyncExecute (uv_work_t* req) { + NanAsyncWorker *worker = static_cast(req->data); + worker->Execute(); +} + +NAN_INLINE void NanAsyncExecuteComplete (uv_work_t* req) { + NanAsyncWorker* worker = static_cast(req->data); + worker->WorkComplete(); + worker->Destroy(); +} + +NAN_INLINE void NanAsyncQueueWorker (NanAsyncWorker* worker) { + uv_queue_work( + uv_default_loop() + , &worker->request + , NanAsyncExecute + , (uv_after_work_cb)NanAsyncExecuteComplete + ); +} + +//// Base 64 //// + +#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + +// Doesn't check for padding at the end. Can be 1-2 bytes over. +NAN_INLINE size_t _nan_base64_decoded_size_fast(size_t size) { + size_t remainder = size % 4; + + size = (size / 4) * 3; + if (remainder) { + if (size == 0 && remainder == 1) { + // special case: 1-byte input cannot be decoded + size = 0; + } else { + // non-padded input, add 1 or 2 extra bytes + size += 1 + (remainder == 3); + } + } + + return size; +} + +template +NAN_INLINE size_t _nan_base64_decoded_size( + const T* src + , size_t size +) { + if (size == 0) + return 0; + + if (src[size - 1] == '=') + size--; + if (size > 0 && src[size - 1] == '=') + size--; + + return _nan_base64_decoded_size_fast(size); +} + +// supports regular and URL-safe base64 +static const int _nan_unbase64_table[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 + , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 + , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 + , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 + , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 + , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 +}; + +#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] + +template static size_t _nan_base64_decode( + char* buf + , size_t len + , const T* src + , const size_t srcLen +) { + char* dst = buf; + char* dstEnd = buf + len; + const T* srcEnd = src + srcLen; + + while (src < srcEnd && dst < dstEnd) { + ptrdiff_t remaining = srcEnd - src; + char a, b, c, d; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining == 0 || *src == '=') break; + a = _nan_unbase64(*src++); + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 1 || *src == '=') break; + b = _nan_unbase64(*src++); + + *dst++ = (a << 2) | ((b & 0x30) >> 4); + if (dst == dstEnd) break; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 2 || *src == '=') break; + c = _nan_unbase64(*src++); + + *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); + if (dst == dstEnd) break; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 3 || *src == '=') break; + d = _nan_unbase64(*src++); + + *dst++ = ((c & 0x03) << 6) | (d & 0x3F); + } + + return dst - buf; +} + +//// HEX //// + +template unsigned _nan_hex2bin(T c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); + if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); + return static_cast(-1); +} + +template static size_t _nan_hex_decode( + char* buf + , size_t len + , const T* src + , const size_t srcLen +) { + size_t i; + for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { + unsigned a = _nan_hex2bin(src[i * 2 + 0]); + unsigned b = _nan_hex2bin(src[i * 2 + 1]); + if (!~a || !~b) return i; + buf[i] = a * 16 + b; + } + + return i; +} + +namespace NanIntern { + +inline +NanExternalOneByteStringResource const* +GetExternalResource(v8::Local str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->GetExternalAsciiStringResource(); +#else + return str->GetExternalOneByteStringResource(); +#endif +} + +inline +bool +IsExternal(v8::Local str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->IsExternalAscii(); +#else + return str->IsExternalOneByte(); +#endif +} + +} // end of namespace NanIntern + +static bool _NanGetExternalParts( + v8::Handle val + , const char** data + , size_t* len +) { + if (node::Buffer::HasInstance(val)) { + *data = node::Buffer::Data(val.As()); + *len = node::Buffer::Length(val.As()); + return true; + } + + assert(val->IsString()); + v8::Local str = NanNew(val.As()); + + if (NanIntern::IsExternal(str)) { + const NanExternalOneByteStringResource* ext; + ext = NanIntern::GetExternalResource(str); + *data = ext->data(); + *len = ext->length(); + return true; + } + + if (str->IsExternal()) { + const v8::String::ExternalStringResource* ext; + ext = str->GetExternalStringResource(); + *data = reinterpret_cast(ext->data()); + *len = ext->length(); + return true; + } + + return false; +} + +namespace Nan { + enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; +} + +#if !NODE_VERSION_AT_LEAST(0, 10, 0) +# include "nan_string_bytes.h" // NOLINT(build/include) +#endif + +NAN_INLINE v8::Local NanEncode( + const void *buf, size_t len, enum Nan::Encoding encoding = Nan::BINARY) { +#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + node::encoding node_enc = static_cast(encoding); + + if (encoding == Nan::UCS2) { + return node::Encode( + isolate + , reinterpret_cast(buf) + , len / 2); + } else { + return node::Encode( + isolate + , reinterpret_cast(buf) + , len + , node_enc); + } +#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::Encode( + v8::Isolate::GetCurrent() + , buf, len + , static_cast(encoding)); +#else +# if NODE_VERSION_AT_LEAST(0, 10, 0) + return node::Encode(buf, len, static_cast(encoding)); +# else + return NanIntern::Encode(reinterpret_cast(buf), len, encoding); +# endif +#endif +} + +NAN_INLINE ssize_t NanDecodeBytes( + v8::Handle val, enum Nan::Encoding encoding = Nan::BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeBytes( + v8::Isolate::GetCurrent() + , val + , static_cast(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == Nan::BUFFER) { + return node::DecodeBytes(val, node::BINARY); + } +# endif + return node::DecodeBytes(val, static_cast(encoding)); +#endif +} + +NAN_INLINE ssize_t NanDecodeWrite( + char *buf + , size_t len + , v8::Handle val + , enum Nan::Encoding encoding = Nan::BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeWrite( + v8::Isolate::GetCurrent() + , buf + , len + , val + , static_cast(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == Nan::BUFFER) { + return node::DecodeWrite(buf, len, val, node::BINARY); + } +# endif + return node::DecodeWrite( + buf + , len + , val + , static_cast(encoding)); +#endif +} + +/* NAN_DEPRECATED */ NAN_INLINE void* _NanRawString( + v8::Handle from + , enum Nan::Encoding encoding + , size_t *datalen + , void *buf + , size_t buflen + , int flags +) { + NanScope(); + + size_t sz_; + size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); + char *data = NULL; + size_t len; + bool is_extern = _NanGetExternalParts( + from + , const_cast(&data) + , &len); + + if (is_extern && !term_len) { + NanSetPointerSafe(datalen, len); + return data; + } + + v8::Local toStr = from->ToString(); + + char *to = static_cast(buf); + + switch (encoding) { + case Nan::ASCII: +#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , toStr->WriteAscii(to, 0, static_cast(sz_ + term_len), flags)); + return to; +#endif + case Nan::BINARY: + case Nan::BUFFER: + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } +#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION + { + uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; + + size_t somelen = toStr->Write(twobytebuf, 0, + static_cast(sz_ + term_len), flags); + + for (size_t i = 0; i < sz_ + term_len && i < somelen + term_len; i++) { + unsigned char *b = reinterpret_cast(&twobytebuf[i]); + to[i] = *b; + } + + NanSetPointerSafe(datalen, somelen); + + delete[] twobytebuf; + return to; + } +#else + NanSetPointerSafe( + datalen, + toStr->WriteOneByte( + reinterpret_cast(to) + , 0 + , static_cast(sz_ + term_len) + , flags)); + return to; +#endif + case Nan::UTF8: + sz_ = toStr->Utf8Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , toStr->WriteUtf8(to, static_cast(sz_ + term_len) + , NULL, flags) + - term_len); + return to; + case Nan::BASE64: + { + v8::String::Value value(toStr); + sz_ = _nan_base64_decoded_size(*value, value.length()); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len); + } + NanSetPointerSafe( + datalen + , _nan_base64_decode(to, sz_, *value, value.length())); + if (term_len) { + to[sz_] = '\0'; + } + return to; + } + case Nan::UCS2: + { + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[(sz_ + term_len) * 2]; + } else { + assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); + } + + int bc = 2 * toStr->Write( + reinterpret_cast(to) + , 0 + , static_cast(sz_ + term_len) + , flags); + NanSetPointerSafe(datalen, bc); + return to; + } + case Nan::HEX: + { + v8::String::Value value(toStr); + sz_ = value.length(); + assert(!(sz_ & 1) && "bad hex data"); + if (to == NULL) { + to = new char[sz_ / 2 + term_len]; + } else { + assert(buflen >= sz_ / 2 + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , _nan_hex_decode(to, sz_ / 2, *value, value.length())); + } + if (term_len) { + to[sz_ / 2] = '\0'; + } + return to; + default: + assert(0 && "unknown encoding"); + } + return to; +} + +NAN_DEPRECATED NAN_INLINE void* NanRawString( + v8::Handle from + , enum Nan::Encoding encoding + , size_t *datalen + , void *buf + , size_t buflen + , int flags +) { + return _NanRawString(from, encoding, datalen, buf, buflen, flags); +} + + +NAN_DEPRECATED NAN_INLINE char* NanCString( + v8::Handle from + , size_t *datalen + , char *buf = NULL + , size_t buflen = 0 + , int flags = v8::String::NO_OPTIONS +) { + return static_cast( + _NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags) + ); +} + +NAN_INLINE void NanSetPrototypeTemplate( + v8::Local templ + , const char *name + , v8::Handle value +) { + NanSetTemplate(templ->PrototypeTemplate(), name, value); +} + +NAN_INLINE void NanSetPrototypeTemplate( + v8::Local templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes +) { + NanSetTemplate(templ->PrototypeTemplate(), name, value, attributes); +} + +NAN_INLINE void NanSetInstanceTemplate( + v8::Local templ + , const char *name + , v8::Handle value +) { + NanSetTemplate(templ->InstanceTemplate(), name, value); +} + +NAN_INLINE void NanSetInstanceTemplate( + v8::Local templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes +) { + NanSetTemplate(templ->InstanceTemplate(), name, value, attributes); +} + +//=== Export ================================================================== + +inline +void +NanExport(v8::Handle target, const char * name, + NanFunctionCallback f) { + target->Set(NanNew(name), + NanNew(f)->GetFunction()); +} + +//=== Tap Reverse Binding ===================================================== + +struct NanTap { + explicit NanTap(v8::Handle t) : t_() { + NanAssignPersistent(t_, t->ToObject()); + } + + ~NanTap() { NanDisposePersistent(t_); } // not sure if neccessary + + inline void plan(int i) { + v8::Handle arg = NanNew(i); + NanMakeCallback(NanNew(t_), "plan", 1, &arg); + } + + inline void ok(bool isOk, const char * msg = NULL) { + v8::Handle args[2]; + args[0] = NanNew(isOk); + if (msg) args[1] = NanNew(msg); + NanMakeCallback(NanNew(t_), "ok", msg ? 2 : 1, args); + } + + private: + v8::Persistent t_; +}; + +#define NAN_STRINGIZE2(x) #x +#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) +#define NAN_TEST_EXPRESSION(expression) \ + ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression + +#define return_NanValue(v) NanReturnValue(v) +#define return_NanUndefined() NanReturnUndefined() +#define NAN_EXPORT(target, function) NanExport(target, #function, function) + +#endif // NAN_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_12_inl.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_12_inl.h new file mode 100644 index 0000000..fc0e0ac --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_12_inl.h @@ -0,0 +1,261 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors + * + * MIT License + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_12_INL_H_ +#define NAN_IMPLEMENTATION_12_INL_H_ +//============================================================================== +// node v0.11 implementation +//============================================================================== + +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# pragma warning( pop ) +#else +# include +#endif + +namespace NanIntern { + +//=== Array ==================================================================== + +Factory::return_t +Factory::New() { + return v8::Array::New(v8::Isolate::GetCurrent()); +} + +Factory::return_t +Factory::New(int length) { + return v8::Array::New(v8::Isolate::GetCurrent(), length); +} + +//=== Boolean ================================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::Boolean::New(v8::Isolate::GetCurrent(), value); +} + +//=== Boolean Object =========================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::BooleanObject::New(value).As(); +} + +//=== Context ================================================================== + +Factory::return_t +Factory::New( v8::ExtensionConfiguration* extensions + , v8::Handle tmpl + , v8::Handle obj) { + return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); +} + +//=== Date ===================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); +} + +//=== External ================================================================= + +Factory::return_t +Factory::New(void * value) { + return v8::External::New(v8::Isolate::GetCurrent(), value); +} + +//=== Function ================================================================= + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data) { + return v8::Function::New( v8::Isolate::GetCurrent() + , callback + , data); +} + +//=== Function Template ======================================================== + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data + , v8::Handle signature) { + return v8::FunctionTemplate::New( v8::Isolate::GetCurrent() + , callback + , data + , signature); +} + +//=== Number =================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Number::New(v8::Isolate::GetCurrent(), value); +} + +//=== Number Object ============================================================ + +Factory::return_t +Factory::New(double value) { + return v8::NumberObject::New( v8::Isolate::GetCurrent() + , value).As(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template +typename IntegerFactory::return_t +IntegerFactory::New(int32_t value) { + return To(T::New(v8::Isolate::GetCurrent(), value)); +} + +template +typename IntegerFactory::return_t +IntegerFactory::New(uint32_t value) { + return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory::return_t +Factory::New(int32_t value) { + return To( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory::return_t +Factory::New(uint32_t value) { + return To( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +//=== Object =================================================================== + +Factory::return_t +Factory::New() { + return v8::Object::New(v8::Isolate::GetCurrent()); +} + +//=== Object Template ========================================================== + +Factory::return_t +Factory::New() { + return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); +} + +//=== RegExp =================================================================== + +Factory::return_t +Factory::New( + v8::Handle pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} + +//=== Script =================================================================== + +Factory::return_t +Factory::New( v8::Local source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} + +Factory::return_t +Factory::New( v8::Local source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} + +//=== Signature ================================================================ + +Factory::return_t +Factory::New(Factory::FTH receiver) { + return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); +} + +//=== String =================================================================== + +Factory::return_t +Factory::New() { + return v8::String::Empty(v8::Isolate::GetCurrent()); +} + +Factory::return_t +Factory::New(const char * value, int length) { + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory::return_t +Factory::New(std::string const& value) { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), + value.data(), v8::String::kNormalString, static_cast(value.size())); +} + +Factory::return_t +Factory::New(const uint8_t * value, int length) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory::return_t +Factory::New(const uint16_t * value, int length) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory::return_t +Factory::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} + +Factory::return_t +Factory::New(NanExternalOneByteStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} + +//=== String Object ============================================================ + +Factory::return_t +Factory::New(v8::Handle value) { + return v8::StringObject::New(value).As(); +} + +//=== Unbound Script =========================================================== + +Factory::return_t +Factory::New(v8::Local source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} + +Factory::return_t +Factory::New( v8::Local source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} + +} // end of namespace NanIntern + +//=== Presistents and Handles ================================================== + +template +inline v8::Local NanNew(v8::Handle h) { + return v8::Local::New(v8::Isolate::GetCurrent(), h); +} + +template +inline v8::Local NanNew(v8::Persistent const& p) { + return v8::Local::New(v8::Isolate::GetCurrent(), p); +} + +#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_pre_12_inl.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_pre_12_inl.h new file mode 100644 index 0000000..e995a14 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_implementation_pre_12_inl.h @@ -0,0 +1,267 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors + * + * MIT License + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ +#define NAN_IMPLEMENTATION_PRE_12_INL_H_ + +#include + +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# include +# pragma warning( pop ) +#else +# include +# include +#endif + +//============================================================================== +// node v0.10 implementation +//============================================================================== + +namespace NanIntern { + +//=== Array ==================================================================== + +Factory::return_t +Factory::New() { + return v8::Array::New(); +} + +Factory::return_t +Factory::New(int length) { + return v8::Array::New(length); +} + +//=== Boolean ================================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::Boolean::New(value)->ToBoolean(); +} + +//=== Boolean Object =========================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::BooleanObject::New(value).As(); +} + +//=== Context ================================================================== + +Factory::return_t +Factory::New( v8::ExtensionConfiguration* extensions + , v8::Handle tmpl + , v8::Handle obj) { + v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local lctx = v8::Local::New(ctx); + ctx.Dispose(); + return lctx; +} + +//=== Date ===================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Date::New(value).As(); +} + +//=== External ================================================================= + +Factory::return_t +Factory::New(void * value) { + return v8::External::New(value); +} + +//=== Function ================================================================= + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data) { + return Factory::New( callback + , data + , v8::Handle() + )->GetFunction(); +} + + +//=== FunctionTemplate ========================================================= + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data + , v8::Handle signature) { + // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find + // a way. Have at it though... + return v8::FunctionTemplate::New( callback + , data + , signature); +} + +//=== Number =================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Number::New(value); +} + +//=== Number Object ============================================================ + +Factory::return_t +Factory::New(double value) { + return v8::NumberObject::New(value).As(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template +typename IntegerFactory::return_t +IntegerFactory::New(int32_t value) { + return To(T::New(value)); +} + +template +typename IntegerFactory::return_t +IntegerFactory::New(uint32_t value) { + return To(T::NewFromUnsigned(value)); +} + +Factory::return_t +Factory::New(int32_t value) { + return To(v8::Uint32::NewFromUnsigned(value)); +} + +Factory::return_t +Factory::New(uint32_t value) { + return To(v8::Uint32::NewFromUnsigned(value)); +} + + +//=== Object =================================================================== + +Factory::return_t +Factory::New() { + return v8::Object::New(); +} + +//=== Object Template ========================================================== + +Factory::return_t +Factory::New() { + return v8::ObjectTemplate::New(); +} + +//=== RegExp =================================================================== + +Factory::return_t +Factory::New( + v8::Handle pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} + +//=== Script =================================================================== + +Factory::return_t +Factory::New( v8::Local source) { + return v8::Script::New(source); +} +Factory::return_t +Factory::New( v8::Local source + , v8::ScriptOrigin const& origin) { + return v8::Script::New(source, const_cast(&origin)); +} + +//=== Signature ================================================================ + +Factory::return_t +Factory::New(Factory::FTH receiver) { + return v8::Signature::New(receiver); +} + +//=== String =================================================================== + +Factory::return_t +Factory::New() { + return v8::String::Empty(); +} + +Factory::return_t +Factory::New(const char * value, int length) { + return v8::String::New(value, length); +} + +Factory::return_t +Factory::New(std::string const& value) { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::New( value.data(), static_cast(value.size())); +} + +inline +void +widenString(std::vector *ws, const uint8_t *s, int l = -1) { + size_t len = static_cast(l); + if (l < 0) { + len = strlen(reinterpret_cast(s)); + } + assert(len <= INT_MAX && "string too long"); + ws->resize(len); + std::copy(s, s + len, ws->begin()); +} + +Factory::return_t +Factory::New(const uint16_t * value, int length) { + return v8::String::New(value, length); +} + +Factory::return_t +Factory::New(const uint8_t * value, int length) { + std::vector wideString; + widenString(&wideString, value, length); + if (wideString.size() == 0) { + return v8::String::Empty(); + } else { + return v8::String::New(&wideString.front() + , static_cast(wideString.size())); + } +} + +Factory::return_t +Factory::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(value); +} + +Factory::return_t +Factory::New(v8::String::ExternalAsciiStringResource * value) { + return v8::String::NewExternal(value); +} + +//=== String Object ============================================================ + +Factory::return_t +Factory::New(v8::Handle value) { + return v8::StringObject::New(value).As(); +} + +} // end of namespace NanIntern + +//=== Presistents and Handles ================================================== + +template +inline v8::Local NanNew(v8::Handle h) { + return v8::Local::New(h); +} + +template +inline v8::Local NanNew(v8::Persistent const& p) { + return v8::Local::New(p); +} + +#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_new.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_new.h new file mode 100644 index 0000000..c189092 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_new.h @@ -0,0 +1,328 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors + * + * MIT License + ********************************************************************/ + +#ifndef NAN_NEW_H_ +#define NAN_NEW_H_ + +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# pragma warning( pop ) +#else +# include +#endif + +namespace NanIntern { // scnr + +// TODO(agnat): Generalize +template v8::Local To(v8::Handle i); + +template <> +inline +v8::Local +To(v8::Handle i) { return i->ToInteger(); } + +template <> +inline +v8::Local +To(v8::Handle i) { return i->ToInt32(); } + +template <> +inline +v8::Local +To(v8::Handle i) { return i->ToUint32(); } + +template struct FactoryBase { typedef v8::Local return_t; }; + +template struct Factory; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); + static inline return_t New(int length); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(bool value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(bool value); +}; + +template <> +struct Factory : FactoryBase { + static inline + return_t + New( v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle()); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(double value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(void *value); +}; + +template <> +struct Factory : FactoryBase { + static inline + return_t + New( NanFunctionCallback callback + , v8::Handle data = v8::Handle()); +}; + +template <> +struct Factory : FactoryBase { + static inline + return_t + New( NanFunctionCallback callback = NULL + , v8::Handle data = v8::Handle() + , v8::Handle signature = v8::Handle()); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(double value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(double value); +}; + +template +struct IntegerFactory : FactoryBase { + typedef typename FactoryBase::return_t return_t; + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory : IntegerFactory {}; + +template <> +struct Factory : IntegerFactory {}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New( + v8::Handle pattern, v8::RegExp::Flags flags); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New( v8::Local source); + static inline return_t New( v8::Local source + , v8::ScriptOrigin const& origin); +}; + +template <> +struct Factory : FactoryBase { + typedef v8::Handle FTH; + static inline return_t New(FTH receiver = FTH()); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); + static inline return_t New(const char *value, int length = -1); + static inline return_t New(const uint16_t *value, int length = -1); + static inline return_t New(std::string const& value); + + static inline return_t New(v8::String::ExternalStringResource * value); + static inline return_t New(NanExternalOneByteStringResource * value); + + // TODO(agnat): Deprecate. + static inline return_t New(const uint8_t * value, int length = -1); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(v8::Handle value); +}; + +} // end of namespace NanIntern + +#if (NODE_MODULE_VERSION >= 12) + +namespace NanIntern { + +template <> +struct Factory : FactoryBase { + static inline return_t New( v8::Local source); + static inline return_t New( v8::Local source + , v8::ScriptOrigin const& origin); +}; + +} // end of namespace NanIntern + +# include "nan_implementation_12_inl.h" + +#else // NODE_MODULE_VERSION >= 12 + +# include "nan_implementation_pre_12_inl.h" + +#endif + +//=== API ====================================================================== + +template +typename NanIntern::Factory::return_t +NanNew() { + return NanIntern::Factory::New(); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0) { + return NanIntern::Factory::New(arg0); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0, A1 arg1) { + return NanIntern::Factory::New(arg0, arg1); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0, A1 arg1, A2 arg2) { + return NanIntern::Factory::New(arg0, arg1, arg2); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { + return NanIntern::Factory::New(arg0, arg1, arg2, arg3); +} + +// Note(agnat): When passing overloaded function pointers to template functions +// as generic arguments the compiler needs help in picking the right overload. +// These two functions handle NanNew and NanNew with +// all argument variations. + +// v8::Function and v8::FunctionTemplate with one or two arguments +template +typename NanIntern::Factory::return_t +NanNew( NanFunctionCallback callback + , v8::Handle data = v8::Handle()) { + return NanIntern::Factory::New(callback, data); +} + +// v8::Function and v8::FunctionTemplate with three arguments +template +typename NanIntern::Factory::return_t +NanNew( NanFunctionCallback callback + , v8::Handle data = v8::Handle() + , A2 a2 = A2()) { + return NanIntern::Factory::New(callback, data, a2); +} + +// Convenience + +template inline v8::Local NanNew(v8::Handle h); +template inline v8::Local NanNew(v8::Persistent const& p); + +inline +NanIntern::Factory::return_t +NanNew(bool value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(int32_t value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(uint32_t value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(double value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(std::string const& value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(const char * value, int length) { + return NanNew(value, length); +} + +inline +NanIntern::Factory::return_t +NanNew(const char * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(const uint8_t * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(const uint16_t * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(v8::String::ExternalStringResource * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(NanExternalOneByteStringResource * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(v8::Handle pattern, v8::RegExp::Flags flags) { + return NanNew(pattern, flags); +} + +#endif // NAN_NEW_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_string_bytes.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_string_bytes.h new file mode 100644 index 0000000..9deecfb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/nan_string_bytes.h @@ -0,0 +1,312 @@ +// 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. + +#ifndef NAN_STRING_BYTES_H_ +#define NAN_STRING_BYTES_H_ + +// Decodes a v8::Handle or Buffer to a raw char* + +#include +#include +#include +#include // memcpy +#include + +namespace NanIntern { + +using v8::Local; +using v8::Handle; +using v8::Object; +using v8::String; +using v8::Value; + + +//// Base 64 //// + +#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + + + +//// Nan::HEX //// + +static bool contains_non_ascii_slow(const char* buf, size_t len) { + for (size_t i = 0; i < len; ++i) { + if (buf[i] & 0x80) return true; + } + return false; +} + + +static bool contains_non_ascii(const char* src, size_t len) { + if (len < 16) { + return contains_non_ascii_slow(src, len); + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned unaligned = reinterpret_cast(src) & align_mask; + + if (unaligned > 0) { + const unsigned n = bytes_per_word - unaligned; + if (contains_non_ascii_slow(src, n)) return true; + src += n; + len -= n; + } + + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = 0x8080808080808080ll; +#else + const uintptr_t mask = 0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast(src); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + if (srcw[i] & mask) return true; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + if (contains_non_ascii_slow(src + offset, remainder)) return true; + } + + return false; +} + + +static void force_ascii_slow(const char* src, char* dst, size_t len) { + for (size_t i = 0; i < len; ++i) { + dst[i] = src[i] & 0x7f; + } +} + + +static void force_ascii(const char* src, char* dst, size_t len) { + if (len < 16) { + force_ascii_slow(src, dst, len); + return; + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned src_unalign = reinterpret_cast(src) & align_mask; + const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; + + if (src_unalign > 0) { + if (src_unalign == dst_unalign) { + const unsigned unalign = bytes_per_word - src_unalign; + force_ascii_slow(src, dst, unalign); + src += unalign; + dst += unalign; + len -= src_unalign; + } else { + force_ascii_slow(src, dst, len); + return; + } + } + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = ~0x8080808080808080ll; +#else + const uintptr_t mask = ~0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast(src); + uintptr_t* dstw = reinterpret_cast(dst); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + dstw[i] = srcw[i] & mask; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + force_ascii_slow(src + offset, dst + offset, remainder); + } +} + + +static size_t base64_encode(const char* src, + size_t slen, + char* dst, + size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= base64_encoded_size(slen) && + "not enough space provided for base64 encode"); + + dlen = base64_encoded_size(slen); + + unsigned a; + unsigned b; + unsigned c; + unsigned i; + unsigned k; + unsigned n; + + static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + i = 0; + k = 0; + n = slen / 3 * 3; + + while (i < n) { + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + c = src[i + 2] & 0xff; + + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; + dst[k + 3] = table[c & 0x3f]; + + i += 3; + k += 4; + } + + if (n != slen) { + switch (slen - n) { + case 1: + a = src[i + 0] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[(a & 3) << 4]; + dst[k + 2] = '='; + dst[k + 3] = '='; + break; + + case 2: + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[(b & 0x0f) << 2]; + dst[k + 3] = '='; + break; + } + } + + return dlen; +} + + +static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= slen * 2 && + "not enough space provided for hex encode"); + + dlen = slen * 2; + for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { + static const char hex[] = "0123456789abcdef"; + uint8_t val = static_cast(src[i]); + dst[k + 0] = hex[val >> 4]; + dst[k + 1] = hex[val & 15]; + } + + return dlen; +} + + + +static Local Encode(const char* buf, + size_t buflen, + enum Nan::Encoding encoding) { + assert(buflen <= node::Buffer::kMaxLength); + if (!buflen && encoding != Nan::BUFFER) + return NanNew(""); + + Local val; + switch (encoding) { + case Nan::BUFFER: + return NanNewBufferHandle(buf, buflen); + + case Nan::ASCII: + if (contains_non_ascii(buf, buflen)) { + char* out = new char[buflen]; + force_ascii(buf, out, buflen); + val = NanNew(out, buflen); + delete[] out; + } else { + val = NanNew(buf, buflen); + } + break; + + case Nan::UTF8: + val = NanNew(buf, buflen); + break; + + case Nan::BINARY: { + // TODO(isaacs) use ExternalTwoByteString? + const unsigned char *cbuf = reinterpret_cast(buf); + uint16_t * twobytebuf = new uint16_t[buflen]; + for (size_t i = 0; i < buflen; i++) { + // XXX is the following line platform independent? + twobytebuf[i] = cbuf[i]; + } + val = NanNew(twobytebuf, buflen); + delete[] twobytebuf; + break; + } + + case Nan::BASE64: { + size_t dlen = base64_encoded_size(buflen); + char* dst = new char[dlen]; + + size_t written = base64_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = NanNew(dst, dlen); + delete[] dst; + break; + } + + case Nan::UCS2: { + const uint16_t* data = reinterpret_cast(buf); + val = NanNew(data, buflen / 2); + break; + } + + case Nan::HEX: { + size_t dlen = buflen * 2; + char* dst = new char[dlen]; + size_t written = hex_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = NanNew(dst, dlen); + delete[] dst; + break; + } + + default: + assert(0 && "unknown encoding"); + break; + } + + return val; +} + +#undef base64_encoded_size + +} // namespace NanIntern + +#endif // NAN_STRING_BYTES_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/package.json new file mode 100644 index 0000000..b69238b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/nan/package.json @@ -0,0 +1,90 @@ +{ + "name": "nan", + "version": "1.8.4", + "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", + "main": "include_dirs.js", + "repository": { + "type": "git", + "url": "git://github.com/iojs/nan.git" + }, + "scripts": { + "test": "tap --gc test/js/*-test.js", + "rebuild-tests": "pangyp rebuild --directory test" + }, + "contributors": [ + { + "name": "Rod Vagg", + "email": "r@va.gg", + "url": "https://github.com/rvagg" + }, + { + "name": "Benjamin Byholm", + "email": "bbyholm@abo.fi", + "url": "https://github.com/kkoopa/" + }, + { + "name": "Trevor Norris", + "email": "trev.norris@gmail.com", + "url": "https://github.com/trevnorris" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "https://github.com/TooTallNate" + }, + { + "name": "Brett Lawson", + "email": "brett19@gmail.com", + "url": "https://github.com/brett19" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl", + "url": "https://github.com/bnoordhuis" + }, + { + "name": "David Siegel", + "email": "david@artcom.de", + "url": "https://github.com/agnat" + } + ], + "devDependencies": { + "bindings": "~1.2.1", + "node-gyp": "~1.0.2", + "pangyp": "~2.0.1", + "tap": "~0.7.1", + "xtend": "~4.0.0" + }, + "license": "MIT", + "gitHead": "ed3bbf4ced0cf7937b4e4164766797f71aa97f3d", + "bugs": { + "url": "https://github.com/iojs/nan/issues" + }, + "homepage": "https://github.com/iojs/nan#readme", + "_id": "nan@1.8.4", + "_shasum": "3c76b5382eab33e44b758d2813ca9d92e9342f34", + "_from": "nan@>=1.8.0 <1.9.0", + "_npmVersion": "2.8.3", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "kkoopa", + "email": "bbyholm@abo.fi" + }, + "maintainers": [ + { + "name": "rvagg", + "email": "rod@vagg.org" + }, + { + "name": "kkoopa", + "email": "bbyholm@abo.fi" + } + ], + "dist": { + "shasum": "3c76b5382eab33e44b758d2813ca9d92e9342f34", + "tarball": "http://registry.npmjs.org/nan/-/nan-1.8.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/nan/-/nan-1.8.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.npmignore new file mode 100644 index 0000000..aadd196 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.npmignore @@ -0,0 +1,18 @@ +.gitignore +.npmignore +.DS_Store +nwsnapshot +node-webkit*.zip +credits.html +node-webkit.app +npm-debug.log +node_modules +test/ +test.sh +test.bat +test-node-webkit.sh +test-custom-target.sh +scripts +.travis.yml +TODO.md +*.tgz \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.travis.yml new file mode 100644 index 0000000..19bff6a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/.travis.yml @@ -0,0 +1,41 @@ +language: cpp + +# http://docs.travis-ci.com/user/multi-os/ +os: + - linux + - osx + +env: + matrix: + - NODE_VERSION="0.10.36" + - NODE_VERSION="0.12.0" + - NODE_VERSION="iojs-v1.2.0" + global: + - secure: nxPEbegqL+ckZ03BvGJSOlfcNuoJvj+rkLbBmmOEuTrk79lvY0+gjpmvWu4gGXMt89Vz+iAJB29ERaUdriKzlmYmebhWEdwQ/aayUv2sNA0eduvr4TALW2iLfLqryeE4449xnuEvz469AVWxO8xoX9KgmrwTLnkMR9SbQHxB6jU= + - secure: Fs0ilCVBL0DUMkd5vzLGL/5K364kLj1LpSKzwZpPvlU6Gx2jW+Zt59RfM1yOTCvrPWWNb+jc8jz8lbbPXAgUnYNmL54WkIjapr8yPIClw6AtNOSuPtL+zGVGT7FZEO7EntNuEtTer6Wj8IuWUT7myeAezKzNogYg7HyaO4JsoJc= + - secure: ovgkAH1h18pGmoYWN/2tWLF1lqaAK74eK1vnNFB5FMq3wTZYXpzM1W9nT3uqaDsNBUbs/groMcCDU/WBvfQtz9DcocVkuSCVgQ+6MaVVIuH7z7erfIe2sNdq0yhjT4KgBjTZcu6ccVSLjNNQwWctOiPuVgMOLacpN1PuPfs7KCk= + +before_install: +- echo $NODE_VERSION +# upgrade nvm +- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm +- source ~/.nvm/nvm.sh +- nvm install $NODE_VERSION +- nvm use $NODE_VERSION +- node --version +- npm --version +- npm update -g npm +- npm --version + +install: +- npm install + +before_script: +- npm test +# test node-webkit usage +- ./scripts/test-node-webkit.sh + +script: +# test non-authenticated mode +- unset node_pre_gyp_accessKeyId +- npm test diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/CHANGELOG.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/CHANGELOG.md new file mode 100644 index 0000000..c5cf9bd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/CHANGELOG.md @@ -0,0 +1,210 @@ +# node-pre-gyp changelog + +## 0.6.4 + + - Improved support for `io.js` (@fengmk2) + - Test coverage improvements (@mikemorris) + - Fixed support for `--dist-url` that regressed in 0.6.3 + +## 0.6.3 + + - Added support for passing raw options to node-gyp using `--` separator. Flags passed after + the `--` to `node-pre-gyp configure` will be passed directly to gyp while flags passed + after the `--` will be passed directly to make/visual studio. + - Added `node-pre-gyp configure` command to be able to call `node-gyp configure` directly + - Fix issue with require validation not working on windows 7 (@edgarsilva) + +## 0.6.2 + + - Support for io.js >= v1.0.2 + - Deferred require of `request` and `tar` to help speed up command line usage of `node-pre-gyp`. + +## 0.6.1 + + - Fixed bundled `tar` version + +## 0.6.0 + + - BREAKING: node odd releases like v0.11.x now use `major.minor.patch` for `{node_abi}` instead of `NODE_MODULE_VERSION` (#124) + - Added support for `toolset` option in versioning. By default is an empty string but `--toolset` can be passed to publish or install to select alternative binaries that target a custom toolset like C++11. For example to target Visual Studio 2014 modules like node-sqlite3 use `--toolset=v140`. + - Added support for `--no-rollback` option to request that a failed binary test does not remove the binary module leaves it in place. + - Added support for `--update-binary` option to request an existing binary be re-installed and the check for a valid local module be skipped. + - Added support for passing build options from `npm` through `node-pre-gyp` to `node-gyp`: `--nodedir`, `--disturl`, `--python`, and `--msvs_version` + +## 0.5.31 + + - Added support for deducing node_abi for node.js runtime from previous release if the series is even + - Added support for --target=0.10.33 + +## 0.5.30 + + - Repackaged with latest bundled deps + +## 0.5.29 + + - Added support for semver `build`. + - Fixed support for downloading from urls that include `+`. + +## 0.5.28 + + - Now reporting unix style paths only in reveal command + +## 0.5.27 + + - Fixed support for auto-detecting s3 bucket name when it contains `.` - @taavo + - Fixed support for installing when path contains a `'` - @halfdan + - Ported tests to mocha + +## 0.5.26 + + - Fix node-webkit support when `--target` option is not provided + +## 0.5.25 + + - Fix bundling of deps + +## 0.5.24 + + - Updated ABI crosswalk to incldue node v0.10.30 and v0.10.31 + +## 0.5.23 + + - Added `reveal` command. Pass no options to get all versioning data as json. Pass a second arg to grab a single versioned property value + - Added support for `--silent` (shortcut for `--loglevel=silent`) + +## 0.5.22 + + - Fixed node-webkit versioning name (NOTE: node-webkit support still experimental) + +## 0.5.21 + + - New package to fix `shasum check failed` error with v0.5.20 + +## 0.5.20 + + - Now versioning node-webkit binaries based on major.minor.patch - assuming no compatible ABI across versions (#90) + +## 0.5.19 + + - Updated to know about more node-webkit releases + +## 0.5.18 + + - Updated to know about more node-webkit releases + +## 0.5.17 + + - Updated to know about node v0.10.29 release + +## 0.5.16 + + - Now supporting all aws-sdk configuration parameters (http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html) (#86) + +## 0.5.15 + + - Fixed installation of windows packages sub directories on unix systems (#84) + +## 0.5.14 + + - Finished support for cross building using `--target_platform` option (#82) + - Now skipping binary validation on install if target arch/platform do not match the host. + - Removed multi-arch validing for OS X since it required a FAT node.js binary + +## 0.5.13 + + - Fix problem in 0.5.12 whereby the wrong versions of mkdirp and semver where bundled. + +## 0.5.12 + + - Improved support for node-webkit (@Mithgol) + +## 0.5.11 + + - Updated target versions listing + +## 0.5.10 + + - Fixed handling of `-debug` flag passed directory to node-pre-gyp (#72) + - Added optional second arg to `node_pre_gyp.find` to customize the default versioning options used to locate the runtime binary + - Failed install due to `testbinary` check failure no longer leaves behind binary (#70) + +## 0.5.9 + + - Fixed regression in `testbinary` command causing installs to fail on windows with 0.5.7 (#60) + +## 0.5.8 + + - Started bundling deps + +## 0.5.7 + + - Fixed the `testbinary` check, which is used to determine whether to re-download or source compile, to work even in complex dependency situations (#63) + - Exposed the internal `testbinary` command in node-pre-gyp command line tool + - Fixed minor bug so that `fallback_to_build` option is always respected + +## 0.5.6 + + - Added support for versioning on the `name` value in `package.json` (#57). + - Moved to using streams for reading tarball when publishing (#52) + +## 0.5.5 + + - Improved binary validation that also now works with node-webkit (@Mithgol) + - Upgraded test apps to work with node v0.11.x + - Improved test coverage + +## 0.5.4 + + - No longer depends on external install of node-gyp for compiling builds. + +## 0.5.3 + + - Reverted fix for debian/nodejs since it broke windows (#45) + +## 0.5.2 + + - Support for debian systems where the node binary is named `nodejs` (#45) + - Added `bin/node-pre-gyp.cmd` to be able to run command on windows locally (npm creates an .npm automatically when globally installed) + - Updated abi-crosswalk with node v0.10.26 entry. + +## 0.5.1 + + - Various minor bug fixes, several improving windows support for publishing. + +## 0.5.0 + + - Changed property names in `binary` object: now required are `module_name`, `module_path`, and `host`. + - Now `module_path` supports versioning, which allows developers to opt-in to using a versioned install path (#18). + - Added `remote_path` which also supports versioning. + - Changed `remote_uri` to `host`. + +## 0.4.2 + + - Added support for `--target` flag to request cross-compile against a specific node/node-webkit version. + - Added preliminary support for node-webkit + - Fixed support for `--target_arch` option being respected in all cases. + +## 0.4.1 + + - Fixed exception when only stderr is available in binary test (@bendi / #31) + +## 0.4.0 + + - Enforce only `https:` based remote publishing access. + - Added `node-pre-gyp info` command to display listing of published binaries + - Added support for changing the directory node-pre-gyp should build in with the `-C/--directory` option. + - Added support for S3 prefixes. + +## 0.3.1 + + - Added `unpublish` command. + - Fixed module path construction in tests. + - Added ability to disable falling back to build behavior via `npm install --fallback-to-build=false` which overrides setting in a depedencies package.json `install` target. + +## 0.3.0 + + - Support for packaging all files in `module_path` directory - see `app4` for example + - Added `testpackage` command. + - Changed `clean` command to only delete `.node` not entire `build` directory since node-gyp will handle that. + - `.node` modules must be in a folder of there own since tar-pack will remove everything when it unpacks. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/LICENSE new file mode 100644 index 0000000..8f5fce9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/LICENSE @@ -0,0 +1,27 @@ +Copyright (c), Mapbox + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of node-pre-gyp nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/README.md new file mode 100644 index 0000000..86c18c6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/README.md @@ -0,0 +1,581 @@ +# node-pre-gyp + +#### node-pre-gyp makes it easy to publish and install Node.js C++ addons from binaries + +[![NPM](https://nodei.co/npm/node-pre-gyp.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-pre-gyp/) + +[![Build Status](https://api.travis-ci.org/mapbox/node-pre-gyp.svg)](https://travis-ci.org/mapbox/node-pre-gyp) +[![Build status](https://ci.appveyor.com/api/projects/status/3nxewb425y83c0gv)](https://ci.appveyor.com/project/Mapbox/node-pre-gyp) +[![Dependencies](https://david-dm.org/mapbox/node-pre-gyp.svg)](https://david-dm.org/mapbox/node-pre-gyp) + +`node-pre-gyp` stands between [npm](https://github.com/npm/npm) and [node-gyp](https://github.com/Tootallnate/node-gyp) and offers a cross-platform method of binary deployment. + +### Features + + - A command line tool called `node-pre-gyp` that can install your package's c++ module from a binary. + - A variety of developer targeted commands for packaging, testing, and publishing binaries. + - A Javascript module that can dynamically require your installed binary: `require('node-pre-gyp').find` + +For a hello world example of a module packaged with `node-pre-gyp` see and [the wiki ](https://github.com/mapbox/node-pre-gyp/wiki/Modules-using-node-pre-gyp) for real world examples. + +## Credits + + - The module is modeled after [node-gyp](https://github.com/Tootallnate/node-gyp) by [@Tootallnate](https://github.com/Tootallnate) + - Motivation for initial development came from [@ErisDS](https://github.com/ErisDS) and the [Ghost Project](https://github.com/TryGhost/Ghost). + - Development is sponsored by [Mapbox](https://www.mapbox.com/) + +## FAQ + +See the [Frequently Ask Questions](https://github.com/mapbox/node-pre-gyp/wiki/FAQ). + +## Depends + + - Node.js 0.12.x -> 0.8.x + +## Install + +`node-pre-gyp` is designed to be installed as a local dependency of your Node.js C++ addon and accessed like: + + ./node_modules/.bin/node-pre-gyp --help + +But you can also install it globally: + + npm install node-pre-gyp -g + +## Usage + +### Commands + +View all possible commands: + + node-pre-gyp --help + +- clean - Remove the entire folder containing the compiled .node module +- install - Install pre-built binary for module +- reinstall - Run "clean" and "install" at once +- build - Compile the module by dispatching to node-gyp or nw-gyp +- rebuild - Run "clean" and "build" at once +- package - Pack binary into tarball +- testpackage - Test that the staged package is valid +- publish - Publish pre-built binary +- unpublish - Unpublish pre-built binary +- info - Fetch info on published binaries + +You can also chain commands: + + node-pre-gyp clean build unpublish publish info + +### Options + +Options include: + + - `-C/--directory`: run the command in this directory + - `--build-from-source`: build from source instead of using pre-built binary + - `--runtime=node-webkit`: customize the runtime: `node` and `node-webkit` are the valid options + - `--fallback-to-build`: fallback to building from source if pre-built binary is not available + - `--target=0.10.25`: Pass the target node or node-webkit version to compile against + - `--target_arch=ia32`: Pass the target arch and override the host `arch`. Valid values are 'ia32','x64', or `arm`. + - `--target_platform=win32`: Pass the target platform and override the host `platform`. Valid values are `linux`, `darwin`, `win32`, `sunos`, `freebsd`, `openbsd`, and `aix`. + +Both `--build-from-source` and `--fallback-to-build` can be passed alone or they can provide values. You can pass `--fallback-to-build=false` to override the option as declared in package.json. In addition to being able to pass `--build-from-source` you can also pass `--build-from-source=myapp` where `myapp` is the name of your module. + +For example: `npm install --build-from-source=myapp`. This is useful if: + + - `myapp` is referenced in the package.json of a larger app and therefore `myapp` is being installed as a dependent with `npm install`. + - The larger app also depends on other modules installed with `node-pre-gyp` + - You only want to trigger a source compile for `myapp` and the other modules. + +### Configuring + +This is a guide to configuring your module to use node-pre-gyp. + +#### 1) Add new entries to your `package.json` + + - Add `node-pre-gyp` to `bundledDependencies` + - Add `aws-sdk` as a `devDependency` + - Add a custom `install` script + - Declare a `binary` object + +This looks like: + +```js + "dependencies" : { + "node-pre-gyp": "0.5.x" + }, + "bundledDependencies":["node-pre-gyp"], + "devDependencies": { + "aws-sdk": "~2.0.0-rc.15" + } + "scripts": { + "install": "node-pre-gyp install --fallback-to-build", + }, + "binary": { + "module_name": "your_module", + "module_path": "./lib/binding/", + "host": "https://your_module.s3-us-west-1.amazonaws.com" + } +``` + +For a full example see [node-addon-examples's package.json](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/package.json#L11-L22). + +##### The `binary` object has three required properties + +###### module_name + +The name of your native node module. This value must: + + - Match the name passed to [the NODE_MODULE macro](http://nodejs.org/api/addons.html#addons_hello_world) + - Must be a valid C variable name (e.g. it cannot contain `-`) + - Should not include the `.node` extension. + +###### module_path + +The location your native module is placed after a build. This should be an empty directory without other Javascript files. This entire directory will be packaged in the binary tarball. When installing from a remote package this directory will be overwritten with the contents of the tarball. + +Note: This property supports variables based on [Versioning](#versioning). + +###### host + +A url to the remote location where you've published tarball binaries (must be `https` not `http`). + +It is highly recommended that you use Amazon S3. The reasons are: + + - Various node-pre-gyp commands like `publish` and `info` only work with an S3 host. + - S3 is a very solid hosting platform for distributing large files, even [Github recommends using it instead of github](https://help.github.com/articles/distributing-large-binaries). + - We provide detail documentation for using [S3 hosting](#s3-hosting) with node-pre-gyp. + +Why then not require S3? Because while some applications using node-pre-gyp need to distribute binaries as large as 20-30 MB, others might have very small binaries and might wish to store them in a github repo. This is not recommended, but if an author really wants to host in a non-s3 location then it should be possible. + +##### The `binary` object has two optional properties + +###### remote_path + +It **is recommended** that you customize this property. This is an extra path to use for publishing and finding remote tarballs. The default value for `remote_path` is `""` meaning that if you do not provide it then all packages will be published at the base of the `host`. It is recommended to provide a value like `./{name}/v{version}` to help organize remote packages in the case that you choose to publish multiple node addons to the same `host`. + +Note: This property supports variables based on [Versioning](#versioning). + +###### package_name + +It is **not recommended** to override this property unless you are also overriding the `remote_path`. This is the versioned name of the remote tarball containing the binary `.node` module and any supporting files you've placed inside the `module_path` directory. Unless you specify `package_name` in your `package.json` then it defaults to `{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz` which allows your binary to work across node versions, platforms, and architectures. If you are using `remote_path` that is also versioned by `./{module_name}/v{version}` then you could remove these variables from the `package_name` and just use: `{node_abi}-{platform}-{arch}.tar.gz`. Then your remote tarball will be looked up at, for example, `https://example.com/your-module/v0.1.0/node-v11-linux-x64.tar.gz`. + +Avoiding the version of your module in the `package_name` and instead only embedding in a directory name can be useful when you want to make a quick tag of your module that does not change any C++ code. In this case you can just copy binaries to the new version behind the scenes like: + +```sh +aws s3 sync --acl public-read s3://mapbox-node-binary/sqlite3/v3.0.3/ s3://mapbox-node-binary/sqlite3/v3.0.4/ +``` + +Note: This property supports variables based on [Versioning](#versioning). + +#### 2) Add a new target to binding.gyp + +`node-pre-gyp` calls out to `node-gyp` to compile the module and passes variables along like [module_name](#module_name) and [module_path](#module_path). + +A new target must be added to `binding.gyp` that moves the compiled `.node` module from `./build/Release/module_name.node` into the directory specified by `module_path`. + +Add a target like this at the end of your `targets` list: + +```js + { + "target_name": "action_after_build", + "type": "none", + "dependencies": [ "<(module_name)" ], + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], + "destination": "<(module_path)" + } + ] + } +``` + +For a full example see [node-addon-example's binding.gyp](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/binding.gyp). + +#### 3) Dynamically require your `.node` + +Inside the main js file that requires your addon module you are likely currently doing: + +```js +var binding = require('../build/Release/binding.node'); +``` + +or: + +```js +var bindings = require('./bindings') +``` + +Change those lines to: + +```js +var binary = require('node-pre-gyp'); +var path = require('path'); +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); +``` + +For a full example see [node-addon-example's index.js](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/index.js#L1-L4) + +#### 4) Build and package your app + +Now build your module from source: + + npm install --build-from-source + +The `--build-from-source` tells `node-pre-gyp` to not look for a remote package and instead dispatch to node-gyp to build. + +Now `node-pre-gyp` should now also be installed as a local dependency so the command line tool it offers can be found at `./node_modules/.bin/node-pre-gyp`. + +#### 5) Test + +Now `npm test` should work just as it did before. + +#### 6) Publish the tarball + +Then package your app: + + ./node_modules/.bin/node-pre-gyp package + +Once packaged, now you can publish: + + ./node_modules/.bin/node-pre-gyp publish + +Currently the `publish` command pushes your binary to S3. This requires: + + - You have installed `aws-sdk` with `npm install aws-sdk` + - You have created a bucket already. + - The `host` points to an S3 http or https endpoint. + - You have configured node-pre-gyp to read your S3 credentials (see [S3 hosting](#s3-hosting) for details). + +You can also host your binaries elsewhere. To do this requires: + + - You manually publish the binary created by the `package` command to an `https` endpoint + - Ensure that the `host` value points to your custom `https` endpoint. + +#### 7) Automate builds + +Now you need to publish builds for all the platforms and node versions you wish to support. This is best automated. + + - See [Appveyor Automation](#appveyor-automation) for how to auto-publish builds on Windows. + - See [Travis Automation](#travis-automation) for how to auto-publish builds on OS X and Linux. + +#### 8) You're done! + +Now publish your module to the npm registry. Users will now be able to install your module from a binary. + +What will happen is this: + +1. `npm install ` will pull from the npm registry +2. npm will run the `install` script which will call out to `node-pre-gyp` +3. `node-pre-gyp` will fetch the binary `.node` module and unpack in the right place +4. Assuming that all worked, you are done + +If a a binary was not available for a given platform and `--fallback-to-build` was used then `node-gyp rebuild` will be called to try to source compile the module. + +## S3 Hosting + +You can host wherever you choose but S3 is cheap, `node-pre-gyp publish` expects it, and S3 can be integrated well with [travis.ci](http://travis-ci.org) to automate builds for OS X and Ubuntu. Here is an approach to do this: + +First, get setup locally and test the workflow: + +#### 1) Create an S3 bucket + +And have your **key** and **secret key** ready for writing to the bucket. + +It is recommended to create a IAM user with a policy that only gives permissions to the specific bucket you plan to publish to. This can be done in the [IAM console](https://console.aws.amazon.com/iam/) by: 1) adding a new user, 2) choosing `Attach User Policy`, 3) Using the `Policy Generator`, 4) selecting `Amazon S3` for the service, 5) adding the actions: `DeleteObject`, `GetObject`, `GetObjectAcl`, `ListBucket`, `PutObject`, `PutObjectAcl`, 6) adding an ARN of `arn:aws:s3:::bucket/*` (replacing `bucket` with your bucket name), and finally 7) clicking `Add Statement` and saving the policy. It should generate a policy like: + +```js +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "Stmt1394587197000", + "Effect": "Allow", + "Action": [ + "s3:DeleteObject", + "s3:GetObject", + "s3:GetObjectAcl", + "s3:ListBucket", + "s3:PutObject", + "s3:PutObjectAcl" + ], + "Resource": [ + "arn:aws:s3:::node-pre-gyp-tests/*" + ] + } + ] +} +``` + +#### 2) Install node-pre-gyp + +Either install it globally: + + npm install node-pre-gyp -g + +Or put the local version on your PATH + + export PATH=`pwd`/node_modules/.bin/:$PATH + +#### 3) Configure AWS credentials + +There are several ways to do this. + +You can use any of the methods described at http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html. + +Or you can create a `~/.node_pre_gyprc` + +Or pass options in any way supported by [RC](https://github.com/dominictarr/rc#standards) + +A `~/.node_pre_gyprc` looks like: + +```js +{ + "accessKeyId": "xxx", + "secretAccessKey": "xxx" +} +``` + +Another way is to use your environment: + + export node_pre_gyp_accessKeyId=xxx + export node_pre_gyp_secretAccessKey=xxx + +You may also need to specify the `region` if it is not explicit in the `host` value you use. The `bucket` can also be specified but it is optional because `node-pre-gyp` will detect it from the `host` value. + +#### 4) Package and publish your build + +Install the `aws-sdk`: + + npm install aws-sdk + +Then publish: + + node-pre-gyp package publish + +Note: if you hit an error like `Hostname/IP doesn't match certificate's altnames` it may mean that you need to provide the `region` option in your config. + +## Appveyor Automation + +[Appveyor](http://www.appveyor.com/) can build binaries and publish the results per commit and supports: + + - Windows Visual Studio 2013 and related compilers + - Both 64 bit (x64) and 32 bit (x86) build configurations + - Multiple Node.js versions + +For an example of doing this see [node-sqlite3's appveyor.yml](https://github.com/mapbox/node-sqlite3/blob/master/appveyor.yml). + +Below is a guide to getting set up: + +#### 1) Create a free Appveyor account + +Go to https://ci.appveyor.com/signup/free and sign in with your github account. + +#### 2) Create a new project + +Go to https://ci.appveyor.com/projects/new and select the github repo for your module + +#### 3) Add appveyor.yml and push it + +Once you have committed an `appveyor.yml` ([appveyor.yml reference](http://www.appveyor.com/docs/appveyor-yml)) to your github repo and pushed it appveyor should automatically start building your project. + +#### 4) Create secure variables + +Encrypt your S3 AWS keys by going to and hitting the `encrypt` button. + +Then paste the result into your `appveyor.yml` + +```yml +environment: + node_pre_gyp_accessKeyId: + secure: Dn9HKdLNYvDgPdQOzRq/DqZ/MPhjknRHB1o+/lVU8MA= + node_pre_gyp_secretAccessKey: + secure: W1rwNoSnOku1r+28gnoufO8UA8iWADmL1LiiwH9IOkIVhDTNGdGPJqAlLjNqwLnL +``` + +NOTE: keys are per account but not per repo (this is difference than travis where keys are per repo but not related to the account used to encrypt them). + +#### 5) Hook up publishing + +Just put `node-pre-gyp package publish` in your `appveyor.yml` after `npm install`. + +#### 6) Publish when you want + +You might wish to publish binaries only on a specific commit. To do this you could borrow from the [travis.ci idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`: + + SET CM=%APPVEYOR_REPO_COMMIT_MESSAGE% + if not "%CM%" == "%CM:[publish binary]=%" node-pre-gyp --msvs_version=2013 publish + +If your commit message contains special characters (e.g. `&`) this method might fail. An alternative is to use PowerShell, which gives you additional possibilities, like ignoring case by using `ToLower()`: + + ps: if($env:APPVEYOR_REPO_COMMIT_MESSAGE.ToLower().Contains('[publish binary]')) { node-pre-gyp --msvs_version=2013 publish } + +Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on travis see http://about.travis-ci.org/docs/user/deployment/npm/ + + +## Travis Automation + +[Travis](https://travis-ci.org/) can push to S3 after a successful build and supports both: + + - Ubuntu Precise and OS X (64 bit) + - Multiple Node.js versions + +For an example of doing this see [node-add-example's .travis.yml](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/.travis.yml). + +Note: if you need 32 bit binaries, this can be done from a 64 bit travis machine. See [the node-sqlite3 scripts for an example of doing this](https://github.com/mapbox/node-sqlite3/blob/bae122aa6a2b8a45f6b717fab24e207740e32b5d/scripts/build_against_node.sh#L54-L74). + +Below is a guide to getting set up: + +#### 1) Install the travis gem + + gem install travis + +#### 2) Create secure variables + +Make sure you run this command from within the directory of your module. + +Use `travis-encrypt` like: + + travis encrypt node_pre_gyp_accessKeyId=${node_pre_gyp_accessKeyId} + travis encrypt node_pre_gyp_secretAccessKey=${node_pre_gyp_secretAccessKey} + +Then put those values in your `.travis.yml` like: + +```yaml +env: + global: + - secure: F+sEL/v56CzHqmCSSES4pEyC9NeQlkoR0Gs/ZuZxX1ytrj8SKtp3MKqBj7zhIclSdXBz4Ev966Da5ctmcTd410p0b240MV6BVOkLUtkjZJyErMBOkeb8n8yVfSoeMx8RiIhBmIvEn+rlQq+bSFis61/JkE9rxsjkGRZi14hHr4M= + - secure: o2nkUQIiABD139XS6L8pxq3XO5gch27hvm/gOdV+dzNKc/s2KomVPWcOyXNxtJGhtecAkABzaW8KHDDi5QL1kNEFx6BxFVMLO8rjFPsMVaBG9Ks6JiDQkkmrGNcnVdxI/6EKTLHTH5WLsz8+J7caDBzvKbEfTux5EamEhxIWgrI= +``` + +More details on travis encryption at http://about.travis-ci.org/docs/user/encryption-keys/. + +#### 3) Hook up publishing + +Just put `node-pre-gyp package publish` in your `.travis.yml` after `npm install`. + +##### OS X publishing + +If you want binaries for OS X in addition to linux you have two options: + +1) [Enabling multi-OS](#enabling-multi-os) + +2) [Using `language: objective-c` in a git branch](#using-language-objective-c). + +##### Enabling multi-OS + +This requires emailing a request to `support@travis-ci.com` for each repo you wish to have enabled. More details at . + +Next you need to tweak the `.travis.yml` to ensure it is cross platform. + +Use a configuration like: + +```yml + +language: cpp + +os: +- linux +- osx + +env: + matrix: + - NODE_VERSION="0.10" + - NODE_VERSION="0.11.14" + +before_install: +- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm +- source ~/.nvm/nvm.sh +- nvm install $NODE_VERSION +- nvm use $NODE_VERSION +``` + +See [Travis OS X Gochas](#travis-os-x-gochas) for why we replace `language: node_js` and `node_js:` sections with `language: cpp` and a custom matrix. + + +Also create platform specific sections for any deps that need install. For example if you need libpng: + +```yml +- if [ $(uname -s) == 'Linux' ]; then apt-get install libpng-dev; fi; +- if [ $(uname -s) == 'Darwin' ]; then brew install libpng; fi; +``` + +For detailed multi-OS examples see [node-mapnik](https://github.com/mapnik/node-mapnik/blob/master/.travis.yml) and [node-sqlite3](https://github.com/mapbox/node-sqlite3/blob/master/.travis.yml). + +##### Using `language: objective-c` + +If your repo does not have multi-OS enabled, an alternative method for building for OS X is to tweak your `.travis.yml` to use: + +```yml +language: objective-c +``` + +Keep that change in a different git branch and sync that when you want binaries published. + +Next learn about a few [Travis OS X Gochas](#travis-os-x-gochas). + +##### Travis OS X Gochas + +First, unlike the Travis linux machines the OS X machines do not put `node-pre-gyp` on PATH by default. So to you will need to: + +```sh +export PATH=$(pwd)/node_modules/.bin:${PATH} +``` + +Second, the OS X machines doe not support using a matrix for installing node.js different versions. So you need to bootstrap the installation of node.js in a cross platform way. + +By doing: + +```yml +env: + matrix: + - NODE_VERSION="0.10" + - NODE_VERSION="0.11.14" + +before_install: + - rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm + - source ~/.nvm/nvm.sh + - nvm install $NODE_VERSION + - nvm use $NODE_VERSION +``` + +You can easily recreate the previous behavior of this matrix: + +```yml +node_js: + - "0.10" + - "0.11.14" +``` + +#### 4) Publish when you want + +You might wish to publish binaries only on a specific commit. To do this you could borrow from the [travis.ci idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`: + + COMMIT_MESSAGE=$(git show -s --format=%B $TRAVIS_COMMIT | tr -d '\n') + if [[ ${COMMIT_MESSAGE} =~ "[publish binary]" ]]; then node-pre-gyp publish; fi; + +Then you can trigger new binaries to be built like: + + git commit -a -m "[publish binary]" + +Or, if you don't have any changes to make simply run: + + git commit --allow-empty -m "[publish binary]" + +Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on travis see http://about.travis-ci.org/docs/user/deployment/npm/ + +# Versioning + +The `binary` properties of `module_path`, `remote_path`, and `package_name` support variable substitution. The strings are evaluated by `node-pre-gyp` depending on your system and any custom build flags you passed. + + - `node_abi`: The node C++ `ABI` number. This value is available in Javascript as `process.versions.modules` as of [`>= v0.10.4 >= v0.11.7`](https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e) and in C++ as the `NODE_MODULE_VERSION` define much earlier. For versions of Node before this was available we fallback to the V8 major and minor version. + - `platform` matches node's `process.platform` like `linux`, `darwin`, and `win32` unless the user passed the `--target_platform` option to override. + - `arch` matches node's `process.arch` like `x64` or `ia32` unless the user passes the `--target_arch` option to override. + - `configuration` - Either 'Release' or 'Debug' depending on if `--debug` is passed during the build. + - `module_name` - the `binary.module_name` attribute from `package.json`. + - `version` - the semver `version` value for your module from `package.json` (NOTE: ignores the `semver.build` property). + - `major`, `minor`, `patch`, and `prelease` match the individual semver values for your module's `version` + - `build` - the sevmer `build` value. For example it would be `this.that` if your package.json `version` was `v1.0.0+this.that` + - `prerelease` - the semver `prerelease` value. For example it would be `alpha.beta` if your package.json `version` was `v1.0.0-alpha.beta` + + +The options are visible in the code at diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/appveyor.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/appveyor.yml new file mode 100644 index 0000000..e2532bd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/appveyor.yml @@ -0,0 +1,30 @@ +environment: + matrix: + - nodejs_version: 0.10.36 + - nodejs_version: 0.12.0 + - nodejs_version: 1.2.0 + +platform: + - x64 + - x86 + +shallow_clone: true + +install: + - ps: Install-Product node $env:nodejs_version $env:Platform + - node --version + - npm --version + - SET PATH=%APPDATA%\npm;%PATH% + - npm update -g npm + - npm --version + - node -e "console.log(process.arch);" + - SET PATH=C:\Program Files (x86)\MSBuild\12.0\bin\;%PATH% + - if "%PLATFORM%" == "x64" set PATH=C:\Python27-x64;%PATH% + - if "%PLATFORM%" == "x86" SET PATH=C:\python27;%PATH% + - npm install + - npm test + - .\scripts\test.bat + +build: off +test: off +deploy: off diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/bin/node-pre-gyp.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/bin/node-pre-gyp.js new file mode 100755 index 0000000..160add1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/bin/node-pre-gyp.js @@ -0,0 +1,131 @@ +#!/usr/bin/env node + +'use strict'; + +/** + * Set the title. + */ + +process.title = 'node-pre-gyp'; + +/** + * Module dependencies. + */ + +var node_pre_gyp = require('../'); +var log = require('npmlog'); + +/** + * Process and execute the selected commands. + */ + +var prog = new node_pre_gyp.Run(); +var completed = false; +prog.parseArgv(process.argv); + +if (prog.todo.length === 0) { + if (~process.argv.indexOf('-v') || ~process.argv.indexOf('--version')) { + console.log('v%s', prog.version); + } else { + console.log('%s', prog.usage()); + } + return process.exit(0); +} + +// if --no-color is passed +if (prog.opts && prog.opts.hasOwnProperty('color') && !prog.opts.color) { + log.disableColor(); +} + +log.info('it worked if it ends with', 'ok'); +log.verbose('cli', process.argv); +log.info('using', process.title + '@%s', prog.version); +log.info('using', 'node@%s | %s | %s', process.versions.node, process.platform, process.arch); + + +/** + * Change dir if -C/--directory was passed. + */ + +var dir = prog.opts.directory; +if (dir) { + var fs = require('fs'); + try { + var stat = fs.statSync(dir); + if (stat.isDirectory()) { + log.info('chdir', dir); + process.chdir(dir); + } else { + log.warn('chdir', dir + ' is not a directory'); + } + } catch (e) { + if (e.code === 'ENOENT') { + log.warn('chdir', dir + ' is not a directory'); + } else { + log.warn('chdir', 'error during chdir() "%s"', e.message); + } + } +} + +function run () { + var command = prog.todo.shift(); + if (!command) { + // done! + completed = true; + log.info('ok'); + return; + } + + prog.commands[command.name](command.args, function (err) { + if (err) { + log.error(command.name + ' error'); + log.error('stack', err.stack); + errorMessage(); + log.error('not ok'); + console.log(err.message); + return process.exit(1); + } + var args_array = [].slice.call(arguments, 1); + if (args_array.length) { + console.log.apply(console, args_array); + } + // now run the next command in the queue + process.nextTick(run); + }); +} + +process.on('exit', function (code) { + if (!completed && !code) { + log.error('Completion callback never invoked!'); + issueMessage(); + process.exit(6); + } +}); + +process.on('uncaughtException', function (err) { + log.error('UNCAUGHT EXCEPTION'); + log.error('stack', err.stack); + issueMessage(); + process.exit(7); +}); + +function errorMessage () { + // copied from npm's lib/util/error-handler.js + var os = require('os'); + log.error('System', os.type() + ' ' + os.release()); + log.error('command', process.argv.map(JSON.stringify).join(' ')); + log.error('cwd', process.cwd()); + log.error('node -v', process.version); + log.error(process.title+' -v', 'v' + prog.package.version); +} + +function issueMessage () { + errorMessage(); + log.error('', [ 'This is a bug in `'+process.title+'`.', + 'Try to update '+process.title+' and file an issue if it does not help:', + ' ', + ].join('\n')); +} + +// start running the given commands! +run(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/build.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/build.js new file mode 100644 index 0000000..1074fa3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/build.js @@ -0,0 +1,43 @@ +"use strict"; + +module.exports = exports = build; + +exports.usage = 'Attempts to compile the module by dispatching to node-gyp or nw-gyp'; + +var compile = require('./util/compile.js'); +var handle_gyp_opts = require('./util/handle_gyp_opts.js'); +var configure = require('./configure.js'); + +function do_build(gyp,argv,callback) { + handle_gyp_opts(gyp,argv,function(err,result) { + var final_args = ['build'].concat(result.gyp).concat(result.pre); + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + compile.run_gyp(final_args,result.opts,function(err) { + return callback(err); + }); + }); +} + +function build(gyp, argv, callback) { + + // Form up commands to pass to node-gyp: + // We map `node-pre-gyp build` to `node-gyp configure build` so that we do not + // trigger a clean and therefore do not pay the penalty of a full recompile + if (argv.length && (argv.indexOf('rebuild') > -1)) { + // here we map `node-pre-gyp rebuild` to `node-gyp rebuild` which internally means + // "clean + configure + build" and triggers a full recompile + compile.run_gyp(['clean'],{},function(err) { + if (err) return callback(err); + configure(gyp,argv,function(err) { + if (err) return callback(err); + return do_build(gyp,argv,callback); + }); + }); + } else { + return do_build(gyp,argv,callback); + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/clean.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/clean.js new file mode 100644 index 0000000..a1289f6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/clean.js @@ -0,0 +1,23 @@ +"use strict"; + +module.exports = exports = clean; + +exports.usage = 'Removes the entire folder containing the compiled .node module'; + +var fs = require('fs'); +var rm = require('rimraf'); +var exists = require('fs').exists || require('path').exists; +var versioning = require('./util/versioning.js'); + +function clean (gyp, argv, callback) { + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + var to_delete = opts.module_path; + exists(to_delete, function(found) { + if (found) { + if (!gyp.opts.silent_clean) console.log('['+package_json.name+'] Removing "%s"', to_delete); + return rm(to_delete, callback); + } + return callback(); + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/configure.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/configure.js new file mode 100644 index 0000000..1ea5664 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/configure.js @@ -0,0 +1,48 @@ +"use strict"; + +module.exports = exports = configure; + +exports.usage = 'Attempts to configure node-gyp or nw-gyp build'; + +var compile = require('./util/compile.js'); +var handle_gyp_opts = require('./util/handle_gyp_opts.js'); + +function configure(gyp, argv, callback) { + handle_gyp_opts(gyp,argv,function(err,result) { + var final_args = result.gyp.concat(result.pre); + // pull select node-gyp configure options out of the npm environ + var known_gyp_args = ['dist-url','python','nodedir','msvs_version']; + known_gyp_args.forEach(function(key) { + var val = gyp.opts[key] || gyp.opts[key.replace('-','_')]; + if (val) { + final_args.push('--'+key+'='+val); + } + }); + // --ensure=false tell node-gyp to re-install node development headers + // but it is only respected by node-gyp install, so we have to call install + // as a separate step if the user passes it + if (gyp.opts.ensure === false) { + var install_args = final_args.concat(['install','--ensure=false']); + compile.run_gyp(install_args,result.opts,function(err) { + if (err) return callback(err); + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + compile.run_gyp(['configure'].concat(final_args),result.opts,function(err) { + return callback(err); + }); + }); + } else { + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + compile.run_gyp(['configure'].concat(final_args),result.opts,function(err) { + return callback(err); + }); + } + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/info.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/info.js new file mode 100644 index 0000000..aff9bf8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/info.js @@ -0,0 +1,40 @@ +"use strict"; + +module.exports = exports = unpublish; + +exports.usage = 'Lists all published binaries (requires aws-sdk)'; + +var fs = require('fs'); +var log = require('npmlog'); +var versioning = require('./util/versioning.js'); +var s3_setup = require('./util/s3_setup.js'); +var config = require('rc')("node_pre_gyp",{acl:"public-read"}); + +function unpublish(gyp, argv, callback) { + var AWS = require("aws-sdk"); + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + s3_setup.detect(opts.hosted_path,config); + AWS.config.update(config); + var s3 = new AWS.S3(); + var s3_opts = { Bucket: config.bucket, + Prefix: config.prefix + }; + s3.listObjects(s3_opts, function(err, meta){ + if (err && err.code == 'NotFound') { + return callback(new Error('['+package_json.name+'] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/'+config.prefix)); + } else if(err) { + return callback(err); + } else { + log.verbose(JSON.stringify(meta,null,1)); + if (meta && meta.Contents) { + meta.Contents.forEach(function(obj) { + console.log(obj.Key); + }); + } else { + console.error('['+package_json.name+'] No objects found at https://' + s3_opts.Bucket + '.s3.amazonaws.com/'+config.prefix ); + } + return callback(); + } + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/install.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/install.js new file mode 100644 index 0000000..6939c11 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/install.js @@ -0,0 +1,205 @@ +"use strict"; + +module.exports = exports = install; + +exports.usage = 'Attempts to install pre-built binary for module'; + +var fs = require('fs'); +var path = require('path'); +var zlib = require('zlib'); +var log = require('npmlog'); +var existsAsync = fs.exists || path.exists; +var versioning = require('./util/versioning.js'); +var testbinary = require('./testbinary.js'); +var clean = require('./clean.js'); + +function download(uri,opts,callback) { + log.http('GET', uri); + + var req = null; + var requestOpts = { + uri: uri.replace('+','%2B'), + headers: { + 'User-Agent': 'node-pre-gyp (node ' + process.version + ')' + } + }; + + var proxyUrl = opts.proxy || + process.env.http_proxy || + process.env.HTTP_PROXY || + process.env.npm_config_proxy; + if (proxyUrl) { + if (/^https?:\/\//i.test(proxyUrl)) { + log.verbose('download', 'using proxy url: "%s"', proxyUrl); + requestOpts.proxy = proxyUrl; + } else { + log.warn('download', 'ignoring invalid "proxy" config setting: "%s"', proxyUrl); + } + } + try { + req = require('request')(requestOpts); + } catch (e) { + return callback(e); + } + if (req) { + req.on('response', function (res) { + log.http(res.statusCode, uri); + }); + } + return callback(null,req); +} + +function place_binary(from,to,opts,callback) { + download(from,opts,function(err,req) { + if (err) return callback(err); + if (!req) return callback(new Error("empty req")); + var badDownload = false; + var extractCount = 0; + var gunzip = zlib.createGunzip(); + var extracter = require('tar').Extract({ path: to, strip: 1}); + + function afterTarball(err) { + if (err) return callback(err); + if (badDownload) return callback(new Error("bad download")); + if (extractCount === 0) { + return callback(new Error('There was a fatal problem while downloading/extracting the tarball')); + } + log.info('tarball', 'done parsing tarball'); + callback(); + } + + function filter_func(entry) { + // ensure directories are +x + // https://github.com/mapnik/node-mapnik/issues/262 + entry.props.mode |= (entry.props.mode >>> 2) & parseInt('0111',8); + log.info('install','unpacking ' + entry.path); + extractCount++; + } + + gunzip.on('error', callback); + extracter.on('entry', filter_func); + extracter.on('error', callback); + extracter.on('end', afterTarball); + + req.on('error', function(err) { + badDownload = true; + return callback(err); + }); + + req.on('close', function () { + if (extractCount === 0) { + return callback(new Error('Connection closed while downloading tarball file')); + } + }); + + req.on('response', function(res) { + if (res.statusCode !== 200) { + badDownload = true; + if (res.statusCode == 404) { + return callback(new Error('Pre-built binary not available for your system, looked for ' + from)); + } else { + return callback(new Error(res.statusCode + ' status code downloading tarball ' + from)); + } + } + // start unzipping and untaring + req.pipe(gunzip).pipe(extracter); + }); + }); +} + +function do_build(gyp,argv,callback) { + gyp.todo.push( { name: 'build', args: ['rebuild'] } ); + process.nextTick(callback); +} + +function install(gyp, argv, callback) { + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var source_build = gyp.opts['build-from-source'] || gyp.opts.build_from_source; + var update_binary = gyp.opts['update-binary'] || gyp.opts.update_binary; + var should_do_source_build = source_build === package_json.name || (source_build === true || source_build === 'true'); + var no_rollback = gyp.opts.hasOwnProperty('rollback') && gyp.opts.rollback === false; + if (should_do_source_build) { + log.info('build','requesting source compile'); + return do_build(gyp,argv,callback); + } else { + var fallback_to_build = gyp.opts['fallback-to-build'] || gyp.opts.fallback_to_build; + var should_do_fallback_build = fallback_to_build === package_json.name || (fallback_to_build === true || fallback_to_build === 'true'); + // but allow override from npm + if (process.env.npm_config_argv) { + var cooked = JSON.parse(process.env.npm_config_argv).cooked; + var match = cooked.indexOf("--fallback-to-build"); + if (match > -1 && cooked.length > match && cooked[match+1] == "false") { + should_do_fallback_build = false; + log.info('install','Build fallback disabled via npm flag: --fallback-to-build=false'); + } + } + var opts; + try { + opts = versioning.evaluate(package_json, gyp.opts); + } catch (err) { + return callback(err); + } + var from = opts.hosted_tarball; + var to = opts.module_path; + var binary_module = path.join(to,opts.module_name + '.node'); + if (existsAsync(binary_module,function(found) { + if (found && !update_binary) { + testbinary(gyp, argv, function(err) { + if (err) { + console.error('['+package_json.name+'] ' + err.message); + log.error("Testing local pre-built binary failed, attempting to re-download"); + place_binary(from,to,opts,function(err) { + if (err) { + if (should_do_fallback_build) { + log.http(err.message + ' (falling back to source compile with node-gyp)'); + return do_build(gyp,argv,callback); + } else { + return callback(err); + } + } else { + console.log('['+package_json.name+'] Success: "' + binary_module + '" is reinstalled via remote'); + return callback(); + } + }); + } else { + console.log('['+package_json.name+'] Success: "' + binary_module + '" already installed'); + console.log('Pass --update-binary to reinstall or --build-from-source to recompile'); + return callback(); + } + }); + } else { + if (!update_binary) log.info('check','checked for "' + binary_module + '" (not found)'); + place_binary(from,to,opts,function(err) { + if (err && should_do_fallback_build) { + log.http(err.message + ' (falling back to source compile with node-gyp)'); + return do_build(gyp,argv,callback); + } else if (err) { + return callback(err); + } else { + testbinary(gyp, argv, function(err) { + if (err) { + if (no_rollback) { + return callback(err); + } + gyp.opts.silent_clean = true; + clean(gyp, argv, function(error) { + if (error) console.log(error); + if (should_do_fallback_build) { + console.error('['+package_json.name+'] ' + err.message); + log.error("Testing pre-built binary failed, attempting to source compile"); + return do_build(gyp,argv,callback); + } else { + return callback(err); + } + }); + } else { + console.log('['+package_json.name+'] Success: "' + binary_module + '" is installed via remote'); + return callback(); + } + }); + } + }); + } + })); + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/node-pre-gyp.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/node-pre-gyp.js new file mode 100644 index 0000000..7e60801 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/node-pre-gyp.js @@ -0,0 +1,192 @@ +"use strict"; + +/** + * Module exports. + */ + +module.exports = exports; + +/** + * Module dependencies. + */ + +var path = require('path'); +var nopt = require('nopt'); +var log = require('npmlog'); +var EE = require('events').EventEmitter; +var inherits = require('util').inherits; +var commands = [ + 'clean', + 'install', + 'reinstall', + 'build', + 'rebuild', + 'package', + 'testpackage', + 'publish', + 'publish-maybe', + 'unpublish', + 'info', + 'testbinary', + 'reveal', + 'configure' + ]; +var aliases = {}; + +// differentiate node-pre-gyp's logs from npm's +log.heading = 'node-pre-gyp'; + +exports.find = require('./pre-binding').find; + +function Run() { + var self = this; + + this.commands = {}; + + commands.forEach(function (command) { + self.commands[command] = function (argv, callback) { + log.verbose('command', command, argv); + return require('./' + command)(self, argv, callback); + }; + }); +} +inherits(Run, EE); +exports.Run = Run; +var proto = Run.prototype; + +/** + * Export the contents of the package.json. + */ + +proto.package = require('../package'); + +/** + * nopt configuration definitions + */ + +proto.configDefs = { + help: Boolean, // everywhere + arch: String, // 'configure' + debug: Boolean, // 'build' + directory: String, // bin + proxy: String, // 'install' + loglevel: String, // everywhere +}; + +/** + * nopt shorthands + */ + +proto.shorthands = { + release: '--no-debug', + C: '--directory', + debug: '--debug', + j: '--jobs', + silent: '--loglevel=silent', + silly: '--loglevel=silly', + verbose: '--loglevel=verbose', +}; + +/** + * expose the command aliases for the bin file to use. + */ + +proto.aliases = aliases; + +/** + * Parses the given argv array and sets the 'opts', + * 'argv' and 'command' properties. + */ + +proto.parseArgv = function parseOpts (argv) { + this.opts = nopt(this.configDefs, this.shorthands, argv); + this.argv = this.opts.argv.remain.slice(); + var commands = this.todo = []; + + // create a copy of the argv array with aliases mapped + argv = this.argv.map(function (arg) { + // is this an alias? + if (arg in this.aliases) { + arg = this.aliases[arg]; + } + return arg; + }, this); + + // process the mapped args into "command" objects ("name" and "args" props) + argv.slice().forEach(function (arg) { + if (arg in this.commands) { + var args = argv.splice(0, argv.indexOf(arg)); + argv.shift(); + if (commands.length > 0) { + commands[commands.length - 1].args = args; + } + commands.push({ name: arg, args: [] }); + } + }, this); + if (commands.length > 0) { + commands[commands.length - 1].args = argv.splice(0); + } + + // support for inheriting config env variables from npm + var npm_config_prefix = 'npm_config_'; + Object.keys(process.env).forEach(function (name) { + if (name.indexOf(npm_config_prefix) !== 0) return; + var val = process.env[name]; + if (name === npm_config_prefix + 'loglevel') { + log.level = val; + } else { + // add the user-defined options to the config + name = name.substring(npm_config_prefix.length); + // avoid npm argv clobber already present args + // which avoids problem of 'npm test' calling + // script that runs unique npm install commands + if (name === 'argv') { + if (this.opts.argv && + this.opts.argv.remain && + this.opts.argv.remain.length) { + // do nothing + } else { + this.opts[name] = val; + } + } else { + this.opts[name] = val; + } + } + }, this); + + if (this.opts.loglevel) { + log.level = this.opts.loglevel; + } + log.resume(); +}; + +/** + * Returns the usage instructions for node-pre-gyp. + */ + +proto.usage = function usage () { + var str = [ + '', + ' Usage: node-pre-gyp [options]', + '', + ' where is one of:', + commands.map(function (c) { + return ' - ' + c + ' - ' + require('./' + c).usage; + }).join('\n'), + '', + 'node-pre-gyp@' + this.version + ' ' + path.resolve(__dirname, '..'), + 'node@' + process.versions.node + ].join('\n'); + return str; +}; + +/** + * Version number getter. + */ + +Object.defineProperty(proto, 'version', { + get: function () { + return this.package.version; + }, + enumerable: true +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/package.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/package.js new file mode 100644 index 0000000..3a35f65 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/package.js @@ -0,0 +1,46 @@ +"use strict"; + +module.exports = exports = _package; + +exports.usage = 'Packs binary (and enclosing directory) into locally staged tarball'; + +var fs = require('fs'); +var path = require('path'); +var log = require('npmlog'); +var versioning = require('./util/versioning.js'); +var write = require('fs').createWriteStream; +var existsAsync = fs.exists || path.exists; +var mkdirp = require('mkdirp'); + +function _package(gyp, argv, callback) { + var pack = require('tar-pack').pack; + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + var from = opts.module_path; + var binary_module = path.join(from,opts.module_name + '.node'); + existsAsync(binary_module,function(found) { + if (!found) { + return callback(new Error("Cannot package because " + binary_module + " missing: run `node-pre-gyp rebuild` first")); + } + var tarball = opts.staged_tarball; + var filter_func = function(entry) { + // ensure directories are +x + // https://github.com/mapnik/node-mapnik/issues/262 + log.info('package','packing ' + entry.path); + return true; + }; + mkdirp(path.dirname(tarball),function(err) { + if (err) throw err; + pack(from, { filter: filter_func }) + .pipe(write(tarball)) + .on('error', function(err) { + if (err) console.error('['+package_json.name+'] ' + err.message); + return callback(err); + }) + .on('close', function() { + log.info('package','Binary staged at "' + tarball + '"'); + return callback(); + }); + }); + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/pre-binding.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/pre-binding.js new file mode 100644 index 0000000..326a486 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/pre-binding.js @@ -0,0 +1,25 @@ +"use strict"; + +var versioning = require('../lib/util/versioning.js'); +var existsSync = require('fs').existsSync || require('path').existsSync; +var path = require('path'); + +module.exports = exports; + +exports.usage = 'Finds the require path for the node-pre-gyp installed module'; + +exports.validate = function(package_json) { + versioning.validate_config(package_json); +}; + +exports.find = function(package_json_path,opts) { + if (!existsSync(package_json_path)) { + throw new Error("package.json does not exist at " + package_json_path); + } + var package_json = require(package_json_path); + versioning.validate_config(package_json); + opts = opts || {}; + if (!opts.module_root) opts.module_root = path.dirname(package_json_path); + var meta = versioning.evaluate(package_json,opts); + return meta.module; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish-maybe.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish-maybe.js new file mode 100644 index 0000000..2858b13 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish-maybe.js @@ -0,0 +1,146 @@ +'use strict'; + +var fs = require('fs'); +var log = require('npmlog'); +var versioning = require('./util/versioning.js'); +var s3_setup = require('./util/s3_setup.js'); +var url = require('url'); +var config = require('rc')("node_pre_gyp", { + acl: "public-read" +}); + +var configure = require('./configure.js'); +var compile = require('./util/compile.js'); +var handle_gyp_opts = require('./util/handle_gyp_opts.js'); + +var createTarball = require('./package'); + +var AWS; +try { + AWS = require('aws-sdk'); +} catch (e) { + log.error('publish-maybe', 'aws-sdk not installed'); +} + +function rebuild(gyp, argv, done) { + compile.run_gyp(['clean'], {}, function(err) { + if (err) return done(err); + + configure(gyp, argv, function(err) { + if (err) return done(err); + + handle_gyp_opts(gyp, argv, function(err, result) { + var final_args = ['build'].concat(result.gyp).concat(result.pre); + if (result.unparsed.length > 0) { + final_args = final_args. + concat(['--']). + concat(result.unparsed); + } + compile.run_gyp(final_args, result.opts, function(err) { + return done(err); + }); + }); + }); + }); +} + +function PublishMaybe(gyp, argv, done) { + if (!(this instanceof PublishMaybe)) return new PublishMaybe(gyp, argv, done); + if (AWS) { + var pkg = JSON.parse(fs.readFileSync('./package.json')); + this.state = versioning.evaluate(pkg, gyp.opts); + s3_setup.detect(this.state.hosted_path, config); + AWS.config.update(config); + + this.state.s3_bucket = config.bucket || pkg.binary.bucket; + this.state.s3_key = url.resolve(config.prefix, this.state.package_name); + + log.info('publish-maybe', 'loaded state: ' + JSON.stringify(this.state)); + + if (!this.state.s3_bucket) { + throw new Error('Could not detect s3 bucket automatically and not set in config.'); + } + + this.s3 = new AWS.S3(); + } + var self = this; + this.prepublish(function(err, ok) { + if (err) return done(err); + if (!ok) { + return done(); + } + self.publish(gyp, argv, done); + }); +} + +PublishMaybe.prototype.publish = function(gyp, argv, done) { + var self = this; + rebuild(gyp, argv, function(err) { + if (err) return done(err); + + createTarball(gyp, argv, function(err) { + if (err) return done(err); + + var opts = { + ACL: config.acl, + Body: fs.createReadStream(self.state.staged_tarball), + Bucket: self.state.s3_bucket, + Key: self.state.s3_key + }; + + log.info('publish-maybe', 'Putting object'); + self.s3.putObject(opts, function(err, resp) { + if (err) { + log.info('publish', 's3 putObject error: "' + err + '"'); + return done(err); + } + if (resp) { + log.info('publish-maybe', 's3 putObject response: "' + JSON.stringify(resp) + '"'); + } + console.log('[' + self.state.name + '] published to ' + self.state.hosted_tarball); + return done(); + }); + }); + }); +}; + +PublishMaybe.prototype.prepublish = function(done) { + var self = this; + + self.canPublish(function(err) { + if (err) return done(err); + + self.shouldPublish(done); + }); +}; + +PublishMaybe.prototype.canPublish = function(fn) { + if (!AWS) { + return fn(new Error('aws-sdk not installed. run `npm install -g aws-sdk and try again.`')); + } + fn(); +}; + +PublishMaybe.prototype.shouldPublish = function(fn) { + var opts = { + Bucket: this.state.s3_bucket, + Key: this.state.s3_key + }; + + log.info('publish-maybe', 'Checking for existing binary on S3 ' + JSON.stringify(opts)); + this.s3.headObject(opts, function(err) { + if (err) { + if (err.code == 'NotFound') { + log.info('publish-maybe', 'OK binary does not exist so we should publish'); + return fn(null, true); + } + log.error('publish-maybe', 'Unexpected error: ' + err.stack); + return fn(err); + } + log.info('publish-maybe', 'Binary already exists so we do not need to publish'); + return fn(null, false); + }); +}; + +module.exports = PublishMaybe; +module.exports.usage = 'Publishes pre-built binary if one does not exist (requires aws-sdk)'; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish.js new file mode 100644 index 0000000..d666b01 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/publish.js @@ -0,0 +1,77 @@ +"use strict"; + +module.exports = exports = publish; + +exports.usage = 'Publishes pre-built binary (requires aws-sdk)'; + +var fs = require('fs'); +var path = require('path'); +var log = require('npmlog'); +var versioning = require('./util/versioning.js'); +var s3_setup = require('./util/s3_setup.js'); +var existsAsync = fs.exists || path.exists; +var url = require('url'); +var config = require('rc')("node_pre_gyp",{acl:"public-read"}); + +function publish(gyp, argv, callback) { + var AWS = require("aws-sdk"); + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + var tarball = opts.staged_tarball; + existsAsync(tarball,function(found) { + if (!found) { + return callback(new Error("Cannot publish because " + tarball + " missing: run `node-pre-gyp package` first")); + } + log.info('publish', 'Detecting s3 credentials'); + s3_setup.detect(opts.hosted_path,config); + var key_name = url.resolve(config.prefix,opts.package_name); + log.info('publish', 'Authenticating with s3'); + AWS.config.update(config); + var s3 = new AWS.S3(); + var s3_opts = { Bucket: config.bucket, + Key: key_name + }; + var remote_package = 'https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key; + log.info('publish', 'Checking for existing binary at ' + remote_package); + s3.headObject(s3_opts, function(err, meta){ + if (meta) log.info('publish', JSON.stringify(meta)); + if (err && err.code == 'NotFound') { + // we are safe to publish because + // the object does not already exist + log.info('publish', 'Preparing to put object'); + var s3_put = new AWS.S3(); + var s3_put_opts = { ACL: config.acl, + Body: fs.createReadStream(tarball), + Bucket: config.bucket, + Key: key_name + }; + log.info('publish', 'Putting object'); + try { + s3_put.putObject(s3_put_opts, function(err, resp){ + log.info('publish', 'returned from putting object'); + if(err) { + log.info('publish', 's3 putObject error: "' + err + '"'); + return callback(err); + } + if (resp) log.info('publish', 's3 putObject response: "' + JSON.stringify(resp) + '"'); + log.info('publish', 'successfully put object'); + console.log('['+package_json.name+'] published to ' + remote_package); + return callback(); + }); + } catch (err) { + log.info('publish', 's3 putObject error: "' + err + '"'); + return callback(err); + } + } else if (err) { + log.info('publish', 's3 headObject error: "' + err + '"'); + return callback(err); + } else { + log.error('publish','Cannot publish over existing version'); + log.error('publish',"Update the 'version' field in package.json and try again"); + log.error('publish','If the previous version was published in error see:'); + log.error('publish','\t node-pre-gyp unpublish'); + return callback(new Error('Failed publishing to ' + remote_package)); + } + }); + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/rebuild.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/rebuild.js new file mode 100644 index 0000000..48a7b74 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/rebuild.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = exports = rebuild; + +exports.usage = 'Runs "clean" and "build" at once'; + +function rebuild (gyp, argv, callback) { + gyp.todo.unshift( + { name: 'clean', args: [] }, + { name: 'build', args: ['rebuild'] } + ); + process.nextTick(callback); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reinstall.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reinstall.js new file mode 100644 index 0000000..ed65d54 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reinstall.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = exports = rebuild; + +exports.usage = 'Runs "clean" and "install" at once'; + +function rebuild (gyp, argv, callback) { + gyp.todo.unshift( + { name: 'clean', args: [] }, + { name: 'install', args: [] } + ); + process.nextTick(callback); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reveal.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reveal.js new file mode 100644 index 0000000..e6d00eb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/reveal.js @@ -0,0 +1,31 @@ +"use strict"; + +module.exports = exports = reveal; + +exports.usage = 'Reveals data on the versioned binary'; + +var fs = require('fs'); +var versioning = require('./util/versioning.js'); + +function unix_paths(key, val) { + return val && val.replace ? val.replace(/\\/g, '/') : val; +} + +function reveal(gyp, argv, callback) { + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + var hit = false; + // if a second arg is passed look to see + // if it is a known option + //console.log(JSON.stringify(gyp.opts,null,1)) + var remain = gyp.opts.argv.remain.pop(); + if (remain && opts.hasOwnProperty(remain)) { + console.log(opts[remain].replace(/\\/g, '/')); + hit = true; + } + // otherwise return all options as json + if (!hit) { + console.log(JSON.stringify(opts,unix_paths,2)); + } + return callback(); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testbinary.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testbinary.js new file mode 100644 index 0000000..bbf1076 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testbinary.js @@ -0,0 +1,73 @@ +"use strict"; + +module.exports = exports = testbinary; + +exports.usage = 'Tests that the binary.node can be required'; + +var fs = require('fs'); +var path = require('path'); +var log = require('npmlog'); +var cp = require('child_process'); +var versioning = require('./util/versioning.js'); +var path = require('path'); + +function testbinary(gyp, argv, callback) { + var args = []; + var options = {}; + var shell_cmd = process.execPath; + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + // ensure on windows that / are used for require path + var binary_module = opts.module.replace(/\\/g, '/'); + var nw = (opts.runtime && opts.runtime === 'node-webkit'); + if (nw) { + options.timeout = 5000; + if (process.platform === 'darwin') { + shell_cmd = 'node-webkit'; + } else if (process.platform === 'win32') { + shell_cmd = 'nw.exe'; + } else { + shell_cmd = 'nw'; + } + var modulePath = path.resolve(binary_module); + var appDir = path.join(__dirname, 'util', 'nw-pre-gyp'); + args.push(appDir); + args.push(modulePath); + log.info("validate","Running test command: '" + shell_cmd + ' ' + args.join(' ') + "'"); + cp.execFile(shell_cmd, args, options, function(err, stdout, stderr) { + // check for normal timeout for node-webkit + if (err) { + if (err.killed === true && err.signal && err.signal.indexOf('SIG') > -1) { + return callback(); + } + var stderrLog = stderr.toString(); + log.info('stderr', stderrLog); + if( /^\s*Xlib:\s*extension\s*"RANDR"\s*missing\s*on\s*display\s*":\d+\.\d+"\.\s*$/.test(stderrLog) ){ + log.info('RANDR', 'stderr contains only RANDR error, ignored'); + return callback(); + } + return callback(err); + } + return callback(); + }); + return; + } + if ((process.arch != opts.target_arch) || + (process.platform != opts.target_platform)) { + var msg = "skipping validation since host platform/arch ("; + msg += process.platform+'/'+process.arch+")"; + msg += " does not match target ("; + msg += opts.target_platform+'/'+opts.target_arch+")"; + log.info('validate', msg); + return callback(); + } + args.push('--eval'); + args.push("'require(\\'" + binary_module.replace(/\'/g, '\\\'') +"\\')'"); + log.info("validate","Running test command: '" + shell_cmd + ' ' + args.join(' ') + "'"); + cp.execFile(shell_cmd, args, options, function(err, stdout, stderr) { + if (err) { + return callback(err, { stdout:stdout, stderr:stderr}); + } + return callback(); + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testpackage.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testpackage.js new file mode 100644 index 0000000..1d4cc60 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/testpackage.js @@ -0,0 +1,49 @@ +"use strict"; + +module.exports = exports = testpackage; + +exports.usage = 'Tests that the staged package is valid'; + +var fs = require('fs'); +var path = require('path'); +var log = require('npmlog'); +var existsAsync = fs.exists || path.exists; +var versioning = require('./util/versioning.js'); +var testbinary = require('./testbinary.js'); +var read = require('fs').createReadStream; +var zlib = require('zlib'); + +function testpackage(gyp, argv, callback) { + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + var tarball = opts.staged_tarball; + existsAsync(tarball, function(found) { + if (!found) { + return callback(new Error("Cannot test package because " + tarball + " missing: run `node-pre-gyp package` first")); + } + var to = opts.module_path; + var gunzip = zlib.createGunzip(); + var extracter = require('tar').Extract({ path: to, strip: 1 }); + function filter_func(entry) { + // ensure directories are +x + // https://github.com/mapnik/node-mapnik/issues/262 + entry.props.mode |= (entry.props.mode >>> 2) & parseInt('0111',8); + log.info('install','unpacking ' + entry.path); + } + gunzip.on('error', callback); + extracter.on('error', callback); + extracter.on('entry', filter_func); + extracter.on('end', function(err) { + if (err) return callback(err); + testbinary(gyp,argv,function(err) { + if (err) { + return callback(err); + } else { + console.log('['+package_json.name+'] Package appears valid'); + return callback(); + } + }); + }); + read(tarball).pipe(gunzip).pipe(extracter); + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/unpublish.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/unpublish.js new file mode 100644 index 0000000..43f8e66 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/unpublish.js @@ -0,0 +1,41 @@ +"use strict"; + +module.exports = exports = unpublish; + +exports.usage = 'Unpublishes pre-built binary (requires aws-sdk)'; + +var fs = require('fs'); +var log = require('npmlog'); +var versioning = require('./util/versioning.js'); +var s3_setup = require('./util/s3_setup.js'); +var url = require('url'); +var config = require('rc')("node_pre_gyp",{acl:"public-read"}); + +function unpublish(gyp, argv, callback) { + var AWS = require("aws-sdk"); + var package_json = JSON.parse(fs.readFileSync('./package.json')); + var opts = versioning.evaluate(package_json, gyp.opts); + s3_setup.detect(opts.hosted_path,config); + AWS.config.update(config); + var key_name = url.resolve(config.prefix,opts.package_name); + var s3 = new AWS.S3(); + var s3_opts = { Bucket: config.bucket, + Key: key_name + }; + s3.headObject(s3_opts, function(err, meta) { + if (err && err.code == 'NotFound') { + console.log('['+package_json.name+'] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key); + return callback(); + } else if(err) { + return callback(err); + } else { + log.info('unpublish', JSON.stringify(meta)); + s3.deleteObject(s3_opts, function(err, resp) { + if (err) return callback(err); + log.info(JSON.stringify(resp)); + console.log('['+package_json.name+'] Success: removed https://' + s3_opts.Bucket + '.s3.amazonaws.com/' + s3_opts.Key); + return callback(); + }); + } + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/abi_crosswalk.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/abi_crosswalk.json new file mode 100644 index 0000000..af014f5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/abi_crosswalk.json @@ -0,0 +1,366 @@ +{ + "0.8.0": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.1": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.2": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.3": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.4": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.5": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.6": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.7": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.8": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.9": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.10": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.11": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.12": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.13": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.14": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.15": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.16": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.17": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.18": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.19": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.20": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.21": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.22": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.23": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.24": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.25": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.26": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.27": { + "node_abi": 1, + "v8": "3.11" + }, + "0.8.28": { + "node_abi": 1, + "v8": "3.11" + }, + "0.10.0": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.1": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.2": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.3": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.4": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.5": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.6": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.7": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.8": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.9": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.10": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.11": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.12": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.13": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.14": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.15": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.16": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.17": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.18": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.19": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.20": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.21": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.22": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.23": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.24": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.25": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.26": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.27": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.28": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.29": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.30": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.31": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.32": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.33": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.34": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.35": { + "node_abi": 11, + "v8": "3.14" + }, + "0.10.36": { + "node_abi": 11, + "v8": "3.14" + }, + "0.11.0": { + "node_abi": 12, + "v8": "3.17" + }, + "0.11.1": { + "node_abi": 12, + "v8": "3.18" + }, + "0.11.2": { + "node_abi": 12, + "v8": "3.19" + }, + "0.11.3": { + "node_abi": 12, + "v8": "3.19" + }, + "0.11.4": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.5": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.6": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.7": { + "node_abi": 12, + "v8": "3.20" + }, + "0.11.8": { + "node_abi": 13, + "v8": "3.21" + }, + "0.11.9": { + "node_abi": 13, + "v8": "3.22" + }, + "0.11.10": { + "node_abi": 13, + "v8": "3.22" + }, + "0.11.11": { + "node_abi": 14, + "v8": "3.22" + }, + "0.11.12": { + "node_abi": 14, + "v8": "3.22" + }, + "0.11.13": { + "node_abi": 14, + "v8": "3.25" + }, + "0.11.14": { + "node_abi": 14, + "v8": "3.26" + }, + "0.11.15": { + "node_abi": 14, + "v8": "3.28" + }, + "0.11.16": { + "node_abi": 14, + "v8": "3.28" + }, + "0.12.0": { + "node_abi": 14, + "v8": "3.28" + }, + "1.0.0": { + "node_abi": 42, + "v8": "3.31" + }, + "1.0.1": { + "node_abi": 42, + "v8": "3.31" + }, + "1.0.2": { + "node_abi": 42, + "v8": "3.31" + }, + "1.0.3": { + "node_abi": 42, + "v8": "4.1" + }, + "1.0.4": { + "node_abi": 42, + "v8": "4.1" + }, + "1.1.0": { + "node_abi": 43, + "v8": "4.1" + }, + "1.2.0": { + "node_abi": 43, + "v8": "4.1" + } +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/compile.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/compile.js new file mode 100644 index 0000000..0dc460c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/compile.js @@ -0,0 +1,87 @@ +"use strict"; + +module.exports = exports; + +var fs = require('fs'); +var path = require('path'); +var win = process.platform == 'win32'; +var existsSync = fs.existsSync || path.existsSync; +var cp = require('child_process'); + +// try to build up the complete path to node-gyp +/* priority: + - node-gyp on ENV:npm_config_node_gyp (https://github.com/npm/npm/pull/4887) + - node-gyp on NODE_PATH + - node-gyp inside npm on NODE_PATH (ignore on iojs) + - node-gyp inside npm beside node exe +*/ +function which_node_gyp() { + var node_gyp_bin; + if (process.env.npm_config_node_gyp) { + try { + node_gyp_bin = process.env.npm_config_node_gyp; + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } + } catch (err) { } + } + try { + var node_gyp_main = require.resolve('node-gyp'); + node_gyp_bin = path.join(path.dirname( + path.dirname(node_gyp_main)), + 'bin/node-gyp.js'); + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } + } catch (err) { } + if (process.execPath.indexOf('iojs') === -1) { + try { + var npm_main = require.resolve('npm'); + node_gyp_bin = path.join(path.dirname( + path.dirname(npm_main)), + 'node_modules/node-gyp/bin/node-gyp.js'); + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } + } catch (err) { } + } + var npm_base = path.join(path.dirname( + path.dirname(process.execPath)), + 'lib/node_modules/npm/'); + node_gyp_bin = path.join(npm_base, 'node_modules/node-gyp/bin/node-gyp.js'); + if (existsSync(node_gyp_bin)) { + return node_gyp_bin; + } +} + +module.exports.run_gyp = function(args,opts,callback) { + var shell_cmd = ''; + var cmd_args = []; + if (opts.runtime && opts.runtime == 'node-webkit') { + shell_cmd = 'nw-gyp'; + if (win) shell_cmd += '.cmd'; + } else { + var node_gyp_path = which_node_gyp(); + if (node_gyp_path) { + shell_cmd = process.execPath; + cmd_args.push(node_gyp_path); + } else { + shell_cmd = 'node-gyp'; + if (win) shell_cmd += '.cmd'; + } + } + var final_args = cmd_args.concat(args); + var cmd = cp.spawn(shell_cmd, final_args, {cwd: undefined, env: process.env, stdio: [ 0, 1, 2]}); + cmd.on('error', function (err) { + if (err) { + return callback(new Error("Failed to execute '" + shell_cmd + ' ' + final_args.join(' ') + "' (" + err + ")")); + } + callback(null,opts); + }); + cmd.on('close', function (code) { + if (code && code !== 0) { + return callback(new Error("Failed to execute '" + shell_cmd + ' ' + final_args.join(' ') + "' (" + code + ")")); + } + callback(null,opts); + }); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/handle_gyp_opts.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/handle_gyp_opts.js new file mode 100644 index 0000000..39fe1a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/handle_gyp_opts.js @@ -0,0 +1,94 @@ +"use strict"; + +module.exports = exports = handle_gyp_opts; + +var fs = require('fs'); +var versioning = require('./versioning.js'); + +/* + +Here we gather node-pre-gyp generated options (from versioning) and pass them along to node-gyp. + +We massage the args and options slightly to account for differences in what commands mean between +node-pre-gyp and node-gyp (e.g. see the difference between "build" and "rebuild" below) + +Keep in mind: the values inside `argv` and `gyp.opts` below are different depending on whether +node-pre-gyp is called directory, or if it is called in a `run-script` phase of npm. + +We also try to preserve any command line options that might have been passed to npm or node-pre-gyp. +But this is fairly difficult without passing way to much through. For example `gyp.opts` contains all +the process.env and npm pushes a lot of variables into process.env which node-pre-gyp inherits. So we have +to be very selective about what we pass through. + +For example: + +`npm install --build-from-source` will give: + +argv == [ 'rebuild' ] +gyp.opts.argv == { remain: [ 'install' ], + cooked: [ 'install', '--fallback-to-build' ], + original: [ 'install', '--fallback-to-build' ] } + +`./bin/node-pre-gyp build` will give: + +argv == [] +gyp.opts.argv == { remain: [ 'build' ], + cooked: [ 'build' ], + original: [ '-C', 'test/app1', 'build' ] } + +*/ + +// select set of node-pre-gyp versioning info +// to share with node-gyp +var share_with_node_gyp = [ + 'module', + 'module_name', + 'module_path', +]; + +function handle_gyp_opts(gyp, argv, callback) { + + // Collect node-pre-gyp specific variables to pass to node-gyp + var node_pre_gyp_options = []; + // generate custom node-pre-gyp versioning info + var opts = versioning.evaluate(JSON.parse(fs.readFileSync('./package.json')), gyp.opts); + share_with_node_gyp.forEach(function(key) { + var val = opts[key]; + if (val) { + node_pre_gyp_options.push('--' + key + '=' + val); + } else { + return callback(new Error("Option " + key + " required but not found by node-pre-gyp")); + } + }); + + // Collect options that follow the special -- which disables nopt parsing + var unparsed_options = []; + var double_hyphen_found = false; + gyp.opts.argv.original.forEach(function(opt) { + if (double_hyphen_found) { + unparsed_options.push(opt); + } + if (opt == '--') { + double_hyphen_found = true; + } + }); + + // We try respect and pass through remaining command + // line options (like --foo=bar) to node-gyp + var cooked = gyp.opts.argv.cooked; + var node_gyp_options = []; + cooked.forEach(function(value) { + if (value.length > 2 && value.slice(0,2) == '--') { + var key = value.slice(2); + var val = cooked[cooked.indexOf(value)+1]; + if (val && val.indexOf('--') === -1) { // handle '--foo=bar' or ['--foo','bar'] + node_gyp_options.push('--' + key + '=' + val); + } else { // pass through --foo + node_gyp_options.push(value); + } + } + }); + + var result = {'opts':opts,'gyp':node_gyp_options,'pre':node_pre_gyp_options,'unparsed':unparsed_options}; + return callback(null,result); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/index.html b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/index.html new file mode 100644 index 0000000..244466c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/index.html @@ -0,0 +1,26 @@ + + + + +Node-webkit-based module test + + + +

Node-webkit-based module test

+ + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/package.json new file mode 100644 index 0000000..71d03f8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/nw-pre-gyp/package.json @@ -0,0 +1,9 @@ +{ +"main": "index.html", +"name": "nw-pre-gyp-module-test", +"description": "Node-webkit-based module test.", +"version": "0.0.1", +"window": { + "show": false +} +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/s3_setup.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/s3_setup.js new file mode 100644 index 0000000..5bc42e9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/s3_setup.js @@ -0,0 +1,27 @@ +"use strict"; + +module.exports = exports; + +var url = require('url'); + +var URI_REGEX="^(.*)\.(s3(?:-.*)?)\.amazonaws\.com$"; + +module.exports.detect = function(to,config) { + var uri = url.parse(to); + var hostname_matches = uri.hostname.match(URI_REGEX); + config.prefix = (!uri.pathname || uri.pathname == '/') ? '' : uri.pathname.replace('/',''); + if(!hostname_matches) { + return; + } + if (!config.bucket) { + config.bucket = hostname_matches[1]; + } + if (!config.region) { + var s3_domain = hostname_matches[2]; + if (s3_domain.slice(0,3) == 's3-' && + s3_domain.length >= 3) { + // it appears the region is explicit in the url + config.region = s3_domain.replace('s3-',''); + } + } +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/versioning.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/versioning.js new file mode 100644 index 0000000..292a4a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/lib/util/versioning.js @@ -0,0 +1,276 @@ +"use strict"; + +module.exports = exports; + +var path = require('path'); +var semver = require('semver'); +var url = require('url'); + +var abi_crosswalk; + +// This is used for unit testing to provide a fake +// ABI crosswalk that emulates one that is not updated +// for the current version +if (process.env.NODE_PRE_GYP_ABI_CROSSWALK) { + abi_crosswalk = require(process.env.NODE_PRE_GYP_ABI_CROSSWALK); +} else { + abi_crosswalk = require('./abi_crosswalk.json'); +} + +function get_node_webkit_abi(runtime, target_version) { + if (!runtime) { + throw new Error("get_node_webkit_abi requires valid runtime arg"); + } + if (typeof target_version === 'undefined') { + // erroneous CLI call + throw new Error("Empty target version is not supported if node-webkit is the target."); + } + return runtime + '-v' + target_version; +} +module.exports.get_node_webkit_abi = get_node_webkit_abi; + +function get_node_abi(runtime, versions) { + if (!runtime) { + throw new Error("get_node_abi requires valid runtime arg"); + } + if (!versions) { + throw new Error("get_node_abi requires valid process.versions object"); + } + var sem_ver = semver.parse(versions.node); + if (sem_ver.major === 0 && sem_ver.minor % 2) { // odd series + // https://github.com/mapbox/node-pre-gyp/issues/124 + return runtime+'-v'+versions.node; + } else { + // process.versions.modules added in >= v0.10.4 and v0.11.7 + // https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e + return versions.modules ? runtime+'-v' + (+versions.modules) : + 'v8-' + versions.v8.split('.').slice(0,2).join('.'); + } +} +module.exports.get_node_abi = get_node_abi; + +function get_runtime_abi(runtime, target_version) { + if (!runtime) { + throw new Error("get_runtime_abi requires valid runtime arg"); + } + if (runtime === 'node-webkit') { + return get_node_webkit_abi(runtime, target_version || process.versions['node-webkit']); + } else { + if (runtime != 'node') { + throw new Error("Unknown Runtime: '" + runtime + "'"); + } + if (!target_version) { + return get_node_abi(runtime,process.versions); + } else { + var cross_obj; + // abi_crosswalk generated with ./scripts/abi_crosswalk.js + if (abi_crosswalk[target_version]) { + cross_obj = abi_crosswalk[target_version]; + } else { + var target_parts = target_version.split('.').map(function(i) { return +i; }); + if (target_parts.length != 3) { // parse failed + throw new Error("Unknown target version: " + target_version); + } + /* + The below code tries to infer the last known ABI compatible version + that we have recorded in the abi_crosswalk.json when an exact match + is not possible. The reasons for this to exist are complicated: + + - We support passing --target to be able to allow developers to package binaries for versions of node + that are not the same one as they are running. This might also be used in combination with the + --target_arch or --target_platform flags to also package binaries for alternative platforms + - When --target is passed we can't therefore determine the ABI (process.versions.modules) from the node + version that is running in memory + - So, therefore node-pre-gyp keeps an "ABI crosswalk" (lib/util/abi_crosswalk.json) to be able to look + this info up for all versions + - But we cannot easily predict what the future ABI will be for released versions + - And node-pre-gyp needs to be a `bundledDependency` in apps that depend on it in order to work correctly + by being fully available at install time. + - So, the speed of node releases and the bundled nature of node-pre-gyp mean that a new node-pre-gyp release + need to happen for every node.js/io.js/node-webkit/nw.js/atom-shell/etc release that might come online if + you want the `--target` flag to keep working for the latest version + - Which is impractical ^^ + - Hence the below code guesses about future ABI to make the need to update node-pre-gyp less demanding. + + In practice then you can have a dependency of your app like `node-sqlite3` that bundles a `node-pre-gyp` that + only knows about node v0.10.33 in the `abi_crosswalk.json` but target node v0.10.34 (which is assumed to be + ABI compatible with v0.10.33). + + TODO: use semver module instead of custom version parsing + */ + var major = target_parts[0]; + var minor = target_parts[1]; + var patch = target_parts[2]; + // io.js: yeah if node.js ever releases 1.x this will break + // but that is unlikely to happen: https://github.com/iojs/io.js/pull/253#issuecomment-69432616 + if (major === 1) { + // look for last release that is the same major version + // e.g. we assume io.js 1.x is ABI compatible with >= 1.0.0 + while (true) { + if (minor > 0) --minor; + if (patch > 0) --patch; + var new_iojs_target = '' + major + '.' + minor + '.' + patch; + if (abi_crosswalk[new_iojs_target]) { + cross_obj = abi_crosswalk[new_iojs_target]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + new_iojs_target + ' as ABI compatible target'); + break; + } + if (minor === 0 && patch === 0) { + break; + } + } + } else if (major === 0) { // node.js + if (target_parts[1] % 2 === 0) { // for stable/even node.js series + // look for the last release that is the same minor release + // e.g. we assume node 0.10.x is ABI compatible with >= 0.10.0 + while (--patch > 0) { + var new_node_target = '' + major + '.' + minor + '.' + patch; + if (abi_crosswalk[new_node_target]) { + cross_obj = abi_crosswalk[new_node_target]; + console.log('Warning: node-pre-gyp could not find exact match for ' + target_version); + console.log('Warning: but node-pre-gyp successfully choose ' + new_node_target + ' as ABI compatible target'); + break; + } + } + } + } + } + if (!cross_obj) { + throw new Error("Unsupported target version: " + target_version); + } + // emulate process.versions + var versions_obj = { + node: target_version, + v8: cross_obj.v8+'.0', + // abi_crosswalk uses 1 for node versions lacking process.versions.modules + // process.versions.modules added in >= v0.10.4 and v0.11.7 + modules: cross_obj.node_abi > 1 ? cross_obj.node_abi : undefined + }; + return get_node_abi(runtime, versions_obj); + } + } +} +module.exports.get_runtime_abi = get_runtime_abi; + +var required_parameters = [ + 'module_name', + 'module_path', + 'host' +]; + +function validate_config(package_json) { + var msg = package_json.name + ' package.json is not node-pre-gyp ready:\n'; + var missing = []; + if (!package_json.main) { + missing.push('main'); + } + if (!package_json.version) { + missing.push('version'); + } + if (!package_json.name) { + missing.push('name'); + } + if (!package_json.binary) { + missing.push('binary'); + } + var o = package_json.binary; + required_parameters.forEach(function(p) { + if (missing.indexOf('binary') > -1) { + missing.pop('binary'); + } + if (!o || o[p] === undefined) { + missing.push('binary.' + p); + } + }); + if (missing.length >= 1) { + throw new Error(msg+"package.json must declare these properties: \n" + missing.join('\n')); + } + if (o) { + // enforce https over http + var protocol = url.parse(o.host).protocol; + if (protocol === 'http:') { + throw new Error("'host' protocol ("+protocol+") is invalid - only 'https:' is accepted"); + } + } +} + +module.exports.validate_config = validate_config; + +function eval_template(template,opts) { + Object.keys(opts).forEach(function(key) { + var pattern = '{'+key+'}'; + while (template.indexOf(pattern) > -1) { + template = template.replace(pattern,opts[key]); + } + }); + return template; +} + +// url.resolve needs single trailing slash +// to behave correctly, otherwise a double slash +// may end up in the url which breaks requests +// and a lacking slash may not lead to proper joining +function fix_slashes(pathname) { + if (pathname.slice(-1) != '/') { + return pathname + '/'; + } + return pathname; +} + +// remove double slashes +// note: path.normalize will not work because +// it will convert forward to back slashes +function drop_double_slashes(pathname) { + return pathname.replace(/\/\//g,'/'); +} + +var default_package_name = '{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz'; +var default_remote_path = ''; + +module.exports.evaluate = function(package_json,options) { + options = options || {}; + validate_config(package_json); + var v = package_json.version; + var module_version = semver.parse(v); + var runtime = options.runtime || (process.versions['node-webkit'] ? 'node-webkit' : 'node'); + var opts = { + name: package_json.name, + configuration: Boolean(options.debug) ? 'Debug' : 'Release', + debug: options.debug, + module_name: package_json.binary.module_name, + version: module_version.version, + prerelease: module_version.prerelease.length ? module_version.prerelease.join('.') : '', + build: module_version.build.length ? module_version.build.join('.') : '', + major: module_version.major, + minor: module_version.minor, + patch: module_version.patch, + runtime: runtime, + node_abi: get_runtime_abi(runtime,options.target), + target: options.target || '', + platform: options.target_platform || process.platform, + target_platform: options.target_platform || process.platform, + arch: options.target_arch || process.arch, + target_arch: options.target_arch || process.arch, + module_main: package_json.main, + toolset : options.toolset || '' // address https://github.com/mapbox/node-pre-gyp/issues/119 + }; + opts.host = fix_slashes(eval_template(package_json.binary.host,opts)); + opts.module_path = eval_template(package_json.binary.module_path,opts); + // now we resolve the module_path to ensure it is absolute so that binding.gyp variables work predictably + if (options.module_root) { + // resolve relative to known module root: works for pre-binding require + opts.module_path = path.join(options.module_root,opts.module_path); + } else { + // resolve relative to current working directory: works for node-pre-gyp commands + opts.module_path = path.resolve(opts.module_path); + } + opts.module = path.join(opts.module_path,opts.module_name + '.node'); + opts.remote_path = package_json.binary.remote_path ? drop_double_slashes(fix_slashes(eval_template(package_json.binary.remote_path,opts))) : default_remote_path; + var package_name = package_json.binary.package_name ? package_json.binary.package_name : default_package_name; + opts.package_name = eval_template(package_name,opts); + opts.staged_tarball = path.join('build/stage',opts.remote_path,opts.package_name); + opts.hosted_path = url.resolve(opts.host,opts.remote_path); + opts.hosted_tarball = url.resolve(opts.hosted_path,opts.package_name); + return opts; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/mkdirp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/mkdirp new file mode 120000 index 0000000..017896c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/mkdirp @@ -0,0 +1 @@ +../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/nopt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/nopt new file mode 120000 index 0000000..6b6566e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/nopt @@ -0,0 +1 @@ +../nopt/bin/nopt.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rc new file mode 120000 index 0000000..a3f6fc7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rc @@ -0,0 +1 @@ +../rc/index.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rimraf b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rimraf new file mode 120000 index 0000000..4cd49a4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/rimraf @@ -0,0 +1 @@ +../rimraf/bin.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/semver b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/.travis.yml new file mode 100644 index 0000000..74c57bf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.12" + - "iojs" +before_install: + - npm install -g npm@~1.4.6 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/LICENSE new file mode 100644 index 0000000..432d1ae --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/cmd.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/cmd.js new file mode 100755 index 0000000..d95de15 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/usage.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/usage.txt new file mode 100644 index 0000000..f952aa2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/bin/usage.txt @@ -0,0 +1,12 @@ +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/examples/pow.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/examples/pow.js new file mode 100644 index 0000000..e692421 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/examples/pow.js @@ -0,0 +1,6 @@ +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/index.js new file mode 100644 index 0000000..6ce241b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/index.js @@ -0,0 +1,98 @@ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/example/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/example/parse.js new file mode 100644 index 0000000..abff3e8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.dir(argv); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/index.js new file mode 100644 index 0000000..584f551 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/index.js @@ -0,0 +1,187 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {} }; + + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + }); + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function setArg (key, val) { + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + setArg(m[1], m[2]); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2)); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, args[i+1]); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + } + else { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + notFlags.forEach(function(key) { + argv._.push(key); + }); + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function longest (xs) { + return Math.max.apply(null, xs.map(function (x) { return x.length })); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/package.json new file mode 100644 index 0000000..09e9ec4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/package.json @@ -0,0 +1,67 @@ +{ + "name": "minimist", + "version": "0.0.8", + "description": "parse argument options", + "main": "index.js", + "devDependencies": { + "tape": "~1.0.4", + "tap": "~0.4.0" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "_id": "minimist@0.0.8", + "dist": { + "shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", + "tarball": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz" + }, + "_from": "minimist@0.0.8", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "substack", + "email": "mail@substack.net" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + } + ], + "directories": {}, + "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/readme.markdown b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/readme.markdown new file mode 100644 index 0000000..c256353 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/readme.markdown @@ -0,0 +1,73 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) + +[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.dir(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dash.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dash.js new file mode 100644 index 0000000..8b034b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dash.js @@ -0,0 +1,24 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/default_bool.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000..f0041ee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/default_bool.js @@ -0,0 +1,20 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dotted.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000..ef0ae34 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/dotted.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/long.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/long.js new file mode 100644 index 0000000..5d3a1e0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse.js new file mode 100644 index 0000000..8a90646 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse.js @@ -0,0 +1,318 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); + +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000..21851b0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: ['123'] }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/short.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/short.js new file mode 100644 index 0000000..d513a1c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/whitespace.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000..8a52a58 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/package.json new file mode 100644 index 0000000..70a6cba --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/package.json @@ -0,0 +1,60 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "0.5.1", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "main": "index.js", + "keywords": [ + "mkdir", + "directory" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "minimist": "0.0.8" + }, + "devDependencies": { + "tap": "1", + "mock-fs": "2 >=2.7.0" + }, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "license": "MIT", + "gitHead": "d4eff0f06093aed4f387e88e9fc301cb76beedc7", + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "homepage": "https://github.com/substack/node-mkdirp#readme", + "_id": "mkdirp@0.5.1", + "_shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", + "_from": "mkdirp@>=0.5.0 <0.6.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "2.0.0", + "_npmUser": { + "name": "substack", + "email": "substack@gmail.com" + }, + "dist": { + "shasum": "30057438eac6cf7f8c4767f38648d6697d75c903", + "tarball": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/readme.markdown b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/readme.markdown new file mode 100644 index 0000000..3cc1315 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/readme.markdown @@ -0,0 +1,100 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, opts, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a non-object, it will be treated as +the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and +`opts.fs.stat(path, cb)`. + +## mkdirp.sync(dir, opts) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `opts.mode`. If `opts` is a non-object, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. + +Returns the first directory that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and +`opts.fs.statSync(path)`. + +# usage + +This package also ships with a `mkdirp` command. + +``` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library, or + +``` +npm install -g mkdirp +``` + +to get the command. + +# license + +MIT diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/chmod.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/chmod.js new file mode 100644 index 0000000..6a404b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/chmod.js @@ -0,0 +1,41 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); +var _0744 = parseInt('0744', 8); + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +test('chmod-pre', function (t) { + var mode = _0744 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.equal(stat && stat.mode & _0777, mode, 'should be 0744'); + t.end(); + }); + }); +}); + +test('chmod', function (t) { + var mode = _0755 + mkdirp(file, mode, function (er) { + t.ifError(er, 'should not error'); + fs.stat(file, function (er, stat) { + t.ifError(er, 'should exist'); + t.ok(stat && stat.isDirectory(), 'should be directory'); + t.end(); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/clobber.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/clobber.js new file mode 100644 index 0000000..2433b9a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/clobber.js @@ -0,0 +1,38 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; +var _0755 = parseInt('0755', 8); + +var ps = [ '', 'tmp' ]; + +for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); +} + +var file = ps.join('/'); + +// a file in the way +var itw = ps.slice(0, 3).join('/'); + + +test('clobber-pre', function (t) { + console.error("about to write to "+itw) + fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); + + fs.stat(itw, function (er, stat) { + t.ifError(er) + t.ok(stat && stat.isFile(), 'should be file') + t.end() + }) +}) + +test('clobber', function (t) { + t.plan(2); + mkdirp(file, _0755, function (err) { + t.ok(err); + t.equal(err.code, 'ENOTDIR'); + t.end(); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/mkdirp.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/mkdirp.js new file mode 100644 index 0000000..eaa8921 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/mkdirp.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('woo', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs.js new file mode 100644 index 0000000..97186b6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs.js @@ -0,0 +1,29 @@ +var mkdirp = require('../'); +var path = require('path'); +var test = require('tap').test; +var mockfs = require('mock-fs'); +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('opts.fs', function (t) { + t.plan(5); + + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/beep/boop/' + [x,y,z].join('/'); + var xfs = mockfs.fs(); + + mkdirp(file, { fs: xfs, mode: _0755 }, function (err) { + t.ifError(err); + xfs.exists(file, function (ex) { + t.ok(ex, 'created file'); + xfs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs_sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs_sync.js new file mode 100644 index 0000000..6c370aa --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/opts_fs_sync.js @@ -0,0 +1,27 @@ +var mkdirp = require('../'); +var path = require('path'); +var test = require('tap').test; +var mockfs = require('mock-fs'); +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('opts.fs sync', function (t) { + t.plan(4); + + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/beep/boop/' + [x,y,z].join('/'); + var xfs = mockfs.fs(); + + mkdirp.sync(file, { fs: xfs, mode: _0755 }); + xfs.exists(file, function (ex) { + t.ok(ex, 'created file'); + xfs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm.js new file mode 100644 index 0000000..fbce44b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('async perm', function (t) { + t.plan(5); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); + + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); + +test('async root perm', function (t) { + mkdirp('/tmp', _0755, function (err) { + if (err) t.fail(err); + t.end(); + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm_sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm_sync.js new file mode 100644 index 0000000..398229f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/perm_sync.js @@ -0,0 +1,36 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('sync perm', function (t) { + t.plan(4); + var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; + + mkdirp.sync(file, _0755); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); + +test('sync root perm', function (t) { + t.plan(3); + + var file = '/tmp'; + mkdirp.sync(file, _0755); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/race.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/race.js new file mode 100644 index 0000000..b0b9e18 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/race.js @@ -0,0 +1,37 @@ +var mkdirp = require('../').mkdirp; +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('race', function (t) { + t.plan(10); + var ps = [ '', 'tmp' ]; + + for (var i = 0; i < 25; i++) { + var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + ps.push(dir); + } + var file = ps.join('/'); + + var res = 2; + mk(file); + + mk(file); + + function mk (file, cb) { + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }) + }); + } +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/rel.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/rel.js new file mode 100644 index 0000000..4ddb342 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/rel.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('rel', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var cwd = process.cwd(); + process.chdir('/tmp'); + + var file = [x,y,z].join('/'); + + mkdirp(file, _0755, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + process.chdir(cwd); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }) + }) + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return.js new file mode 100644 index 0000000..bce68e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return.js @@ -0,0 +1,25 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, '/tmp/' + x); + mkdirp(file, function (err, made) { + t.ifError(err); + t.equal(made, null); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return_sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return_sync.js new file mode 100644 index 0000000..7c222d3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/return_sync.js @@ -0,0 +1,24 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; + +test('return value', function (t) { + t.plan(2); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + // should return the first dir created. + // By this point, it would be profoundly surprising if /tmp didn't + // already exist, since every other test makes things in there. + // Note that this will throw on failure, which will fail the test. + var made = mkdirp.sync(file); + t.equal(made, '/tmp/' + x); + + // making the same file again should have no effect. + made = mkdirp.sync(file); + t.equal(made, null); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/root.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/root.js new file mode 100644 index 0000000..9e7d079 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/root.js @@ -0,0 +1,19 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var test = require('tap').test; +var _0755 = parseInt('0755', 8); + +test('root', function (t) { + // '/' on unix, 'c:/' on windows. + var file = path.resolve('/'); + + mkdirp(file, _0755, function (err) { + if (err) throw err + fs.stat(file, function (er, stat) { + if (er) throw er + t.ok(stat.isDirectory(), 'target is a directory'); + t.end(); + }) + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/sync.js new file mode 100644 index 0000000..8c8dc93 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('sync', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file, _0755); + } catch (err) { + t.fail(err); + return t.end(); + } + + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0755); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask.js new file mode 100644 index 0000000..2033c63 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask.js @@ -0,0 +1,28 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('implicit mode from umask', function (t) { + t.plan(5); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + mkdirp(file, function (err) { + t.ifError(err); + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, _0777 & (~process.umask())); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }) + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask_sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask_sync.js new file mode 100644 index 0000000..11a7614 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/mkdirp/test/umask_sync.js @@ -0,0 +1,32 @@ +var mkdirp = require('../'); +var path = require('path'); +var fs = require('fs'); +var exists = fs.exists || path.exists; +var test = require('tap').test; +var _0777 = parseInt('0777', 8); +var _0755 = parseInt('0755', 8); + +test('umask sync modes', function (t) { + t.plan(4); + var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); + + var file = '/tmp/' + [x,y,z].join('/'); + + try { + mkdirp.sync(file); + } catch (err) { + t.fail(err); + return t.end(); + } + + exists(file, function (ex) { + t.ok(ex, 'file created'); + fs.stat(file, function (err, stat) { + t.ifError(err); + t.equal(stat.mode & _0777, (_0777 & (~process.umask()))); + t.ok(stat.isDirectory(), 'target not a directory'); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/README.md new file mode 100644 index 0000000..5aba088 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/README.md @@ -0,0 +1,209 @@ +If you want to write an option parser, and have it be good, there are +two ways to do it. The Right Way, and the Wrong Way. + +The Wrong Way is to sit down and write an option parser. We've all done +that. + +The Right Way is to write some complex configurable program with so many +options that you go half-insane just trying to manage them all, and put +it off with duct-tape solutions until you see exactly to the core of the +problem, and finally snap and write an awesome option parser. + +If you want to write an option parser, don't write an option parser. +Write a package manager, or a source control system, or a service +restarter, or an operating system. You probably won't end up with a +good one of those, but if you don't give up, and you are relentless and +diligent enough in your procrastination, you may just end up with a very +nice option parser. + +## USAGE + + // my-program.js + var nopt = require("nopt") + , Stream = require("stream").Stream + , path = require("path") + , knownOpts = { "foo" : [String, null] + , "bar" : [Stream, Number] + , "baz" : path + , "bloo" : [ "big", "medium", "small" ] + , "flag" : Boolean + , "pick" : Boolean + , "many" : [String, Array] + } + , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] + , "b7" : ["--bar", "7"] + , "m" : ["--bloo", "medium"] + , "p" : ["--pick"] + , "f" : ["--flag"] + } + // everything is optional. + // knownOpts and shorthands default to {} + // arg list defaults to process.argv + // slice defaults to 2 + , parsed = nopt(knownOpts, shortHands, process.argv, 2) + console.log(parsed) + +This would give you support for any of the following: + +```bash +$ node my-program.js --foo "blerp" --no-flag +{ "foo" : "blerp", "flag" : false } + +$ node my-program.js ---bar 7 --foo "Mr. Hand" --flag +{ bar: 7, foo: "Mr. Hand", flag: true } + +$ node my-program.js --foo "blerp" -f -----p +{ foo: "blerp", flag: true, pick: true } + +$ node my-program.js -fp --foofoo +{ foo: "Mr. Foo", flag: true, pick: true } + +$ node my-program.js --foofoo -- -fp # -- stops the flag parsing. +{ foo: "Mr. Foo", argv: { remain: ["-fp"] } } + +$ node my-program.js --blatzk -fp # unknown opts are ok. +{ blatzk: true, flag: true, pick: true } + +$ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value +{ blatzk: 1000, flag: true, pick: true } + +$ node my-program.js --no-blatzk -fp # unless they start with "no-" +{ blatzk: false, flag: true, pick: true } + +$ node my-program.js --baz b/a/z # known paths are resolved. +{ baz: "/Users/isaacs/b/a/z" } + +# if Array is one of the types, then it can take many +# values, and will always be an array. The other types provided +# specify what types are allowed in the list. + +$ node my-program.js --many 1 --many null --many foo +{ many: ["1", "null", "foo"] } + +$ node my-program.js --many foo +{ many: ["foo"] } +``` + +Read the tests at the bottom of `lib/nopt.js` for more examples of +what this puppy can do. + +## Types + +The following types are supported, and defined on `nopt.typeDefs` + +* String: A normal string. No parsing is done. +* path: A file system path. Gets resolved against cwd if not absolute. +* url: A url. If it doesn't parse, it isn't accepted. +* Number: Must be numeric. +* Date: Must parse as a date. If it does, and `Date` is one of the options, + then it will return a Date object, not a string. +* Boolean: Must be either `true` or `false`. If an option is a boolean, + then it does not need a value, and its presence will imply `true` as + the value. To negate boolean flags, do `--no-whatever` or `--whatever + false` +* NaN: Means that the option is strictly not allowed. Any value will + fail. +* Stream: An object matching the "Stream" class in node. Valuable + for use when validating programmatically. (npm uses this to let you + supply any WriteStream on the `outfd` and `logfd` config options.) +* Array: If `Array` is specified as one of the types, then the value + will be parsed as a list of options. This means that multiple values + can be specified, and that the value will always be an array. + +If a type is an array of values not on this list, then those are +considered valid values. For instance, in the example above, the +`--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`, +and any other value will be rejected. + +When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be +interpreted as their JavaScript equivalents. + +You can also mix types and values, or multiple types, in a list. For +instance `{ blah: [Number, null] }` would allow a value to be set to +either a Number or null. When types are ordered, this implies a +preference, and the first type that can be used to properly interpret +the value will be used. + +To define a new type, add it to `nopt.typeDefs`. Each item in that +hash is an object with a `type` member and a `validate` method. The +`type` member is an object that matches what goes in the type list. The +`validate` method is a function that gets called with `validate(data, +key, val)`. Validate methods should assign `data[key]` to the valid +value of `val` if it can be handled properly, or return boolean +`false` if it cannot. + +You can also call `nopt.clean(data, types, typeDefs)` to clean up a +config object and remove its invalid properties. + +## Error Handling + +By default, nopt outputs a warning to standard error when invalid +options are found. You can change this behavior by assigning a method +to `nopt.invalidHandler`. This method will be called with +the offending `nopt.invalidHandler(key, val, types)`. + +If no `nopt.invalidHandler` is assigned, then it will console.error +its whining. If it is assigned to boolean `false` then the warning is +suppressed. + +## Abbreviations + +Yes, they are supported. If you define options like this: + +```javascript +{ "foolhardyelephants" : Boolean +, "pileofmonkeys" : Boolean } +``` + +Then this will work: + +```bash +node program.js --foolhar --pil +node program.js --no-f --pileofmon +# etc. +``` + +## Shorthands + +Shorthands are a hash of shorter option names to a snippet of args that +they expand to. + +If multiple one-character shorthands are all combined, and the +combination does not unambiguously match any other option or shorthand, +then they will be broken up into their constituent parts. For example: + +```json +{ "s" : ["--loglevel", "silent"] +, "g" : "--global" +, "f" : "--force" +, "p" : "--parseable" +, "l" : "--long" +} +``` + +```bash +npm ls -sgflp +# just like doing this: +npm ls --loglevel silent --global --force --long --parseable +``` + +## The Rest of the args + +The config object returned by nopt is given a special member called +`argv`, which is an object with the following fields: + +* `remain`: The remaining args after all the parsing has occurred. +* `original`: The args as they originally appeared. +* `cooked`: The args after flags and shorthands are expanded. + +## Slicing + +Node programs are called with more or less the exact argv as it appears +in C land, after the v8 and node-specific options have been plucked off. +As such, `argv[0]` is always `node` and `argv[1]` is always the +JavaScript program being run. + +That's usually not very useful to you. So they're sliced off by +default. If you want them, then you can pass in `0` as the last +argument, or any other number that you'd like to slice off the start of +the list. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/bin/nopt.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/bin/nopt.js new file mode 100755 index 0000000..3232d4c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/bin/nopt.js @@ -0,0 +1,54 @@ +#!/usr/bin/env node +var nopt = require("../lib/nopt") + , path = require("path") + , types = { num: Number + , bool: Boolean + , help: Boolean + , list: Array + , "num-list": [Number, Array] + , "str-list": [String, Array] + , "bool-list": [Boolean, Array] + , str: String + , clear: Boolean + , config: Boolean + , length: Number + , file: path + } + , shorthands = { s: [ "--str", "astring" ] + , b: [ "--bool" ] + , nb: [ "--no-bool" ] + , tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ] + , "?": ["--help"] + , h: ["--help"] + , H: ["--help"] + , n: [ "--num", "125" ] + , c: ["--config"] + , l: ["--length"] + , f: ["--file"] + } + , parsed = nopt( types + , shorthands + , process.argv + , 2 ) + +console.log("parsed", parsed) + +if (parsed.help) { + console.log("") + console.log("nopt cli tester") + console.log("") + console.log("types") + console.log(Object.keys(types).map(function M (t) { + var type = types[t] + if (Array.isArray(type)) { + return [t, type.map(function (type) { return type.name })] + } + return [t, type && type.name] + }).reduce(function (s, i) { + s[i[0]] = i[1] + return s + }, {})) + console.log("") + console.log("shorthands") + console.log(shorthands) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/examples/my-program.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/examples/my-program.js new file mode 100755 index 0000000..142447e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/examples/my-program.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node + +//process.env.DEBUG_NOPT = 1 + +// my-program.js +var nopt = require("../lib/nopt") + , Stream = require("stream").Stream + , path = require("path") + , knownOpts = { "foo" : [String, null] + , "bar" : [Stream, Number] + , "baz" : path + , "bloo" : [ "big", "medium", "small" ] + , "flag" : Boolean + , "pick" : Boolean + } + , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] + , "b7" : ["--bar", "7"] + , "m" : ["--bloo", "medium"] + , "p" : ["--pick"] + , "f" : ["--flag", "true"] + , "g" : ["--flag"] + , "s" : "--flag" + } + // everything is optional. + // knownOpts and shorthands default to {} + // arg list defaults to process.argv + // slice defaults to 2 + , parsed = nopt(knownOpts, shortHands, process.argv, 2) + +console.log("parsed =\n"+ require("util").inspect(parsed)) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/lib/nopt.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/lib/nopt.js new file mode 100644 index 0000000..5309a00 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/lib/nopt.js @@ -0,0 +1,414 @@ +// info about each config option. + +var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG + ? function () { console.error.apply(console, arguments) } + : function () {} + +var url = require("url") + , path = require("path") + , Stream = require("stream").Stream + , abbrev = require("abbrev") + +module.exports = exports = nopt +exports.clean = clean + +exports.typeDefs = + { String : { type: String, validate: validateString } + , Boolean : { type: Boolean, validate: validateBoolean } + , url : { type: url, validate: validateUrl } + , Number : { type: Number, validate: validateNumber } + , path : { type: path, validate: validatePath } + , Stream : { type: Stream, validate: validateStream } + , Date : { type: Date, validate: validateDate } + } + +function nopt (types, shorthands, args, slice) { + args = args || process.argv + types = types || {} + shorthands = shorthands || {} + if (typeof slice !== "number") slice = 2 + + debug(types, shorthands, args, slice) + + args = args.slice(slice) + var data = {} + , key + , remain = [] + , cooked = args + , original = args.slice(0) + + parse(args, data, remain, types, shorthands) + // now data is full + clean(data, types, exports.typeDefs) + data.argv = {remain:remain,cooked:cooked,original:original} + Object.defineProperty(data.argv, 'toString', { value: function () { + return this.original.map(JSON.stringify).join(" ") + }, enumerable: false }) + return data +} + +function clean (data, types, typeDefs) { + typeDefs = typeDefs || exports.typeDefs + var remove = {} + , typeDefault = [false, true, null, String, Array] + + Object.keys(data).forEach(function (k) { + if (k === "argv") return + var val = data[k] + , isArray = Array.isArray(val) + , type = types[k] + if (!isArray) val = [val] + if (!type) type = typeDefault + if (type === Array) type = typeDefault.concat(Array) + if (!Array.isArray(type)) type = [type] + + debug("val=%j", val) + debug("types=", type) + val = val.map(function (val) { + // if it's an unknown value, then parse false/true/null/numbers/dates + if (typeof val === "string") { + debug("string %j", val) + val = val.trim() + if ((val === "null" && ~type.indexOf(null)) + || (val === "true" && + (~type.indexOf(true) || ~type.indexOf(Boolean))) + || (val === "false" && + (~type.indexOf(false) || ~type.indexOf(Boolean)))) { + val = JSON.parse(val) + debug("jsonable %j", val) + } else if (~type.indexOf(Number) && !isNaN(val)) { + debug("convert to number", val) + val = +val + } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { + debug("convert to date", val) + val = new Date(val) + } + } + + if (!types.hasOwnProperty(k)) { + return val + } + + // allow `--no-blah` to set 'blah' to null if null is allowed + if (val === false && ~type.indexOf(null) && + !(~type.indexOf(false) || ~type.indexOf(Boolean))) { + val = null + } + + var d = {} + d[k] = val + debug("prevalidated val", d, val, types[k]) + if (!validate(d, k, val, types[k], typeDefs)) { + if (exports.invalidHandler) { + exports.invalidHandler(k, val, types[k], data) + } else if (exports.invalidHandler !== false) { + debug("invalid: "+k+"="+val, types[k]) + } + return remove + } + debug("validated val", d, val, types[k]) + return d[k] + }).filter(function (val) { return val !== remove }) + + if (!val.length) delete data[k] + else if (isArray) { + debug(isArray, data[k], val) + data[k] = val + } else data[k] = val[0] + + debug("k=%s val=%j", k, val, data[k]) + }) +} + +function validateString (data, k, val) { + data[k] = String(val) +} + +function validatePath (data, k, val) { + if (val === true) return false + if (val === null) return true + + val = String(val) + var homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\// + if (val.match(homePattern) && process.env.HOME) { + val = path.resolve(process.env.HOME, val.substr(2)) + } + data[k] = path.resolve(String(val)) + return true +} + +function validateNumber (data, k, val) { + debug("validate Number %j %j %j", k, val, isNaN(val)) + if (isNaN(val)) return false + data[k] = +val +} + +function validateDate (data, k, val) { + debug("validate Date %j %j %j", k, val, Date.parse(val)) + var s = Date.parse(val) + if (isNaN(s)) return false + data[k] = new Date(val) +} + +function validateBoolean (data, k, val) { + if (val instanceof Boolean) val = val.valueOf() + else if (typeof val === "string") { + if (!isNaN(val)) val = !!(+val) + else if (val === "null" || val === "false") val = false + else val = true + } else val = !!val + data[k] = val +} + +function validateUrl (data, k, val) { + val = url.parse(String(val)) + if (!val.host) return false + data[k] = val.href +} + +function validateStream (data, k, val) { + if (!(val instanceof Stream)) return false + data[k] = val +} + +function validate (data, k, val, type, typeDefs) { + // arrays are lists of types. + if (Array.isArray(type)) { + for (var i = 0, l = type.length; i < l; i ++) { + if (type[i] === Array) continue + if (validate(data, k, val, type[i], typeDefs)) return true + } + delete data[k] + return false + } + + // an array of anything? + if (type === Array) return true + + // NaN is poisonous. Means that something is not allowed. + if (type !== type) { + debug("Poison NaN", k, val, type) + delete data[k] + return false + } + + // explicit list of values + if (val === type) { + debug("Explicitly allowed %j", val) + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + return true + } + + // now go through the list of typeDefs, validate against each one. + var ok = false + , types = Object.keys(typeDefs) + for (var i = 0, l = types.length; i < l; i ++) { + debug("test type %j %j %j", k, val, types[i]) + var t = typeDefs[types[i]] + if (t && type === t.type) { + var d = {} + ok = false !== t.validate(d, k, val) + val = d[k] + if (ok) { + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + break + } + } + } + debug("OK? %j (%j %j %j)", ok, k, val, types[i]) + + if (!ok) delete data[k] + return ok +} + +function parse (args, data, remain, types, shorthands) { + debug("parse", args, data, remain) + + var key = null + , abbrevs = abbrev(Object.keys(types)) + , shortAbbr = abbrev(Object.keys(shorthands)) + + for (var i = 0; i < args.length; i ++) { + var arg = args[i] + debug("arg", arg) + + if (arg.match(/^-{2,}$/)) { + // done with keys. + // the rest are args. + remain.push.apply(remain, args.slice(i + 1)) + args[i] = "--" + break + } + var hadEq = false + if (arg.charAt(0) === "-" && arg.length > 1) { + if (arg.indexOf("=") !== -1) { + hadEq = true + var v = arg.split("=") + arg = v.shift() + v = v.join("=") + args.splice.apply(args, [i, 1].concat([arg, v])) + } + + // see if it's a shorthand + // if so, splice and back up to re-parse it. + var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) + debug("arg=%j shRes=%j", arg, shRes) + if (shRes) { + debug(arg, shRes) + args.splice.apply(args, [i, 1].concat(shRes)) + if (arg !== shRes[0]) { + i -- + continue + } + } + arg = arg.replace(/^-+/, "") + var no = null + while (arg.toLowerCase().indexOf("no-") === 0) { + no = !no + arg = arg.substr(3) + } + + if (abbrevs[arg]) arg = abbrevs[arg] + + var isArray = types[arg] === Array || + Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1 + + // allow unknown things to be arrays if specified multiple times. + if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) { + if (!Array.isArray(data[arg])) + data[arg] = [data[arg]] + isArray = true + } + + var val + , la = args[i + 1] + + var isBool = typeof no === 'boolean' || + types[arg] === Boolean || + Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 || + (typeof types[arg] === 'undefined' && !hadEq) || + (la === "false" && + (types[arg] === null || + Array.isArray(types[arg]) && ~types[arg].indexOf(null))) + + if (isBool) { + // just set and move along + val = !no + // however, also support --bool true or --bool false + if (la === "true" || la === "false") { + val = JSON.parse(la) + la = null + if (no) val = !val + i ++ + } + + // also support "foo":[Boolean, "bar"] and "--foo bar" + if (Array.isArray(types[arg]) && la) { + if (~types[arg].indexOf(la)) { + // an explicit type + val = la + i ++ + } else if ( la === "null" && ~types[arg].indexOf(null) ) { + // null allowed + val = null + i ++ + } else if ( !la.match(/^-{2,}[^-]/) && + !isNaN(la) && + ~types[arg].indexOf(Number) ) { + // number + val = +la + i ++ + } else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) { + // string + val = la + i ++ + } + } + + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + continue + } + + if (types[arg] === String && la === undefined) + la = "" + + if (la && la.match(/^-{2,}$/)) { + la = undefined + i -- + } + + val = la === undefined ? true : la + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + i ++ + continue + } + remain.push(arg) + } +} + +function resolveShort (arg, shorthands, shortAbbr, abbrevs) { + // handle single-char shorthands glommed together, like + // npm ls -glp, but only if there is one dash, and only if + // all of the chars are single-char shorthands, and it's + // not a match to some other abbrev. + arg = arg.replace(/^-+/, '') + + // if it's an exact known option, then don't go any further + if (abbrevs[arg] === arg) + return null + + // if it's an exact known shortopt, same deal + if (shorthands[arg]) { + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] + } + + // first check to see if this arg is a set of single-char shorthands + var singles = shorthands.___singles + if (!singles) { + singles = Object.keys(shorthands).filter(function (s) { + return s.length === 1 + }).reduce(function (l,r) { + l[r] = true + return l + }, {}) + shorthands.___singles = singles + debug('shorthand singles', singles) + } + + var chrs = arg.split("").filter(function (c) { + return singles[c] + }) + + if (chrs.join("") === arg) return chrs.map(function (c) { + return shorthands[c] + }).reduce(function (l, r) { + return l.concat(r) + }, []) + + + // if it's an arg abbrev, and not a literal shorthand, then prefer the arg + if (abbrevs[arg] && !shorthands[arg]) + return null + + // if it's an abbr for a shorthand, then use that + if (shortAbbr[arg]) + arg = shortAbbr[arg] + + // make it an array, if it's a list of words + if (shorthands[arg] && !Array.isArray(shorthands[arg])) + shorthands[arg] = shorthands[arg].split(/\s+/) + + return shorthands[arg] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.npmignore new file mode 100644 index 0000000..9d6cd2f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.npmignore @@ -0,0 +1,4 @@ +.nyc_output +nyc_output +node_modules +coverage diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.travis.yml new file mode 100644 index 0000000..991d04b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - 'iojs' diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/CONTRIBUTING.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/CONTRIBUTING.md new file mode 100644 index 0000000..2f30261 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/CONTRIBUTING.md @@ -0,0 +1,3 @@ + To get started, sign the + Contributor License Agreement. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/README.md new file mode 100644 index 0000000..99746fe --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/README.md @@ -0,0 +1,23 @@ +# abbrev-js + +Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev). + +Usage: + + var abbrev = require("abbrev"); + abbrev("foo", "fool", "folding", "flop"); + + // returns: + { fl: 'flop' + , flo: 'flop' + , flop: 'flop' + , fol: 'folding' + , fold: 'folding' + , foldi: 'folding' + , foldin: 'folding' + , folding: 'folding' + , foo: 'foo' + , fool: 'fool' + } + +This is handy for command-line scripts, or other cases where you want to be able to accept shorthands. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/abbrev.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/abbrev.js new file mode 100644 index 0000000..69cfeac --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/abbrev.js @@ -0,0 +1,62 @@ + +module.exports = exports = abbrev.abbrev = abbrev + +abbrev.monkeyPatch = monkeyPatch + +function monkeyPatch () { + Object.defineProperty(Array.prototype, 'abbrev', { + value: function () { return abbrev(this) }, + enumerable: false, configurable: true, writable: true + }) + + Object.defineProperty(Object.prototype, 'abbrev', { + value: function () { return abbrev(Object.keys(this)) }, + enumerable: false, configurable: true, writable: true + }) +} + +function abbrev (list) { + if (arguments.length !== 1 || !Array.isArray(list)) { + list = Array.prototype.slice.call(arguments, 0) + } + for (var i = 0, l = list.length, args = [] ; i < l ; i ++) { + args[i] = typeof list[i] === "string" ? list[i] : String(list[i]) + } + + // sort them lexicographically, so that they're next to their nearest kin + args = args.sort(lexSort) + + // walk through each, seeing how much it has in common with the next and previous + var abbrevs = {} + , prev = "" + for (var i = 0, l = args.length ; i < l ; i ++) { + var current = args[i] + , next = args[i + 1] || "" + , nextMatches = true + , prevMatches = true + if (current === next) continue + for (var j = 0, cl = current.length ; j < cl ; j ++) { + var curChar = current.charAt(j) + nextMatches = nextMatches && curChar === next.charAt(j) + prevMatches = prevMatches && curChar === prev.charAt(j) + if (!nextMatches && !prevMatches) { + j ++ + break + } + } + prev = current + if (j === cl) { + abbrevs[current] = current + continue + } + for (var a = current.substr(0, j) ; j <= cl ; j ++) { + abbrevs[a] = current + a += current.charAt(j) + } + } + return abbrevs +} + +function lexSort (a, b) { + return a === b ? 0 : a > b ? 1 : -1 +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/package.json new file mode 100644 index 0000000..ca11350 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/package.json @@ -0,0 +1,47 @@ +{ + "name": "abbrev", + "version": "1.0.7", + "description": "Like ruby's abbrev module, but in js", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "main": "abbrev.js", + "scripts": { + "test": "tap test.js --cov" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/isaacs/abbrev-js.git" + }, + "license": "ISC", + "devDependencies": { + "tap": "^1.2.0" + }, + "gitHead": "821d09ce7da33627f91bbd8ed631497ed6f760c2", + "bugs": { + "url": "https://github.com/isaacs/abbrev-js/issues" + }, + "homepage": "https://github.com/isaacs/abbrev-js#readme", + "_id": "abbrev@1.0.7", + "_shasum": "5b6035b2ee9d4fb5cf859f08a9be81b208491843", + "_from": "abbrev@>=1.0.0 <2.0.0", + "_npmVersion": "2.10.1", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "5b6035b2ee9d4fb5cf859f08a9be81b208491843", + "tarball": "http://registry.npmjs.org/abbrev/-/abbrev-1.0.7.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.7.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/test.js new file mode 100644 index 0000000..eb30e42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/node_modules/abbrev/test.js @@ -0,0 +1,47 @@ +var abbrev = require('./abbrev.js') +var assert = require("assert") +var util = require("util") + +console.log("TAP version 13") +var count = 0 + +function test (list, expect) { + count++ + var actual = abbrev(list) + assert.deepEqual(actual, expect, + "abbrev("+util.inspect(list)+") === " + util.inspect(expect) + "\n"+ + "actual: "+util.inspect(actual)) + actual = abbrev.apply(exports, list) + assert.deepEqual(abbrev.apply(exports, list), expect, + "abbrev("+list.map(JSON.stringify).join(",")+") === " + util.inspect(expect) + "\n"+ + "actual: "+util.inspect(actual)) + console.log('ok - ' + list.join(' ')) +} + +test([ "ruby", "ruby", "rules", "rules", "rules" ], +{ rub: 'ruby' +, ruby: 'ruby' +, rul: 'rules' +, rule: 'rules' +, rules: 'rules' +}) +test(["fool", "foom", "pool", "pope"], +{ fool: 'fool' +, foom: 'foom' +, poo: 'pool' +, pool: 'pool' +, pop: 'pope' +, pope: 'pope' +}) +test(["a", "ab", "abc", "abcd", "abcde", "acde"], +{ a: 'a' +, ab: 'ab' +, abc: 'abc' +, abcd: 'abcd' +, abcde: 'abcde' +, ac: 'acde' +, acd: 'acde' +, acde: 'acde' +}) + +console.log("1..%d", count) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/package.json new file mode 100644 index 0000000..719da0c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/package.json @@ -0,0 +1,55 @@ +{ + "name": "nopt", + "version": "3.0.2", + "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "main": "lib/nopt.js", + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/isaacs/nopt.git" + }, + "bin": { + "nopt": "./bin/nopt.js" + }, + "license": "ISC", + "dependencies": { + "abbrev": "1" + }, + "devDependencies": { + "tap": "~0.4.8" + }, + "gitHead": "a0ff8dcbb29ae9da68769c9f782bd4d70746b02d", + "bugs": { + "url": "https://github.com/isaacs/nopt/issues" + }, + "homepage": "https://github.com/isaacs/nopt#readme", + "_id": "nopt@3.0.2", + "_shasum": "a82a87f9d8c3df140fe78fb29657a7a774403b5e", + "_from": "nopt@>=3.0.1 <3.1.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "a82a87f9d8c3df140fe78fb29657a7a774403b5e", + "tarball": "http://registry.npmjs.org/nopt/-/nopt-3.0.2.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/test/basic.js new file mode 100644 index 0000000..2f9088c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/nopt/test/basic.js @@ -0,0 +1,251 @@ +var nopt = require("../") + , test = require('tap').test + + +test("passing a string results in a string", function (t) { + var parsed = nopt({ key: String }, {}, ["--key", "myvalue"], 0) + t.same(parsed.key, "myvalue") + t.end() +}) + +// https://github.com/npm/nopt/issues/31 +test("Empty String results in empty string, not true", function (t) { + var parsed = nopt({ empty: String }, {}, ["--empty"], 0) + t.same(parsed.empty, "") + t.end() +}) + +test("~ path is resolved to $HOME", function (t) { + var path = require("path") + if (!process.env.HOME) process.env.HOME = "/tmp" + var parsed = nopt({key: path}, {}, ["--key=~/val"], 0) + t.same(parsed.key, path.resolve(process.env.HOME, "val")) + t.end() +}) + +// https://github.com/npm/nopt/issues/24 +test("Unknown options are not parsed as numbers", function (t) { + var parsed = nopt({"parse-me": Number}, null, ['--leave-as-is=1.20', '--parse-me=1.20'], 0) + t.equal(parsed['leave-as-is'], '1.20') + t.equal(parsed['parse-me'], 1.2) + t.end() +}); + +test("other tests", function (t) { + + var util = require("util") + , Stream = require("stream") + , path = require("path") + , url = require("url") + + , shorthands = + { s : ["--loglevel", "silent"] + , d : ["--loglevel", "info"] + , dd : ["--loglevel", "verbose"] + , ddd : ["--loglevel", "silly"] + , noreg : ["--no-registry"] + , reg : ["--registry"] + , "no-reg" : ["--no-registry"] + , silent : ["--loglevel", "silent"] + , verbose : ["--loglevel", "verbose"] + , h : ["--usage"] + , H : ["--usage"] + , "?" : ["--usage"] + , help : ["--usage"] + , v : ["--version"] + , f : ["--force"] + , desc : ["--description"] + , "no-desc" : ["--no-description"] + , "local" : ["--no-global"] + , l : ["--long"] + , p : ["--parseable"] + , porcelain : ["--parseable"] + , g : ["--global"] + } + + , types = + { aoa: Array + , nullstream: [null, Stream] + , date: Date + , str: String + , browser : String + , cache : path + , color : ["always", Boolean] + , depth : Number + , description : Boolean + , dev : Boolean + , editor : path + , force : Boolean + , global : Boolean + , globalconfig : path + , group : [String, Number] + , gzipbin : String + , logfd : [Number, Stream] + , loglevel : ["silent","win","error","warn","info","verbose","silly"] + , long : Boolean + , "node-version" : [false, String] + , npaturl : url + , npat : Boolean + , "onload-script" : [false, String] + , outfd : [Number, Stream] + , parseable : Boolean + , pre: Boolean + , prefix: path + , proxy : url + , "rebuild-bundle" : Boolean + , registry : url + , searchopts : String + , searchexclude: [null, String] + , shell : path + , t: [Array, String] + , tag : String + , tar : String + , tmp : path + , "unsafe-perm" : Boolean + , usage : Boolean + , user : String + , username : String + , userconfig : path + , version : Boolean + , viewer: path + , _exit : Boolean + , path: path + } + + ; [["-v", {version:true}, []] + ,["---v", {version:true}, []] + ,["ls -s --no-reg connect -d", + {loglevel:"info",registry:null},["ls","connect"]] + ,["ls ---s foo",{loglevel:"silent"},["ls","foo"]] + ,["ls --registry blargle", {}, ["ls"]] + ,["--no-registry", {registry:null}, []] + ,["--no-color true", {color:false}, []] + ,["--no-color false", {color:true}, []] + ,["--no-color", {color:false}, []] + ,["--color false", {color:false}, []] + ,["--color --logfd 7", {logfd:7,color:true}, []] + ,["--color=true", {color:true}, []] + ,["--logfd=10", {logfd:10}, []] + ,["--tmp=/tmp -tar=gtar",{tmp:"/tmp",tar:"gtar"},[]] + ,["--tmp=tmp -tar=gtar", + {tmp:path.resolve(process.cwd(), "tmp"),tar:"gtar"},[]] + ,["--logfd x", {}, []] + ,["a -true -- -no-false", {true:true},["a","-no-false"]] + ,["a -no-false", {false:false},["a"]] + ,["a -no-no-true", {true:true}, ["a"]] + ,["a -no-no-no-false", {false:false}, ["a"]] + ,["---NO-no-No-no-no-no-nO-no-no"+ + "-No-no-no-no-no-no-no-no-no"+ + "-no-no-no-no-NO-NO-no-no-no-no-no-no"+ + "-no-body-can-do-the-boogaloo-like-I-do" + ,{"body-can-do-the-boogaloo-like-I-do":false}, []] + ,["we are -no-strangers-to-love "+ + "--you-know=the-rules --and=so-do-i "+ + "---im-thinking-of=a-full-commitment "+ + "--no-you-would-get-this-from-any-other-guy "+ + "--no-gonna-give-you-up "+ + "-no-gonna-let-you-down=true "+ + "--no-no-gonna-run-around false "+ + "--desert-you=false "+ + "--make-you-cry false "+ + "--no-tell-a-lie "+ + "--no-no-and-hurt-you false" + ,{"strangers-to-love":false + ,"you-know":"the-rules" + ,"and":"so-do-i" + ,"you-would-get-this-from-any-other-guy":false + ,"gonna-give-you-up":false + ,"gonna-let-you-down":false + ,"gonna-run-around":false + ,"desert-you":false + ,"make-you-cry":false + ,"tell-a-lie":false + ,"and-hurt-you":false + },["we", "are"]] + ,["-t one -t two -t three" + ,{t: ["one", "two", "three"]} + ,[]] + ,["-t one -t null -t three four five null" + ,{t: ["one", "null", "three"]} + ,["four", "five", "null"]] + ,["-t foo" + ,{t:["foo"]} + ,[]] + ,["--no-t" + ,{t:["false"]} + ,[]] + ,["-no-no-t" + ,{t:["true"]} + ,[]] + ,["-aoa one -aoa null -aoa 100" + ,{aoa:["one", null, '100']} + ,[]] + ,["-str 100" + ,{str:"100"} + ,[]] + ,["--color always" + ,{color:"always"} + ,[]] + ,["--no-nullstream" + ,{nullstream:null} + ,[]] + ,["--nullstream false" + ,{nullstream:null} + ,[]] + ,["--notadate=2011-01-25" + ,{notadate: "2011-01-25"} + ,[]] + ,["--date 2011-01-25" + ,{date: new Date("2011-01-25")} + ,[]] + ,["-cl 1" + ,{config: true, length: 1} + ,[] + ,{config: Boolean, length: Number, clear: Boolean} + ,{c: "--config", l: "--length"}] + ,["--acount bla" + ,{"acount":true} + ,["bla"] + ,{account: Boolean, credentials: Boolean, options: String} + ,{a:"--account", c:"--credentials",o:"--options"}] + ,["--clear" + ,{clear:true} + ,[] + ,{clear:Boolean,con:Boolean,len:Boolean,exp:Boolean,add:Boolean,rep:Boolean} + ,{c:"--con",l:"--len",e:"--exp",a:"--add",r:"--rep"}] + ,["--file -" + ,{"file":"-"} + ,[] + ,{file:String} + ,{}] + ,["--file -" + ,{"file":true} + ,["-"] + ,{file:Boolean} + ,{}] + ,["--path" + ,{"path":null} + ,[]] + ,["--path ." + ,{"path":process.cwd()} + ,[]] + ].forEach(function (test) { + var argv = test[0].split(/\s+/) + , opts = test[1] + , rem = test[2] + , actual = nopt(test[3] || types, test[4] || shorthands, argv, 0) + , parsed = actual.argv + delete actual.argv + for (var i in opts) { + var e = JSON.stringify(opts[i]) + , a = JSON.stringify(actual[i] === undefined ? null : actual[i]) + if (e && typeof e === "object") { + t.deepEqual(e, a) + } else { + t.equal(e, a) + } + } + t.deepEqual(rem, parsed.remain) + }) + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/.npmrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/.npmrc new file mode 100644 index 0000000..ca0bc48 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/.npmrc @@ -0,0 +1,2 @@ +save-prefix = ~ +proprietary-attribs = false diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/README.md new file mode 100644 index 0000000..a57cf42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/README.md @@ -0,0 +1,195 @@ +# npmlog + +The logger util that npm uses. + +This logger is very basic. It does the logging for npm. It supports +custom levels and colored output. + +By default, logs are written to stderr. If you want to send log messages +to outputs other than streams, then you can change the `log.stream` +member, or you can just listen to the events that it emits, and do +whatever you want with them. + +# Basic Usage + +``` +var log = require('npmlog') + +// additional stuff ---------------------------+ +// message ----------+ | +// prefix ----+ | | +// level -+ | | | +// v v v v + log.info('fyi', 'I have a kitty cat: %j', myKittyCat) +``` + +## log.level + +* {String} + +The level to display logs at. Any logs at or above this level will be +displayed. The special level `silent` will prevent anything from being +displayed ever. + +## log.record + +* {Array} + +An array of all the log messages that have been entered. + +## log.maxRecordSize + +* {Number} + +The maximum number of records to keep. If log.record gets bigger than +10% over this value, then it is sliced down to 90% of this value. + +The reason for the 10% window is so that it doesn't have to resize a +large array on every log entry. + +## log.prefixStyle + +* {Object} + +A style object that specifies how prefixes are styled. (See below) + +## log.headingStyle + +* {Object} + +A style object that specifies how the heading is styled. (See below) + +## log.heading + +* {String} Default: "" + +If set, a heading that is printed at the start of every line. + +## log.stream + +* {Stream} Default: `process.stderr` + +The stream where output is written. + +## log.enableColor() + +Force colors to be used on all messages, regardless of the output +stream. + +## log.disableColor() + +Disable colors on all messages. + +## log.enableProgress() + +Enable the display of log activity spinner and progress bar + +## log.disableProgress() + +Disable the display of a progress bar + +## log.enableUnicode() + +Force the unicode theme to be used for the progress bar. + +## log.disableUnicode() + +Disable the use of unicode in the progress bar. + +## log.setGaugeTemplate(template) + +Overrides the default gauge template. + +## log.pause() + +Stop emitting messages to the stream, but do not drop them. + +## log.resume() + +Emit all buffered messages that were written while paused. + +## log.log(level, prefix, message, ...) + +* `level` {String} The level to emit the message at +* `prefix` {String} A string prefix. Set to "" to skip. +* `message...` Arguments to `util.format` + +Emit a log message at the specified level. + +## log\[level](prefix, message, ...) + +For example, + +* log.silly(prefix, message, ...) +* log.verbose(prefix, message, ...) +* log.info(prefix, message, ...) +* log.http(prefix, message, ...) +* log.warn(prefix, message, ...) +* log.error(prefix, message, ...) + +Like `log.log(level, prefix, message, ...)`. In this way, each level is +given a shorthand, so you can do `log.info(prefix, message)`. + +## log.addLevel(level, n, style, disp) + +* `level` {String} Level indicator +* `n` {Number} The numeric level +* `style` {Object} Object with fg, bg, inverse, etc. +* `disp` {String} Optional replacement for `level` in the output. + +Sets up a new level with a shorthand function and so forth. + +Note that if the number is `Infinity`, then setting the level to that +will cause all log messages to be suppressed. If the number is +`-Infinity`, then the only way to show it is to enable all log messages. + +## log.newItem(name, todo, weight) + +* `name` {String} Optional; progress item name. +* `todo` {Number} Optional; total amount of work to be done. Default 0. +* `weight` {Number} Optional; the weight of this item relative to others. Default 1. + +This adds a new `are-we-there-yet` item tracker to the progress tracker. The +object returned has the `log[level]` methods but is otherwise an +`are-we-there-yet` `Tracker` object. + +## log.newStream(name, todo, weight) + +This adds a new `are-we-there-yet` stream tracker to the progress tracker. The +object returned has the `log[level]` methods but is otherwise an +`are-we-there-yet` `TrackerStream` object. + +## log.newGroup(name, weight) + +This adds a new `are-we-there-yet` tracker group to the progress tracker. The +object returned has the `log[level]` methods but is otherwise an +`are-we-there-yet` `TrackerGroup` object. + +# Events + +Events are all emitted with the message object. + +* `log` Emitted for all messages +* `log.` Emitted for all messages with the `` level. +* `` Messages with prefixes also emit their prefix as an event. + +# Style Objects + +Style objects can have the following fields: + +* `fg` {String} Color for the foreground text +* `bg` {String} Color for the background +* `bold`, `inverse`, `underline` {Boolean} Set the associated property +* `bell` {Boolean} Make a noise (This is pretty annoying, probably.) + +# Message Objects + +Every log event is emitted with a message object, and the `log.record` +list contains all of them that have been created. They have the +following fields: + +* `id` {Number} +* `level` {String} +* `prefix` {String} +* `message` {String} Result of `util.format()` +* `messageRaw` {Array} Arguments to `util.format()` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/example.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/example.js new file mode 100644 index 0000000..c009fb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/example.js @@ -0,0 +1,39 @@ +var log = require('./log.js') + +log.heading = 'npm' + +console.error('log.level=silly') +log.level = 'silly' +log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) +log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) +log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) +log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) +log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) +log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) +log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) + +console.error('log.level=silent') +log.level = 'silent' +log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) +log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) +log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) +log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) +log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) +log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) +log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) + +console.error('log.level=info') +log.level = 'info' +log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) +log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) +log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) +log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) +log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) +log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) +log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) +log.error('404', 'This is a longer\n'+ + 'message, with some details\n'+ + 'and maybe a stack.\n'+ + new Error('a 404 error').stack) +log.addLevel('noise', 10000, {beep: true}) +log.noise(false, 'LOUD NOISES') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/log.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/log.js new file mode 100644 index 0000000..8bf6422 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/log.js @@ -0,0 +1,247 @@ +'use strict' +var Progress = require('are-we-there-yet') +var Gauge = require('gauge') +var EE = require('events').EventEmitter +var log = exports = module.exports = new EE +var util = require('util') + +var ansi = require('ansi') +log.cursor = ansi(process.stderr) +log.stream = process.stderr + +// by default, let ansi decide based on tty-ness. +var colorEnabled = undefined +log.enableColor = function () { + colorEnabled = true + this.cursor.enabled = true +} +log.disableColor = function () { + colorEnabled = false + this.cursor.enabled = false +} + +// default level +log.level = 'info' + +log.gauge = new Gauge(log.cursor) +log.tracker = new Progress.TrackerGroup() + +// no progress bars unless asked +log.progressEnabled = false + +var gaugeTheme = undefined + +log.enableUnicode = function () { + gaugeTheme = Gauge.unicode + log.gauge.setTheme(gaugeTheme) +} + +log.disableUnicode = function () { + gaugeTheme = Gauge.ascii + log.gauge.setTheme(gaugeTheme) +} + +var gaugeTemplate = undefined +log.setGaugeTemplate = function (template) { + gaugeTemplate = template + log.gauge.setTemplate(gaugeTemplate) +} + +log.enableProgress = function () { + if (this.progressEnabled) return + this.progressEnabled = true + if (this._pause) return + this.tracker.on('change', this.showProgress) + this.gauge.enable() + this.showProgress() +} + +log.disableProgress = function () { + if (!this.progressEnabled) return + this.clearProgress() + this.progressEnabled = false + this.tracker.removeListener('change', this.showProgress) + this.gauge.disable() +} + +var trackerConstructors = ['newGroup', 'newItem', 'newStream'] + +var mixinLog = function (tracker) { + // mixin the public methods from log into the tracker + // (except: conflicts and one's we handle specially) + Object.keys(log).forEach(function (P) { + if (P[0] === '_') return + if (trackerConstructors.filter(function (C) { return C === P }).length) return + if (tracker[P]) return + if (typeof log[P] !== 'function') return + var func = log[P] + tracker[P] = function () { + return func.apply(log, arguments) + } + }) + // if the new tracker is a group, make sure any subtrackers get + // mixed in too + if (tracker instanceof Progress.TrackerGroup) { + trackerConstructors.forEach(function (C) { + var func = tracker[C] + tracker[C] = function () { return mixinLog(func.apply(tracker, arguments)) } + }) + } + return tracker +} + +// Add tracker constructors to the top level log object +trackerConstructors.forEach(function (C) { + log[C] = function () { return mixinLog(this.tracker[C].apply(this.tracker, arguments)) } +}) + +log.clearProgress = function () { + if (!this.progressEnabled) return + this.gauge.hide() +} + +log.showProgress = function (name) { + if (!this.progressEnabled) return + this.gauge.show(name, this.tracker.completed()) +}.bind(log) // bind for use in tracker's on-change listener + +// temporarily stop emitting, but don't drop +log.pause = function () { + this._paused = true +} + +log.resume = function () { + if (!this._paused) return + this._paused = false + + var b = this._buffer + this._buffer = [] + b.forEach(function (m) { + this.emitLog(m) + }, this) + if (this.progressEnabled) this.enableProgress() +} + +log._buffer = [] + +var id = 0 +log.record = [] +log.maxRecordSize = 10000 +log.log = function (lvl, prefix, message) { + var l = this.levels[lvl] + if (l === undefined) { + return this.emit('error', new Error(util.format( + 'Undefined log level: %j', lvl))) + } + + var a = new Array(arguments.length - 2) + var stack = null + for (var i = 2; i < arguments.length; i ++) { + var arg = a[i-2] = arguments[i] + + // resolve stack traces to a plain string. + if (typeof arg === 'object' && arg && + (arg instanceof Error) && arg.stack) { + arg.stack = stack = arg.stack + '' + } + } + if (stack) a.unshift(stack + '\n') + message = util.format.apply(util, a) + + var m = { id: id++, + level: lvl, + prefix: String(prefix || ''), + message: message, + messageRaw: a } + + this.emit('log', m) + this.emit('log.' + lvl, m) + if (m.prefix) this.emit(m.prefix, m) + + this.record.push(m) + var mrs = this.maxRecordSize + var n = this.record.length - mrs + if (n > mrs / 10) { + var newSize = Math.floor(mrs * 0.9) + this.record = this.record.slice(-1 * newSize) + } + + this.emitLog(m) +}.bind(log) + +log.emitLog = function (m) { + if (this._paused) { + this._buffer.push(m) + return + } + if (this.progressEnabled) this.gauge.pulse(m.prefix) + var l = this.levels[m.level] + if (l === undefined) return + if (l < this.levels[this.level]) return + if (l > 0 && !isFinite(l)) return + + var style = log.style[m.level] + var disp = log.disp[m.level] || m.level + this.clearProgress() + m.message.split(/\r?\n/).forEach(function (line) { + if (this.heading) { + this.write(this.heading, this.headingStyle) + this.write(' ') + } + this.write(disp, log.style[m.level]) + var p = m.prefix || '' + if (p) this.write(' ') + this.write(p, this.prefixStyle) + this.write(' ' + line + '\n') + }, this) + this.showProgress() +} + +log.write = function (msg, style) { + if (!this.cursor) return + if (this.stream !== this.cursor.stream) { + this.cursor = ansi(this.stream, { enabled: colorEnabled }) + var options = {} + if (gaugeTheme != null) options.theme = gaugeTheme + if (gaugeTemplate != null) options.template = gaugeTemplate + this.gauge = new Gauge(options, this.cursor) + } + + style = style || {} + if (style.fg) this.cursor.fg[style.fg]() + if (style.bg) this.cursor.bg[style.bg]() + if (style.bold) this.cursor.bold() + if (style.underline) this.cursor.underline() + if (style.inverse) this.cursor.inverse() + if (style.beep) this.cursor.beep() + this.cursor.write(msg).reset() +} + +log.addLevel = function (lvl, n, style, disp) { + if (!disp) disp = lvl + this.levels[lvl] = n + this.style[lvl] = style + if (!this[lvl]) this[lvl] = function () { + var a = new Array(arguments.length + 1) + a[0] = lvl + for (var i = 0; i < arguments.length; i ++) { + a[i + 1] = arguments[i] + } + return this.log.apply(this, a) + }.bind(this) + this.disp[lvl] = disp +} + +log.prefixStyle = { fg: 'magenta' } +log.headingStyle = { fg: 'white', bg: 'black' } + +log.style = {} +log.levels = {} +log.disp = {} +log.addLevel('silly', -Infinity, { inverse: true }, 'sill') +log.addLevel('verbose', 1000, { fg: 'blue', bg: 'black' }, 'verb') +log.addLevel('info', 2000, { fg: 'green' }) +log.addLevel('http', 3000, { fg: 'green', bg: 'black' }) +log.addLevel('warn', 4000, { fg: 'black', bg: 'yellow' }, 'WARN') +log.addLevel('error', 5000, { fg: 'red', bg: 'black' }, 'ERR!') +log.addLevel('silent', Infinity) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.jshintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.jshintrc new file mode 100644 index 0000000..248c542 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.jshintrc @@ -0,0 +1,4 @@ +{ + "laxcomma": true, + "asi": true +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/History.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/History.md new file mode 100644 index 0000000..f4a9fe3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/History.md @@ -0,0 +1,16 @@ + +0.3.0 / 2014-05-09 +================== + + * package: remove "test" script and "devDependencies" + * package: remove "engines" section + * pacakge: remove "bin" section + * package: beautify + * examples: remove `starwars` example (#15) + * Documented goto, horizontalAbsolute, and eraseLine methods in README.md (#12, @Jammerwoch) + * add `.jshintrc` file + +< 0.3.0 +======= + + * Prehistoric diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/README.md new file mode 100644 index 0000000..6ce1940 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/README.md @@ -0,0 +1,98 @@ +ansi.js +========= +### Advanced ANSI formatting tool for Node.js + +`ansi.js` is a module for Node.js that provides an easy-to-use API for +writing ANSI escape codes to `Stream` instances. ANSI escape codes are used to do +fancy things in a terminal window, like render text in colors, delete characters, +lines, the entire window, or hide and show the cursor, and lots more! + +#### Features: + + * 256 color support for the terminal! + * Make a beep sound from your terminal! + * Works with *any* writable `Stream` instance. + * Allows you to move the cursor anywhere on the terminal window. + * Allows you to delete existing contents from the terminal window. + * Allows you to hide and show the cursor. + * Converts CSS color codes and RGB values into ANSI escape codes. + * Low-level; you are in control of when escape codes are used, it's not abstracted. + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install ansi +``` + + +Example +------- + +``` js +var ansi = require('ansi') + , cursor = ansi(process.stdout) + +// You can chain your calls forever: +cursor + .red() // Set font color to red + .bg.grey() // Set background color to grey + .write('Hello World!') // Write 'Hello World!' to stdout + .bg.reset() // Reset the bgcolor before writing the trailing \n, + // to avoid Terminal glitches + .write('\n') // And a final \n to wrap things up + +// Rendering modes are persistent: +cursor.hex('#660000').bold().underline() + +// You can use the regular logging functions, text will be green: +console.log('This is blood red, bold text') + +// To reset just the foreground color: +cursor.fg.reset() + +console.log('This will still be bold') + +// to go to a location (x,y) on the console +// note: 1-indexed, not 0-indexed: +cursor.goto(10, 5).write('Five down, ten over') + +// to clear the current line: +cursor.horizontalAbsolute(0).eraseLine().write('Starting again') + +// to go to a different column on the current line: +cursor.horizontalAbsolute(5).write('column five') + +// Clean up after yourself! +cursor.reset() +``` + + +License +------- + +(The MIT License) + +Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/beep/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/beep/index.js new file mode 100755 index 0000000..c1ec929 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/beep/index.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node + +/** + * Invokes the terminal "beep" sound once per second on every exact second. + */ + +process.title = 'beep' + +var cursor = require('../../')(process.stdout) + +function beep () { + cursor.beep() + setTimeout(beep, 1000 - (new Date()).getMilliseconds()) +} + +setTimeout(beep, 1000 - (new Date()).getMilliseconds()) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/clear/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/clear/index.js new file mode 100755 index 0000000..6ac21ff --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/clear/index.js @@ -0,0 +1,15 @@ +#!/usr/bin/env node + +/** + * Like GNU ncurses "clear" command. + * https://github.com/mscdex/node-ncurses/blob/master/deps/ncurses/progs/clear.c + */ + +process.title = 'clear' + +function lf () { return '\n' } + +require('../../')(process.stdout) + .write(Array.apply(null, Array(process.stdout.getWindowSize()[1])).map(lf).join('')) + .eraseData(2) + .goto(1, 1) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/cursorPosition.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/cursorPosition.js new file mode 100755 index 0000000..50f9644 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/cursorPosition.js @@ -0,0 +1,32 @@ +#!/usr/bin/env node + +var tty = require('tty') +var cursor = require('../')(process.stdout) + +// listen for the queryPosition report on stdin +process.stdin.resume() +raw(true) + +process.stdin.once('data', function (b) { + var match = /\[(\d+)\;(\d+)R$/.exec(b.toString()) + if (match) { + var xy = match.slice(1, 3).reverse().map(Number) + console.error(xy) + } + + // cleanup and close stdin + raw(false) + process.stdin.pause() +}) + + +// send the query position request code to stdout +cursor.queryPosition() + +function raw (mode) { + if (process.stdin.setRawMode) { + process.stdin.setRawMode(mode) + } else { + tty.setRawMode(mode) + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/progress/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/progress/index.js new file mode 100644 index 0000000..d28dbda --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/examples/progress/index.js @@ -0,0 +1,87 @@ +#!/usr/bin/env node + +var assert = require('assert') + , ansi = require('../../') + +function Progress (stream, width) { + this.cursor = ansi(stream) + this.delta = this.cursor.newlines + this.width = width | 0 || 10 + this.open = '[' + this.close = ']' + this.complete = '█' + this.incomplete = '_' + + // initial render + this.progress = 0 +} + +Object.defineProperty(Progress.prototype, 'progress', { + get: get + , set: set + , configurable: true + , enumerable: true +}) + +function get () { + return this._progress +} + +function set (v) { + this._progress = Math.max(0, Math.min(v, 100)) + + var w = this.width - this.complete.length - this.incomplete.length + , n = w * (this._progress / 100) | 0 + , i = w - n + , com = c(this.complete, n) + , inc = c(this.incomplete, i) + , delta = this.cursor.newlines - this.delta + + assert.equal(com.length + inc.length, w) + + if (delta > 0) { + this.cursor.up(delta) + this.delta = this.cursor.newlines + } + + this.cursor + .horizontalAbsolute(0) + .eraseLine(2) + .fg.white() + .write(this.open) + .fg.grey() + .bold() + .write(com) + .resetBold() + .write(inc) + .fg.white() + .write(this.close) + .fg.reset() + .write('\n') +} + +function c (char, length) { + return Array.apply(null, Array(length)).map(function () { + return char + }).join('') +} + + + + +// Usage +var width = parseInt(process.argv[2], 10) || process.stdout.getWindowSize()[0] / 2 + , p = new Progress(process.stdout, width) + +;(function tick () { + p.progress += Math.random() * 5 + p.cursor + .eraseLine(2) + .write('Progress: ') + .bold().write(p.progress.toFixed(2)) + .write('%') + .resetBold() + .write('\n') + if (p.progress < 100) + setTimeout(tick, 100) +})() diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/lib/ansi.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/lib/ansi.js new file mode 100644 index 0000000..52fc8ec --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/ansi/lib/ansi.js @@ -0,0 +1,405 @@ + +/** + * References: + * + * - http://en.wikipedia.org/wiki/ANSI_escape_code + * - http://www.termsys.demon.co.uk/vtansi.htm + * + */ + +/** + * Module dependencies. + */ + +var emitNewlineEvents = require('./newlines') + , prefix = '\x1b[' // For all escape codes + , suffix = 'm' // Only for color codes + +/** + * The ANSI escape sequences. + */ + +var codes = { + up: 'A' + , down: 'B' + , forward: 'C' + , back: 'D' + , nextLine: 'E' + , previousLine: 'F' + , horizontalAbsolute: 'G' + , eraseData: 'J' + , eraseLine: 'K' + , scrollUp: 'S' + , scrollDown: 'T' + , savePosition: 's' + , restorePosition: 'u' + , queryPosition: '6n' + , hide: '?25l' + , show: '?25h' +} + +/** + * Rendering ANSI codes. + */ + +var styles = { + bold: 1 + , italic: 3 + , underline: 4 + , inverse: 7 +} + +/** + * The negating ANSI code for the rendering modes. + */ + +var reset = { + bold: 22 + , italic: 23 + , underline: 24 + , inverse: 27 +} + +/** + * The standard, styleable ANSI colors. + */ + +var colors = { + white: 37 + , black: 30 + , blue: 34 + , cyan: 36 + , green: 32 + , magenta: 35 + , red: 31 + , yellow: 33 + , grey: 90 + , brightBlack: 90 + , brightRed: 91 + , brightGreen: 92 + , brightYellow: 93 + , brightBlue: 94 + , brightMagenta: 95 + , brightCyan: 96 + , brightWhite: 97 +} + + +/** + * Creates a Cursor instance based off the given `writable stream` instance. + */ + +function ansi (stream, options) { + if (stream._ansicursor) { + return stream._ansicursor + } else { + return stream._ansicursor = new Cursor(stream, options) + } +} +module.exports = exports = ansi + +/** + * The `Cursor` class. + */ + +function Cursor (stream, options) { + if (!(this instanceof Cursor)) { + return new Cursor(stream, options) + } + if (typeof stream != 'object' || typeof stream.write != 'function') { + throw new Error('a valid Stream instance must be passed in') + } + + // the stream to use + this.stream = stream + + // when 'enabled' is false then all the functions are no-ops except for write() + this.enabled = options && options.enabled + if (typeof this.enabled === 'undefined') { + this.enabled = stream.isTTY + } + this.enabled = !!this.enabled + + // then `buffering` is true, then `write()` calls are buffered in + // memory until `flush()` is invoked + this.buffering = !!(options && options.buffering) + this._buffer = [] + + // controls the foreground and background colors + this.fg = this.foreground = new Colorer(this, 0) + this.bg = this.background = new Colorer(this, 10) + + // defaults + this.Bold = false + this.Italic = false + this.Underline = false + this.Inverse = false + + // keep track of the number of "newlines" that get encountered + this.newlines = 0 + emitNewlineEvents(stream) + stream.on('newline', function () { + this.newlines++ + }.bind(this)) +} +exports.Cursor = Cursor + +/** + * Helper function that calls `write()` on the underlying Stream. + * Returns `this` instead of the write() return value to keep + * the chaining going. + */ + +Cursor.prototype.write = function (data) { + if (this.buffering) { + this._buffer.push(arguments) + } else { + this.stream.write.apply(this.stream, arguments) + } + return this +} + +/** + * Buffer `write()` calls into memory. + * + * @api public + */ + +Cursor.prototype.buffer = function () { + this.buffering = true + return this +} + +/** + * Write out the in-memory buffer. + * + * @api public + */ + +Cursor.prototype.flush = function () { + this.buffering = false + var str = this._buffer.map(function (args) { + if (args.length != 1) throw new Error('unexpected args length! ' + args.length); + return args[0]; + }).join(''); + this._buffer.splice(0); // empty + this.write(str); + return this +} + + +/** + * The `Colorer` class manages both the background and foreground colors. + */ + +function Colorer (cursor, base) { + this.current = null + this.cursor = cursor + this.base = base +} +exports.Colorer = Colorer + +/** + * Write an ANSI color code, ensuring that the same code doesn't get rewritten. + */ + +Colorer.prototype._setColorCode = function setColorCode (code) { + var c = String(code) + if (this.current === c) return + this.cursor.enabled && this.cursor.write(prefix + c + suffix) + this.current = c + return this +} + + +/** + * Set up the positional ANSI codes. + */ + +Object.keys(codes).forEach(function (name) { + var code = String(codes[name]) + Cursor.prototype[name] = function () { + var c = code + if (arguments.length > 0) { + c = toArray(arguments).map(Math.round).join(';') + code + } + this.enabled && this.write(prefix + c) + return this + } +}) + +/** + * Set up the functions for the rendering ANSI codes. + */ + +Object.keys(styles).forEach(function (style) { + var name = style[0].toUpperCase() + style.substring(1) + , c = styles[style] + , r = reset[style] + + Cursor.prototype[style] = function () { + if (this[name]) return + this.enabled && this.write(prefix + c + suffix) + this[name] = true + return this + } + + Cursor.prototype['reset' + name] = function () { + if (!this[name]) return + this.enabled && this.write(prefix + r + suffix) + this[name] = false + return this + } +}) + +/** + * Setup the functions for the standard colors. + */ + +Object.keys(colors).forEach(function (color) { + var code = colors[color] + + Colorer.prototype[color] = function () { + this._setColorCode(this.base + code) + return this.cursor + } + + Cursor.prototype[color] = function () { + return this.foreground[color]() + } +}) + +/** + * Makes a beep sound! + */ + +Cursor.prototype.beep = function () { + this.enabled && this.write('\x07') + return this +} + +/** + * Moves cursor to specific position + */ + +Cursor.prototype.goto = function (x, y) { + x = x | 0 + y = y | 0 + this.enabled && this.write(prefix + y + ';' + x + 'H') + return this +} + +/** + * Resets the color. + */ + +Colorer.prototype.reset = function () { + this._setColorCode(this.base + 39) + return this.cursor +} + +/** + * Resets all ANSI formatting on the stream. + */ + +Cursor.prototype.reset = function () { + this.enabled && this.write(prefix + '0' + suffix) + this.Bold = false + this.Italic = false + this.Underline = false + this.Inverse = false + this.foreground.current = null + this.background.current = null + return this +} + +/** + * Sets the foreground color with the given RGB values. + * The closest match out of the 216 colors is picked. + */ + +Colorer.prototype.rgb = function (r, g, b) { + var base = this.base + 38 + , code = rgb(r, g, b) + this._setColorCode(base + ';5;' + code) + return this.cursor +} + +/** + * Same as `cursor.fg.rgb(r, g, b)`. + */ + +Cursor.prototype.rgb = function (r, g, b) { + return this.foreground.rgb(r, g, b) +} + +/** + * Accepts CSS color codes for use with ANSI escape codes. + * For example: `#FF000` would be bright red. + */ + +Colorer.prototype.hex = function (color) { + return this.rgb.apply(this, hex(color)) +} + +/** + * Same as `cursor.fg.hex(color)`. + */ + +Cursor.prototype.hex = function (color) { + return this.foreground.hex(color) +} + + +// UTIL FUNCTIONS // + +/** + * Translates a 255 RGB value to a 0-5 ANSI RGV value, + * then returns the single ANSI color code to use. + */ + +function rgb (r, g, b) { + var red = r / 255 * 5 + , green = g / 255 * 5 + , blue = b / 255 * 5 + return rgb5(red, green, blue) +} + +/** + * Turns rgb 0-5 values into a single ANSI color code to use. + */ + +function rgb5 (r, g, b) { + var red = Math.round(r) + , green = Math.round(g) + , blue = Math.round(b) + return 16 + (red*36) + (green*6) + blue +} + +/** + * Accepts a hex CSS color code string (# is optional) and + * translates it into an Array of 3 RGB 0-255 values, which + * can then be used with rgb(). + */ + +function hex (color) { + var c = color[0] === '#' ? color.substring(1) : color + , r = c.substring(0, 2) + , g = c.substring(2, 4) + , b = c.substring(4, 6) + return [parseInt(r, 16), parseInt(g, 16), parseInt(b, 16)] +} + +/** + * Turns an array-like object into a real array. + */ + +function toArray (a) { + var i = 0 + , l = a.length + , rtn = [] + for (; i 0) { + var len = data.length + , i = 0 + // now try to calculate any deltas + if (typeof data == 'string') { + for (; i=0.3.0 <0.4.0", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "TooTallNate", + "email": "nathan@tootallnate.net" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "74b2f1f187c8553c7f95015bcb76009fb43d38e0", + "tarball": "http://registry.npmjs.org/ansi/-/ansi-0.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ansi/-/ansi-0.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/.npmignore new file mode 100644 index 0000000..926ddf6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/.npmignore @@ -0,0 +1,3 @@ +*~ +.#* +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/README.md new file mode 100644 index 0000000..52f9f9a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/README.md @@ -0,0 +1,183 @@ +are-we-there-yet +---------------- + +Track complex hiearchies of asynchronous task completion statuses. This is +intended to give you a way of recording and reporting the progress of the big +recursive fan-out and gather type workflows that are so common in async. + +What you do with this completion data is up to you, but the most common use case is to +feed it to one of the many progress bar modules. + +Most progress bar modules include a rudamentary version of this, but my +needs were more complex. + +Usage +===== + +```javascript +var TrackerGroup = require("are-we-there-yet").TrackerGroup + +var top = new TrackerGroup("program") + +var single = top.newItem("one thing", 100) +single.completeWork(20) + +console.log(top.completed()) // 0.2 + +fs.stat("file", function(er, stat) { + if (er) throw er + var stream = top.newStream("file", stat.size) + console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete + // and 50% * 20% == 10% + fs.createReadStream("file").pipe(stream).on("data", function (chunk) { + // do stuff with chunk + }) + top.on("change", function (name) { + // called each time a chunk is read from "file" + // top.completed() will start at 0.1 and fill up to 0.6 as the file is read + }) +}) +``` + +Shared Methods +============== + +All tracker objects described below have the following methods, they, along +with the event comprise the interface for consumers of tracker objects. + +* var completed = tracker.completed() + +Returns the ratio of completed work to work to be done. Range of 0 to 1. + +* tracker.finish() + +Marks the tracker as completed. With a TrackerGroup this marks all of its +components as completed. + +Marks all of the components of this tracker as finished, which in turn means +that `tracker.completed()` for this will now be 1. + +This will result in one or more `change` events being emitted. + +Events +====== + +All tracker objects emit `change` events with an argument of the name of the +thing changing. + +TrackerGroup +============ + +* var tracker = new TrackerGroup(**name**) + + * **name** *(optional)* - The name of this tracker group, used in change + notifications if the component updating didn't have a name. Defaults to undefined. + +Creates a new empty tracker aggregation group. These are trackers whose +completion status is determined by the completion status of other trackers. + +* tracker.addUnit(**otherTracker**, **weight**) + + * **otherTracker** - Any of the other are-we-there-yet tracker objects + * **weight** *(optional)* - The weight to give the tracker, defaults to 1. + +Adds the **otherTracker** to this aggregation group. The weight determines +how long you expect this tracker to take to complete in proportion to other +units. So for instance, if you add one tracker with a weight of 1 and +another with a weight of 2, you're saying the second will take twice as long +to complete as the first. As such, the first will account for 33% of the +completion of this tracker and the second will account for the other 67%. + +Returns **otherTracker**. + +* var subGroup = tracker.newGroup(**name**, **weight**) + +The above is exactly equivalent to: + +```javascript + var subGroup = tracker.addUnit(new TrackerGroup(name), weight) +``` + +* var subItem = tracker.newItem(**name**, **todo**, **weight**) + +The above is exactly equivalent to: + +```javascript + var subItem = tracker.addUnit(new Tracker(name, todo), weight) +``` + +* var subStream = tracker.newStream(**name**, **todo**, **weight**) + +The above is exactly equivalent to: + +```javascript + var subStream = tracker.addUnit(new TrackerStream(name, todo), weight) +``` + +* console.log( tracker.debug() ) + +Returns a tree showing the completion of this tracker group and all of its +children, including recursively entering all of the children. + +Tracker +======= + +* var tracker = new Tracker(**name**, **todo**) + + * **name** *(optional)* The name of this counter to report in change + events. Defaults to undefined. + * **todo** *(optional)* The amount of work todo (a number). Defaults to 0. + +Ordinarily these are constructed as a part of a tracker group (via `newItem`) but they c + +* var completed = tracker.completed() + +Returns the ratio of completed work to work to be done. Range of 0 to 1. If +total work to be done is 0 then it will return 0. + +* tracker.addWork(**todo**) + + * **todo** A number to add to the amount of work to be done. + +Increases the amount of work to be done, thus decreasing the completion +percentage. Triggers a `change` event. + +* tracker.completeWork(**completed**) + + * **completed** A number to add to the work complete + +Increase the amount of work complete, thus increasing the completion percentage. +Will never increase the work completed past the amount of work todo. That is, +percentages > 100% are not allowed. Triggers a `change` event. + +* tracker.finish() + +Marks this tracker as finished, tracker.completed() will now be 1. Triggers +a `change` event. + +TrackerStream +============= + +* var tracker = new TrackerStream(**name**, **size**, **options**) + + * **name** *(optional)* The name of this counter to report in change + events. Defaults to undefined. + * **size** *(optional)* The number of bytes being sent through this stream. + * **options** *(optional)* A hash of stream options + +The tracker stream object is a pass through stream that updates an internal +tracker object each time a block passes through. It's intended to track +downloads, file extraction and other related activities. You use it by piping +your data source into it and then using it as your data source. + +If your data has a length attribute then that's used as the amount of work +completed when the chunk is passed through. If it does not (eg, object +streams) then each chunk counts as completing 1 unit of work, so your size +should be the total number of objects being streamed. + +* tracker.addWork(**todo**) + + * **todo** Increase the expected overall size by **todo** bytes. + +Increases the amount of work to be done, thus decreasing the completion +percentage. Triggers a `change` event. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/index.js new file mode 100644 index 0000000..22f47ac --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/index.js @@ -0,0 +1,130 @@ +"use strict" +var stream = require("readable-stream"); +var EventEmitter = require("events").EventEmitter +var util = require("util") +var delegate = require("delegates") + +var TrackerGroup = exports.TrackerGroup = function (name) { + EventEmitter.call(this) + this.name = name + this.trackGroup = [] + var self = this + this.totalWeight = 0 + var noteChange = this.noteChange = function (name) { + self.emit("change", name || this.name) + }.bind(this) + this.trackGroup.forEach(function(unit) { + unit.on("change", noteChange) + }) +} +util.inherits(TrackerGroup, EventEmitter) + +TrackerGroup.prototype.completed = function () { + if (this.trackGroup.length==0) return 0 + var valPerWeight = 1 / this.totalWeight + var completed = 0 + this.trackGroup.forEach(function(T) { + completed += valPerWeight * T.weight * T.completed() + }) + return completed +} + +TrackerGroup.prototype.addUnit = function (unit, weight, noChange) { + unit.weight = weight || 1 + this.totalWeight += unit.weight + this.trackGroup.push(unit) + unit.on("change", this.noteChange) + if (! noChange) this.emit("change", this.name) + return unit +} + +TrackerGroup.prototype.newGroup = function (name, weight) { + return this.addUnit(new TrackerGroup(name), weight) +} + +TrackerGroup.prototype.newItem = function (name, todo, weight) { + return this.addUnit(new Tracker(name, todo), weight) +} + +TrackerGroup.prototype.newStream = function (name, todo, weight) { + return this.addUnit(new TrackerStream(name, todo), weight) +} + +TrackerGroup.prototype.finish = function () { + if (! this.trackGroup.length) { this.addUnit(new Tracker(), 1, true) } + var self = this + this.trackGroup.forEach(function(T) { + T.removeListener("change", self.noteChange) + T.finish() + }) + this.emit("change", this.name) +} + +var buffer = " " +TrackerGroup.prototype.debug = function (depth) { + depth = depth || 0 + var indent = depth ? buffer.substr(0,depth) : "" + var output = indent + (this.name||"top") + ": " + this.completed() + "\n" + this.trackGroup.forEach(function(T) { + if (T instanceof TrackerGroup) { + output += T.debug(depth + 1) + } + else { + output += indent + " " + T.name + ": " + T.completed() + "\n" + } + }) + return output +} + +var Tracker = exports.Tracker = function (name,todo) { + EventEmitter.call(this) + this.name = name + this.workDone = 0 + this.workTodo = todo || 0 +} +util.inherits(Tracker, EventEmitter) + +Tracker.prototype.completed = function () { + return this.workTodo==0 ? 0 : this.workDone / this.workTodo +} + +Tracker.prototype.addWork = function (work) { + this.workTodo += work + this.emit("change", this.name) +} + +Tracker.prototype.completeWork = function (work) { + this.workDone += work + if (this.workDone > this.workTodo) this.workDone = this.workTodo + this.emit("change", this.name) +} + +Tracker.prototype.finish = function () { + this.workTodo = this.workDone = 1 + this.emit("change", this.name) +} + + +var TrackerStream = exports.TrackerStream = function (name, size, options) { + stream.Transform.call(this, options) + this.tracker = new Tracker(name, size) + this.name = name + var self = this + this.tracker.on("change", function (name) { self.emit("change", name) }) +} +util.inherits(TrackerStream, stream.Transform) + +TrackerStream.prototype._transform = function (data, encoding, cb) { + this.tracker.completeWork(data.length ? data.length : 1) + this.push(data) + cb() +} + +TrackerStream.prototype._flush = function (cb) { + this.tracker.finish() + cb() +} + +delegate(TrackerStream.prototype, "tracker") + .method("completed") + .method("addWork") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/.npmignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/History.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/History.md new file mode 100644 index 0000000..aee31a4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/History.md @@ -0,0 +1,16 @@ + +0.1.0 / 2014-10-17 +================== + + * adds `.fluent()` to api + +0.0.3 / 2014-01-13 +================== + + * fix receiver for .method() + +0.0.2 / 2014-01-13 +================== + + * Object.defineProperty() sucks + * Initial commit diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Makefile new file mode 100644 index 0000000..a9dcfd5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Makefile @@ -0,0 +1,8 @@ + +test: + @./node_modules/.bin/mocha \ + --require should \ + --reporter spec \ + --bail + +.PHONY: test \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Readme.md new file mode 100644 index 0000000..ab8cf4a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/Readme.md @@ -0,0 +1,94 @@ + +# delegates + + Node method and accessor delegation utilty. + +## Installation + +``` +$ npm install delegates +``` + +## Example + +```js +var delegate = require('delegates'); + +... + +delegate(proto, 'request') + .method('acceptsLanguages') + .method('acceptsEncodings') + .method('acceptsCharsets') + .method('accepts') + .method('is') + .access('querystring') + .access('idempotent') + .access('socket') + .access('length') + .access('query') + .access('search') + .access('status') + .access('method') + .access('path') + .access('body') + .access('host') + .access('url') + .getter('subdomains') + .getter('protocol') + .getter('header') + .getter('stale') + .getter('fresh') + .getter('secure') + .getter('ips') + .getter('ip') +``` + +# API + +## Delegate(proto, prop) + +Creates a delegator instance used to configure using the `prop` on the given +`proto` object. (which is usually a prototype) + +## Delegate#method(name) + +Allows the given method `name` to be accessed on the host. + +## Delegate#getter(name) + +Creates a "getter" for the property with the given `name` on the delegated +object. + +## Delegate#setter(name) + +Creates a "setter" for the property with the given `name` on the delegated +object. + +## Delegate#access(name) + +Creates an "accessor" (ie: both getter *and* setter) for the property with the +given `name` on the delegated object. + +## Delegate#fluent(name) + +A unique type of "accessor" that works for a "fluent" API. When called as a +getter, the method returns the expected value. However, if the method is called +with a value, it will return itself so it can be chained. For example: + +```js +delegate(proto, 'request') + .fluent('query') + +// getter +var q = request.query(); + +// setter (chainable) +request + .query({ a: 1 }) + .query({ b: 2 }); +``` + +# License + + MIT diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js new file mode 100644 index 0000000..17c222d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/index.js @@ -0,0 +1,121 @@ + +/** + * Expose `Delegator`. + */ + +module.exports = Delegator; + +/** + * Initialize a delegator. + * + * @param {Object} proto + * @param {String} target + * @api public + */ + +function Delegator(proto, target) { + if (!(this instanceof Delegator)) return new Delegator(proto, target); + this.proto = proto; + this.target = target; + this.methods = []; + this.getters = []; + this.setters = []; + this.fluents = []; +} + +/** + * Delegate method `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.method = function(name){ + var proto = this.proto; + var target = this.target; + this.methods.push(name); + + proto[name] = function(){ + return this[target][name].apply(this[target], arguments); + }; + + return this; +}; + +/** + * Delegator accessor `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.access = function(name){ + return this.getter(name).setter(name); +}; + +/** + * Delegator getter `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.getter = function(name){ + var proto = this.proto; + var target = this.target; + this.getters.push(name); + + proto.__defineGetter__(name, function(){ + return this[target][name]; + }); + + return this; +}; + +/** + * Delegator setter `name`. + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.setter = function(name){ + var proto = this.proto; + var target = this.target; + this.setters.push(name); + + proto.__defineSetter__(name, function(val){ + return this[target][name] = val; + }); + + return this; +}; + +/** + * Delegator fluent accessor + * + * @param {String} name + * @return {Delegator} self + * @api public + */ + +Delegator.prototype.fluent = function (name) { + var proto = this.proto; + var target = this.target; + this.fluents.push(name); + + proto[name] = function(val){ + if ('undefined' != typeof val) { + this[target][name] = val; + return this; + } else { + return this[target][name]; + } + }; + + return this; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/package.json new file mode 100644 index 0000000..ea3c1da --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/package.json @@ -0,0 +1,48 @@ +{ + "name": "delegates", + "version": "0.1.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-delegates.git" + }, + "description": "delegate methods and accessors to another property", + "keywords": [ + "delegate", + "delegation" + ], + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/visionmedia/node-delegates/issues" + }, + "homepage": "https://github.com/visionmedia/node-delegates", + "_id": "delegates@0.1.0", + "_shasum": "b4b57be11a1653517a04b27f0949bdc327dfe390", + "_from": "delegates@>=0.1.0 <0.2.0", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + } + ], + "dist": { + "shasum": "b4b57be11a1653517a04b27f0949bdc327dfe390", + "tarball": "http://registry.npmjs.org/delegates/-/delegates-0.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/delegates/-/delegates-0.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/test/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/test/index.js new file mode 100644 index 0000000..7b6e3d4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/delegates/test/index.js @@ -0,0 +1,94 @@ + +var assert = require('assert'); +var delegate = require('..'); + +describe('.method(name)', function(){ + it('should delegate methods', function(){ + var obj = {}; + + obj.request = { + foo: function(bar){ + assert(this == obj.request); + return bar; + } + }; + + delegate(obj, 'request').method('foo'); + + obj.foo('something').should.equal('something'); + }) +}) + +describe('.getter(name)', function(){ + it('should delegate getters', function(){ + var obj = {}; + + obj.request = { + get type() { + return 'text/html'; + } + } + + delegate(obj, 'request').getter('type'); + + obj.type.should.equal('text/html'); + }) +}) + +describe('.setter(name)', function(){ + it('should delegate setters', function(){ + var obj = {}; + + obj.request = { + get type() { + return this._type.toUpperCase(); + }, + + set type(val) { + this._type = val; + } + } + + delegate(obj, 'request').setter('type'); + + obj.type = 'hey'; + obj.request.type.should.equal('HEY'); + }) +}) + +describe('.access(name)', function(){ + it('should delegate getters and setters', function(){ + var obj = {}; + + obj.request = { + get type() { + return this._type.toUpperCase(); + }, + + set type(val) { + this._type = val; + } + } + + delegate(obj, 'request').access('type'); + + obj.type = 'hey'; + obj.type.should.equal('HEY'); + }) +}) + +describe('.fluent(name)', function () { + it('should delegate in a fluent fashion', function () { + var obj = { + settings: { + env: 'development' + } + }; + + delegate(obj, 'settings').fluent('env'); + + obj.env().should.equal('development'); + obj.env('production').should.equal(obj); + obj.settings.env.should.equal('production'); + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/README.md new file mode 100644 index 0000000..e46b823 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png&months=6&height=3)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/float.patch b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/float.patch new file mode 100644 index 0000000..b984607 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/float.patch @@ -0,0 +1,923 @@ +diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js +index c5a741c..a2e0d8e 100644 +--- a/lib/_stream_duplex.js ++++ b/lib/_stream_duplex.js +@@ -26,8 +26,8 @@ + + module.exports = Duplex; + var util = require('util'); +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('./_stream_readable'); ++var Writable = require('./_stream_writable'); + + util.inherits(Duplex, Readable); + +diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js +index a5e9864..330c247 100644 +--- a/lib/_stream_passthrough.js ++++ b/lib/_stream_passthrough.js +@@ -25,7 +25,7 @@ + + module.exports = PassThrough; + +-var Transform = require('_stream_transform'); ++var Transform = require('./_stream_transform'); + var util = require('util'); + util.inherits(PassThrough, Transform); + +diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js +index 0c3fe3e..90a8298 100644 +--- a/lib/_stream_readable.js ++++ b/lib/_stream_readable.js +@@ -23,10 +23,34 @@ module.exports = Readable; + Readable.ReadableState = ReadableState; + + var EE = require('events').EventEmitter; ++if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { ++ return emitter.listeners(type).length; ++}; ++ ++if (!global.setImmediate) global.setImmediate = function setImmediate(fn) { ++ return setTimeout(fn, 0); ++}; ++if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) { ++ return clearTimeout(i); ++}; ++ + var Stream = require('stream'); + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + var StringDecoder; +-var debug = util.debuglog('stream'); ++var debug; ++if (util.debuglog) ++ debug = util.debuglog('stream'); ++else try { ++ debug = require('debuglog')('stream'); ++} catch (er) { ++ debug = function() {}; ++} + + util.inherits(Readable, Stream); + +@@ -380,7 +404,7 @@ function chunkInvalid(state, chunk) { + + + function onEofChunk(stream, state) { +- if (state.decoder && !state.ended) { ++ if (state.decoder && !state.ended && state.decoder.end) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); +diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js +index b1f9fcc..b0caf57 100644 +--- a/lib/_stream_transform.js ++++ b/lib/_stream_transform.js +@@ -64,8 +64,14 @@ + + module.exports = Transform; + +-var Duplex = require('_stream_duplex'); ++var Duplex = require('./_stream_duplex'); + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + util.inherits(Transform, Duplex); + + +diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js +index ba2e920..f49288b 100644 +--- a/lib/_stream_writable.js ++++ b/lib/_stream_writable.js +@@ -27,6 +27,12 @@ module.exports = Writable; + Writable.WritableState = WritableState; + + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + var Stream = require('stream'); + + util.inherits(Writable, Stream); +@@ -119,7 +125,7 @@ function WritableState(options, stream) { + function Writable(options) { + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. +- if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) ++ if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex'))) + return new Writable(options); + + this._writableState = new WritableState(options, this); +diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js +index e3787e4..8cd2127 100644 +--- a/test/simple/test-stream-big-push.js ++++ b/test/simple/test-stream-big-push.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + var str = 'asdfasdfasdfasdfasdf'; + + var r = new stream.Readable({ +diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js +index bb73777..d40efc7 100644 +--- a/test/simple/test-stream-end-paused.js ++++ b/test/simple/test-stream-end-paused.js +@@ -25,7 +25,7 @@ var gotEnd = false; + + // Make sure we don't miss the end event for paused 0-length streams + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var stream = new Readable(); + var calledRead = false; + stream._read = function() { +diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js +index b46ee90..0be8366 100644 +--- a/test/simple/test-stream-pipe-after-end.js ++++ b/test/simple/test-stream-pipe-after-end.js +@@ -22,8 +22,8 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var util = require('util'); + + util.inherits(TestReadable, Readable); +diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js +deleted file mode 100644 +index f689358..0000000 +--- a/test/simple/test-stream-pipe-cleanup.js ++++ /dev/null +@@ -1,122 +0,0 @@ +-// 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. +- +-// This test asserts that Stream.prototype.pipe does not leave listeners +-// hanging on the source or dest. +- +-var common = require('../common'); +-var stream = require('stream'); +-var assert = require('assert'); +-var util = require('util'); +- +-function Writable() { +- this.writable = true; +- this.endCalls = 0; +- stream.Stream.call(this); +-} +-util.inherits(Writable, stream.Stream); +-Writable.prototype.end = function() { +- this.endCalls++; +-}; +- +-Writable.prototype.destroy = function() { +- this.endCalls++; +-}; +- +-function Readable() { +- this.readable = true; +- stream.Stream.call(this); +-} +-util.inherits(Readable, stream.Stream); +- +-function Duplex() { +- this.readable = true; +- Writable.call(this); +-} +-util.inherits(Duplex, Writable); +- +-var i = 0; +-var limit = 100; +- +-var w = new Writable(); +- +-var r; +- +-for (i = 0; i < limit; i++) { +- r = new Readable(); +- r.pipe(w); +- r.emit('end'); +-} +-assert.equal(0, r.listeners('end').length); +-assert.equal(limit, w.endCalls); +- +-w.endCalls = 0; +- +-for (i = 0; i < limit; i++) { +- r = new Readable(); +- r.pipe(w); +- r.emit('close'); +-} +-assert.equal(0, r.listeners('close').length); +-assert.equal(limit, w.endCalls); +- +-w.endCalls = 0; +- +-r = new Readable(); +- +-for (i = 0; i < limit; i++) { +- w = new Writable(); +- r.pipe(w); +- w.emit('close'); +-} +-assert.equal(0, w.listeners('close').length); +- +-r = new Readable(); +-w = new Writable(); +-var d = new Duplex(); +-r.pipe(d); // pipeline A +-d.pipe(w); // pipeline B +-assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup +-assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +-assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 1); // B.cleanup +- +-r.emit('end'); +-assert.equal(d.endCalls, 1); +-assert.equal(w.endCalls, 0); +-assert.equal(r.listeners('end').length, 0); +-assert.equal(r.listeners('close').length, 0); +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +-assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 1); // B.cleanup +- +-d.emit('end'); +-assert.equal(d.endCalls, 1); +-assert.equal(w.endCalls, 1); +-assert.equal(r.listeners('end').length, 0); +-assert.equal(r.listeners('close').length, 0); +-assert.equal(d.listeners('end').length, 0); +-assert.equal(d.listeners('close').length, 0); +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 0); +diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js +index c5d724b..c7d6b7d 100644 +--- a/test/simple/test-stream-pipe-error-handling.js ++++ b/test/simple/test-stream-pipe-error-handling.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var Stream = require('stream').Stream; ++var Stream = require('../../').Stream; + + (function testErrorListenerCatches() { + var source = new Stream(); +diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js +index cb9d5fe..56f8d61 100644 +--- a/test/simple/test-stream-pipe-event.js ++++ b/test/simple/test-stream-pipe-event.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common'); +-var stream = require('stream'); ++var stream = require('../../'); + var assert = require('assert'); + var util = require('util'); + +diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js +index f2e6ec2..a5c9bf9 100644 +--- a/test/simple/test-stream-push-order.js ++++ b/test/simple/test-stream-push-order.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var assert = require('assert'); + + var s = new Readable({ +diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js +index 06f43dc..1701a9a 100644 +--- a/test/simple/test-stream-push-strings.js ++++ b/test/simple/test-stream-push-strings.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var util = require('util'); + + util.inherits(MyStream, Readable); +diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js +index ba6a577..a8e6f7b 100644 +--- a/test/simple/test-stream-readable-event.js ++++ b/test/simple/test-stream-readable-event.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + (function first() { + // First test, not reading when the readable is added. +diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js +index 2891ad6..11689ba 100644 +--- a/test/simple/test-stream-readable-flow-recursion.js ++++ b/test/simple/test-stream-readable-flow-recursion.js +@@ -27,7 +27,7 @@ var assert = require('assert'); + // more data continuously, but without triggering a nextTick + // warning or RangeError. + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + // throw an error if we trigger a nextTick warning. + process.throwDeprecation = true; +diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js +index 0c96476..7827538 100644 +--- a/test/simple/test-stream-unshift-empty-chunk.js ++++ b/test/simple/test-stream-unshift-empty-chunk.js +@@ -24,7 +24,7 @@ var assert = require('assert'); + + // This test verifies that stream.unshift(Buffer(0)) or + // stream.unshift('') does not set state.reading=false. +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + var r = new Readable(); + var nChunks = 10; +diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js +index 83fd9fa..17c18aa 100644 +--- a/test/simple/test-stream-unshift-read-race.js ++++ b/test/simple/test-stream-unshift-read-race.js +@@ -29,7 +29,7 @@ var assert = require('assert'); + // 3. push() after the EOF signaling null is an error. + // 4. _read() is not called after pushing the EOF null chunk. + +-var stream = require('stream'); ++var stream = require('../../'); + var hwm = 10; + var r = stream.Readable({ highWaterMark: hwm }); + var chunks = 10; +@@ -51,7 +51,14 @@ r._read = function(n) { + + function push(fast) { + assert(!pushedNull, 'push() after null push'); +- var c = pos >= data.length ? null : data.slice(pos, pos + n); ++ var c; ++ if (pos >= data.length) ++ c = null; ++ else { ++ if (n + pos > data.length) ++ n = data.length - pos; ++ c = data.slice(pos, pos + n); ++ } + pushedNull = c === null; + if (fast) { + pos += n; +diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js +index 5b49e6e..b5321f3 100644 +--- a/test/simple/test-stream-writev.js ++++ b/test/simple/test-stream-writev.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var stream = require('stream'); ++var stream = require('../../'); + + var queue = []; + for (var decode = 0; decode < 2; decode++) { +diff --git a/test/simple/test-stream2-basic.js b/test/simple/test-stream2-basic.js +index 3814bf0..248c1be 100644 +--- a/test/simple/test-stream2-basic.js ++++ b/test/simple/test-stream2-basic.js +@@ -21,7 +21,7 @@ + + + var common = require('../common.js'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js +index 6cdd4e9..f0fa84b 100644 +--- a/test/simple/test-stream2-compatibility.js ++++ b/test/simple/test-stream2-compatibility.js +@@ -21,7 +21,7 @@ + + + var common = require('../common.js'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js +index 39b274f..006a19b 100644 +--- a/test/simple/test-stream2-finish-pipe.js ++++ b/test/simple/test-stream2-finish-pipe.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var stream = require('stream'); ++var stream = require('../../'); + var Buffer = require('buffer').Buffer; + + var r = new stream.Readable(); +diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js +deleted file mode 100644 +index e162406..0000000 +--- a/test/simple/test-stream2-fs.js ++++ /dev/null +@@ -1,72 +0,0 @@ +-// Copyright Joyent, Inc. and other Node contributors. +-// +-// Permission is hereby granted, free of charge, to any person obtaining a +-// copy of this software and associated documentation files (the +-// "Software"), to deal in the Software without restriction, including +-// without limitation the rights to use, copy, modify, merge, publish, +-// distribute, sublicense, and/or sell copies of the Software, and to permit +-// persons to whom the Software is furnished to do so, subject to the +-// following conditions: +-// +-// The above copyright notice and this permission notice shall be included +-// in all copies or substantial portions of the Software. +-// +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +-// USE OR OTHER DEALINGS IN THE SOFTWARE. +- +- +-var common = require('../common.js'); +-var R = require('_stream_readable'); +-var assert = require('assert'); +- +-var fs = require('fs'); +-var FSReadable = fs.ReadStream; +- +-var path = require('path'); +-var file = path.resolve(common.fixturesDir, 'x1024.txt'); +- +-var size = fs.statSync(file).size; +- +-var expectLengths = [1024]; +- +-var util = require('util'); +-var Stream = require('stream'); +- +-util.inherits(TestWriter, Stream); +- +-function TestWriter() { +- Stream.apply(this); +- this.buffer = []; +- this.length = 0; +-} +- +-TestWriter.prototype.write = function(c) { +- this.buffer.push(c.toString()); +- this.length += c.length; +- return true; +-}; +- +-TestWriter.prototype.end = function(c) { +- if (c) this.buffer.push(c.toString()); +- this.emit('results', this.buffer); +-} +- +-var r = new FSReadable(file); +-var w = new TestWriter(); +- +-w.on('results', function(res) { +- console.error(res, w.length); +- assert.equal(w.length, size); +- var l = 0; +- assert.deepEqual(res.map(function (c) { +- return c.length; +- }), expectLengths); +- console.log('ok'); +-}); +- +-r.pipe(w); +diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js +deleted file mode 100644 +index 15cffc2..0000000 +--- a/test/simple/test-stream2-httpclient-response-end.js ++++ /dev/null +@@ -1,52 +0,0 @@ +-// Copyright Joyent, Inc. and other Node contributors. +-// +-// Permission is hereby granted, free of charge, to any person obtaining a +-// copy of this software and associated documentation files (the +-// "Software"), to deal in the Software without restriction, including +-// without limitation the rights to use, copy, modify, merge, publish, +-// distribute, sublicense, and/or sell copies of the Software, and to permit +-// persons to whom the Software is furnished to do so, subject to the +-// following conditions: +-// +-// The above copyright notice and this permission notice shall be included +-// in all copies or substantial portions of the Software. +-// +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +-// USE OR OTHER DEALINGS IN THE SOFTWARE. +- +-var common = require('../common.js'); +-var assert = require('assert'); +-var http = require('http'); +-var msg = 'Hello'; +-var readable_event = false; +-var end_event = false; +-var server = http.createServer(function(req, res) { +- res.writeHead(200, {'Content-Type': 'text/plain'}); +- res.end(msg); +-}).listen(common.PORT, function() { +- http.get({port: common.PORT}, function(res) { +- var data = ''; +- res.on('readable', function() { +- console.log('readable event'); +- readable_event = true; +- data += res.read(); +- }); +- res.on('end', function() { +- console.log('end event'); +- end_event = true; +- assert.strictEqual(msg, data); +- server.close(); +- }); +- }); +-}); +- +-process.on('exit', function() { +- assert(readable_event); +- assert(end_event); +-}); +- +diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js +index 2fbfbca..667985b 100644 +--- a/test/simple/test-stream2-large-read-stall.js ++++ b/test/simple/test-stream2-large-read-stall.js +@@ -30,7 +30,7 @@ var PUSHSIZE = 20; + var PUSHCOUNT = 1000; + var HWM = 50; + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var r = new Readable({ + highWaterMark: HWM + }); +@@ -39,23 +39,23 @@ var rs = r._readableState; + r._read = push; + + r.on('readable', function() { +- console.error('>> readable'); ++ //console.error('>> readable'); + do { +- console.error(' > read(%d)', READSIZE); ++ //console.error(' > read(%d)', READSIZE); + var ret = r.read(READSIZE); +- console.error(' < %j (%d remain)', ret && ret.length, rs.length); ++ //console.error(' < %j (%d remain)', ret && ret.length, rs.length); + } while (ret && ret.length === READSIZE); + +- console.error('<< after read()', +- ret && ret.length, +- rs.needReadable, +- rs.length); ++ //console.error('<< after read()', ++ // ret && ret.length, ++ // rs.needReadable, ++ // rs.length); + }); + + var endEmitted = false; + r.on('end', function() { + endEmitted = true; +- console.error('end'); ++ //console.error('end'); + }); + + var pushes = 0; +@@ -64,11 +64,11 @@ function push() { + return; + + if (pushes++ === PUSHCOUNT) { +- console.error(' push(EOF)'); ++ //console.error(' push(EOF)'); + return r.push(null); + } + +- console.error(' push #%d', pushes); ++ //console.error(' push #%d', pushes); + if (r.push(new Buffer(PUSHSIZE))) + setTimeout(push); + } +diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js +index 3e6931d..ff47d89 100644 +--- a/test/simple/test-stream2-objects.js ++++ b/test/simple/test-stream2-objects.js +@@ -21,8 +21,8 @@ + + + var common = require('../common.js'); +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var assert = require('assert'); + + // tiny node-tap lookalike. +diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js +index cf7531c..e3f3e4e 100644 +--- a/test/simple/test-stream2-pipe-error-handling.js ++++ b/test/simple/test-stream2-pipe-error-handling.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + + (function testErrorListenerCatches() { + var count = 1000; +diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js +index 5e8e3cb..53b2616 100755 +--- a/test/simple/test-stream2-pipe-error-once-listener.js ++++ b/test/simple/test-stream2-pipe-error-once-listener.js +@@ -24,7 +24,7 @@ var common = require('../common.js'); + var assert = require('assert'); + + var util = require('util'); +-var stream = require('stream'); ++var stream = require('../../'); + + + var Read = function() { +diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js +index b63edc3..eb2b0e9 100644 +--- a/test/simple/test-stream2-push.js ++++ b/test/simple/test-stream2-push.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var stream = require('stream'); ++var stream = require('../../'); + var Readable = stream.Readable; + var Writable = stream.Writable; + var assert = require('assert'); +diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js +index e8a7305..9740a47 100644 +--- a/test/simple/test-stream2-read-sync-stack.js ++++ b/test/simple/test-stream2-read-sync-stack.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var r = new Readable(); + var N = 256 * 1024; + +diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js +index cd30178..4b1659d 100644 +--- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js ++++ b/test/simple/test-stream2-readable-empty-buffer-no-eof.js +@@ -22,10 +22,9 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + test1(); +-test2(); + + function test1() { + var r = new Readable(); +@@ -88,31 +87,3 @@ function test1() { + console.log('ok'); + }); + } +- +-function test2() { +- var r = new Readable({ encoding: 'base64' }); +- var reads = 5; +- r._read = function(n) { +- if (!reads--) +- return r.push(null); // EOF +- else +- return r.push(new Buffer('x')); +- }; +- +- var results = []; +- function flow() { +- var chunk; +- while (null !== (chunk = r.read())) +- results.push(chunk + ''); +- } +- r.on('readable', flow); +- r.on('end', function() { +- results.push('EOF'); +- }); +- flow(); +- +- process.on('exit', function() { +- assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); +- console.log('ok'); +- }); +-} +diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js +index 7c96ffe..04a96f5 100644 +--- a/test/simple/test-stream2-readable-from-list.js ++++ b/test/simple/test-stream2-readable-from-list.js +@@ -21,7 +21,7 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var fromList = require('_stream_readable')._fromList; ++var fromList = require('../../lib/_stream_readable')._fromList; + + // tiny node-tap lookalike. + var tests = []; +diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js +index 675da8e..51fd3d5 100644 +--- a/test/simple/test-stream2-readable-legacy-drain.js ++++ b/test/simple/test-stream2-readable-legacy-drain.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Stream = require('stream'); ++var Stream = require('../../'); + var Readable = Stream.Readable; + + var r = new Readable(); +diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js +index 7314ae7..c971898 100644 +--- a/test/simple/test-stream2-readable-non-empty-end.js ++++ b/test/simple/test-stream2-readable-non-empty-end.js +@@ -21,7 +21,7 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var Readable = require('_stream_readable'); ++var Readable = require('../../lib/_stream_readable'); + + var len = 0; + var chunks = new Array(10); +diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js +index 2e5cf25..fd8a3dc 100644 +--- a/test/simple/test-stream2-readable-wrap-empty.js ++++ b/test/simple/test-stream2-readable-wrap-empty.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); ++var Readable = require('../../lib/_stream_readable'); + var EE = require('events').EventEmitter; + + var oldStream = new EE(); +diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js +index 90eea01..6b177f7 100644 +--- a/test/simple/test-stream2-readable-wrap.js ++++ b/test/simple/test-stream2-readable-wrap.js +@@ -22,8 +22,8 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var EE = require('events').EventEmitter; + + var testRuns = 0, completedRuns = 0; +diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js +index 5d2c32a..685531b 100644 +--- a/test/simple/test-stream2-set-encoding.js ++++ b/test/simple/test-stream2-set-encoding.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var util = require('util'); + + // tiny node-tap lookalike. +diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js +index 9c9ddd8..a0cacc6 100644 +--- a/test/simple/test-stream2-transform.js ++++ b/test/simple/test-stream2-transform.js +@@ -21,8 +21,8 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var PassThrough = require('_stream_passthrough'); +-var Transform = require('_stream_transform'); ++var PassThrough = require('../../').PassThrough; ++var Transform = require('../../').Transform; + + // tiny node-tap lookalike. + var tests = []; +diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js +index d66dc3c..365b327 100644 +--- a/test/simple/test-stream2-unpipe-drain.js ++++ b/test/simple/test-stream2-unpipe-drain.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + var crypto = require('crypto'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js +index 99f8746..17c92ae 100644 +--- a/test/simple/test-stream2-unpipe-leak.js ++++ b/test/simple/test-stream2-unpipe-leak.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + + var chunk = new Buffer('hallo'); + +diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js +index 704100c..209c3a6 100644 +--- a/test/simple/test-stream2-writable.js ++++ b/test/simple/test-stream2-writable.js +@@ -20,8 +20,8 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var W = require('_stream_writable'); +-var D = require('_stream_duplex'); ++var W = require('../../').Writable; ++var D = require('../../').Duplex; + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js +index b91bde3..2f72c15 100644 +--- a/test/simple/test-stream3-pause-then-read.js ++++ b/test/simple/test-stream3-pause-then-read.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var stream = require('stream'); ++var stream = require('../../'); + var Readable = stream.Readable; + var Writable = stream.Writable; + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..19ab358 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,951 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + + +/**/ +var debug = require('util'); +if (debug && debug.debuglog) { + debug = debug.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + var Duplex = require('./_stream_duplex'); + + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + var Duplex = require('./_stream_duplex'); + + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (util.isString(chunk) && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (util.isNullOrUndefined(chunk)) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + if (!addToFront) + state.reading = false; + + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) + state.buffer.unshift(chunk); + else + state.buffer.push(chunk); + + if (state.needReadable) + emitReadable(stream); + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (isNaN(n) || util.isNull(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; + + if (!util.isNumber(n) || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) + endReadable(this); + else + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) + endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } + + if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + var ret; + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (util.isNull(ret)) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) + endReadable(this); + + if (!util.isNull(ret)) + this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && + (!dest._writableState || dest._writableState.needDrain)) + ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + debug('false write response, pause', + src._readableState.awaitDrain); + src._readableState.awaitDrain++; + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + var self = this; + process.nextTick(function() { + debug('readable nexttick read 0'); + self.read(0); + }); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + if (!state.reading) { + debug('resume read 0'); + this.read(0); + } + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(function() { + resume_(stream, state); + }); + } +} + +function resume_(stream, state) { + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) + stream.read(0); +} + +Readable.prototype.pause = function() { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + debug('wrapped data'); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !chunk.length) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..905c5e4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,209 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (!util.isNullOrUndefined(data)) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('prefinish', function() { + if (util.isFunction(this._flush)) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..db8539c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,477 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + var Duplex = require('./_stream_duplex'); + + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; + } + + if (util.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (!util.isFunction(cb)) + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function() { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function() { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && + !state.corked && + !state.finished && + !state.bufferProcessing && + state.buffer.length) + clearBuffer(this, state); + } +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + util.isString(chunk)) { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (util.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing || state.corked) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, false, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + state.pendingcb--; + cb(er); + }); + else { + state.pendingcb--; + cb(er); + } + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && + !state.corked && + !state.bufferProcessing && + state.buffer.length) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + if (stream._writev && state.buffer.length > 1) { + // Fast case, write everything using _writev() + var cbs = []; + for (var c = 0; c < state.buffer.length; c++) + cbs.push(state.buffer[c].callback); + + // count the one we are adding, as well. + // TODO(isaacs) clean this up + state.pendingcb++; + doWrite(stream, state, true, state.length, state.buffer, '', function(err) { + for (var i = 0; i < cbs.length; i++) { + state.pendingcb--; + cbs[i](err); + } + }); + + // Clear buffer + state.buffer = []; + } else { + // Slow case, write chunks one-by-one + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; + } + + state.bufferProcessing = false; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); + +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (util.isFunction(chunk)) { + cb = chunk; + chunk = null; + encoding = null; + } else if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; + } + + if (!util.isNullOrUndefined(chunk)) + this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else + prefinish(stream, state); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..9074e8e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..b673333 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,37 @@ +{ + "name": "core-util-is", + "version": "1.0.1", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.1", + "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz", + "_from": "core-util-is@>=1.0.0 <1.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/util.js new file mode 100644 index 0000000..007fa10 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/core-util-is/util.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && objectToString(e) === '[object Error]'; +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..933382a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.1 <2.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/build/build.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/component.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..fb1eb37 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,38 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies 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 THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@0.0.1", + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "_from": "isarray@0.0.1" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..ee70702 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "readme": "**string_decoder.js** (`require('string_decoder')`) from Node.js core\n\nCopyright Joyent, Inc. and other Node contributors. See LICENCE file for details.\n\nVersion numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**\n\nThe *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_from": "string_decoder@>=0.10.0 <0.11.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/package.json new file mode 100644 index 0000000..5e945ce --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/package.json @@ -0,0 +1,46 @@ +{ + "name": "readable-stream", + "version": "1.1.13", + "description": "Streams3, a user-land copy of the stream library from Node.js v0.11.x", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "devDependencies": { + "tap": "~0.2.6" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "readme": "# readable-stream\n\n***Node-core streams for userland***\n\n[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)\n[![NPM](https://nodei.co/npm-dl/readable-stream.png&months=6&height=3)](https://nodei.co/npm/readable-stream/)\n\nThis package is a mirror of the Streams2 and Streams3 implementations in Node-core.\n\nIf you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *\"stream\"* module in Node-core.\n\n**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12.\n\n**readable-stream** uses proper patch-level versioning so if you pin to `\"~1.0.0\"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `\"~1.1.0\"`\n\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream#readme", + "_id": "readable-stream@1.1.13", + "_shasum": "f6eef764f514c89e2b9e23146a75ba106756d23e", + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.13.tgz", + "_from": "readable-stream@>=1.1.13 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..09b8bf5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js @@ -0,0 +1,7 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = require('stream'); +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/package.json new file mode 100644 index 0000000..7591006 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/package.json @@ -0,0 +1,51 @@ +{ + "name": "are-we-there-yet", + "version": "1.0.4", + "description": "Keep track of the overall completion of many dispirate processes", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/iarna/are-we-there-yet.git" + }, + "author": { + "name": "Rebecca Turner", + "url": "http://re-becca.org" + }, + "license": "ISC", + "bugs": { + "url": "https://github.com/iarna/are-we-there-yet/issues" + }, + "homepage": "https://github.com/iarna/are-we-there-yet", + "devDependencies": { + "tap": "^0.4.13" + }, + "dependencies": { + "delegates": "^0.1.0", + "readable-stream": "^1.1.13" + }, + "gitHead": "7ce414849b81ab83935a935275def01914821bde", + "_id": "are-we-there-yet@1.0.4", + "_shasum": "527fe389f7bcba90806106b99244eaa07e886f85", + "_from": "are-we-there-yet@>=1.0.0 <1.1.0", + "_npmVersion": "2.0.0", + "_npmUser": { + "name": "iarna", + "email": "me@re-becca.org" + }, + "maintainers": [ + { + "name": "iarna", + "email": "me@re-becca.org" + } + ], + "dist": { + "shasum": "527fe389f7bcba90806106b99244eaa07e886f85", + "tarball": "http://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.0.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.0.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/tracker.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/tracker.js new file mode 100644 index 0000000..18c31c3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/tracker.js @@ -0,0 +1,56 @@ +"use strict" +var test = require("tap").test +var Tracker = require("../index.js").Tracker + +var timeoutError = new Error("timeout") +var testEvent = function (obj,event,next) { + var timeout = setTimeout(function(){ + obj.removeListener(event, eventHandler) + next(timeoutError) + }, 10) + var eventHandler = function () { + var args = Array.prototype.slice.call(arguments) + args.unshift(null) + clearTimeout(timeout) + next.apply(null, args) + } + obj.once(event, eventHandler) +} + +test("Tracker", function (t) { + t.plan(10) + + var name = "test" + var track = new Tracker(name) + + t.is(track.completed(), 0, "Nothing todo is 0 completion") + + var todo = 100 + track = new Tracker(name, todo) + t.is(track.completed(), 0, "Nothing done is 0 completion") + + testEvent(track, "change", afterCompleteWork) + track.completeWork(100) + function afterCompleteWork(er, onChangeName) { + t.is(er, null, "completeWork: on change event fired") + t.is(onChangeName, name, "completeWork: on change emits the correct name") + } + t.is(track.completed(), 1, "completeWork: 100% completed") + + testEvent(track, "change", afterAddWork) + track.addWork(100) + function afterAddWork(er, onChangeName) { + t.is(er, null, "addWork: on change event fired") + t.is(onChangeName, name, "addWork: on change emits the correct name") + } + t.is(track.completed(), 0.5, "addWork: 50% completed") + + + track.completeWork(200) + t.is(track.completed(), 1, "completeWork: Over completion is still only 100% complete") + + track = new Tracker(name, todo) + track.completeWork(50) + track.finish() + t.is(track.completed(), 1, "finish: Explicitly finishing moves to 100%") +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackergroup.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackergroup.js new file mode 100644 index 0000000..a64e121 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackergroup.js @@ -0,0 +1,87 @@ +"use strict" +var test = require("tap").test +var Tracker = require("../index.js").Tracker +var TrackerGroup = require("../index.js").TrackerGroup + +var timeoutError = new Error("timeout") +var testEvent = function (obj,event,next) { + var timeout = setTimeout(function(){ + obj.removeListener(event, eventHandler) + next(timeoutError) + }, 10) + var eventHandler = function () { + var args = Array.prototype.slice.call(arguments) + args.unshift(null) + clearTimeout(timeout) + next.apply(null, args) + } + obj.once(event, eventHandler) +} + +test("TrackerGroup", function (t) { + var name = "test" + + var track = new TrackerGroup(name) + t.is(track.completed(), 0, "Nothing todo is 0 completion") + testEvent(track, "change", afterFinishEmpty) + track.finish() + var a, b + function afterFinishEmpty(er, onChangeName) { + t.is(er, null, "finishEmpty: on change event fired") + t.is(onChangeName, name, "finishEmpty: on change emits the correct name") + t.is(track.completed(), 1, "finishEmpty: Finishing an empty group actually finishes it") + + track = new TrackerGroup(name) + a = track.newItem("a", 10, 1) + b = track.newItem("b", 10, 1) + t.is(track.completed(), 0, "Initially empty") + testEvent(track, "change", afterCompleteWork) + a.completeWork(5) + } + function afterCompleteWork(er, onChangeName) { + t.is(er, null, "on change event fired") + t.is(onChangeName, "a", "on change emits the correct name") + t.is(track.completed(), 0.25, "Complete half of one is a quarter overall") + testEvent(track, "change", afterFinishAll) + track.finish() + } + function afterFinishAll(er, onChangeName) { + t.is(er, null, "finishAll: on change event fired") + t.is(onChangeName, name, "finishAll: on change emits the correct name") + t.is(track.completed(), 1, "Finishing everything ") + + track = new TrackerGroup(name) + a = track.newItem("a", 10, 2) + b = track.newItem("b", 10, 1) + t.is(track.completed(), 0, "weighted: Initially empty") + testEvent(track, "change", afterWeightedCompleteWork) + a.completeWork(5) + } + function afterWeightedCompleteWork(er, onChangeName) { + t.is(er, null, "weighted: on change event fired") + t.is(onChangeName, "a", "weighted: on change emits the correct name") + t.is(Math.round(track.completed()*100), 33, "weighted: Complete half of double weighted") + testEvent(track, "change", afterWeightedFinishAll) + track.finish() + } + function afterWeightedFinishAll(er, onChangeName) { + t.is(er, null, "weightedFinishAll: on change event fired") + t.is(onChangeName, name, "weightedFinishAll: on change emits the correct name") + t.is(track.completed(), 1, "weightedFinishaAll: Finishing everything ") + + track = new TrackerGroup(name) + a = track.newGroup("a", 10) + b = track.newGroup("b", 10) + var a1 = a.newItem("a.1",10) + a1.completeWork(5) + t.is(track.completed(), 0.25, "nested: Initially quarter done") + testEvent(track, "change", afterNestedComplete) + b.finish() + } + function afterNestedComplete(er, onChangeName) { + t.is(er, null, "nestedComplete: on change event fired") + t.is(onChangeName, "b", "nestedComplete: on change emits the correct name") + t.is(track.completed(), 0.75, "nestedComplete: Finishing everything ") + t.end() + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackerstream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackerstream.js new file mode 100644 index 0000000..72b6043 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/are-we-there-yet/test/trackerstream.js @@ -0,0 +1,65 @@ +"use strict" +var test = require("tap").test +var util = require("util") +var stream = require("readable-stream") +var TrackerStream = require("../index.js").TrackerStream + +var timeoutError = new Error("timeout") +var testEvent = function (obj,event,next) { + var timeout = setTimeout(function(){ + obj.removeListener(event, eventHandler) + next(timeoutError) + }, 10) + var eventHandler = function () { + var args = Array.prototype.slice.call(arguments) + args.unshift(null) + clearTimeout(timeout) + next.apply(null, args) + } + obj.once(event, eventHandler) +} + +var Sink = function () { + stream.Writable.apply(this,arguments) +} +util.inherits(Sink, stream.Writable) +Sink.prototype._write = function (data, encoding, cb) { + cb() +} + +test("TrackerStream", function (t) { + t.plan(9) + + var name = "test" + var track = new TrackerStream(name) + + t.is(track.completed(), 0, "Nothing todo is 0 completion") + + var todo = 10 + track = new TrackerStream(name, todo) + t.is(track.completed(), 0, "Nothing done is 0 completion") + + track.pipe(new Sink()) + + testEvent(track, "change", afterCompleteWork) + track.write("0123456789") + function afterCompleteWork(er, onChangeName) { + t.is(er, null, "write: on change event fired") + t.is(onChangeName, name, "write: on change emits the correct name") + t.is(track.completed(), 1, "write: 100% completed") + + testEvent(track, "change", afterAddWork) + track.addWork(10) + } + function afterAddWork(er, onChangeName) { + t.is(er, null, "addWork: on change event fired") + t.is(track.completed(), 0.5, "addWork: 50% completed") + + testEvent(track, "change", afterAllWork) + track.write("ABCDEFGHIJKLMNOPQRST") + } + function afterAllWork(er) { + t.is(er, null, "allWork: on change event fired") + t.is(track.completed(), 1, "allWork: 100% completed") + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/.npmignore new file mode 100644 index 0000000..df22a16 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/.npmignore @@ -0,0 +1,32 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript + +# Editor cruft +*~ +.#* diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/LICENSE new file mode 100644 index 0000000..e756052 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2014, Rebecca Turner + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md new file mode 100644 index 0000000..fb9eb0a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md @@ -0,0 +1,161 @@ +gauge +===== + +A nearly stateless terminal based horizontal guage / progress bar. + +```javascript +var Gauge = require("gauge") + +var gauge = new Gauge() + +gauge.show("test", 0.20) + +gauge.pulse("this") + +gauge.hide() +``` + +![](example.png) + + +### `var gauge = new Gauge([options], [ansiStream])` + +* **options** – *(optional)* An option object. (See [below] for details.) +* **ansiStream** – *(optional)* A stream that's been blessed by the [ansi] + module to include various commands for controlling the cursor in a terminal. + +[ansi]: https://www.npmjs.com/package/ansi +[below]: #theme-objects + +Constructs a new gauge. Gauges are drawn on a single line, and are not drawn +if the current terminal isn't a tty. + +The **options** object can have the following properties, all of which are +optional: + +* maxUpdateFrequency: defaults to 50 msec, the gauge will not be drawn more + than once in this period of time. This applies to `show` and `pulse` + calls, but if you `hide` and then `show` the gauge it will draw it + regardless of time since last draw. +* theme: defaults to Gauge.unicode` if the terminal supports + unicode according to [has-unicode], otherwise it defaults to `Gauge.ascii`. + Details on the [theme object](#theme-objects) are documented elsewhere. +* template: see [documentation elsewhere](#template-objects) for + defaults and details. + +[has-unicode]: https://www.npmjs.com/package/has-unicode + +If **ansiStream** isn't passed in, then one will be constructed from stderr +with `ansi(process.stderr)`. + +### `gauge.show([name, [completed]])` + +* **name** – *(optional)* The name of the current thing contributing to progress. Defaults to the last value used, or "". +* **completed** – *(optional)* The portion completed as a value between 0 and 1. Defaults to the last value used, or 0. + +If `process.stdout.isTTY` is false then this does nothing. If completed is 0 +and `gauge.pulse` has never been called, then similarly nothing will be printed. + +If `maxUpdateFrequency` msec haven't passed since the last call to `show` or +`pulse` then similarly, nothing will be printed. (Actually, the update is +deferred until `maxUpdateFrequency` msec have passed and if nothing else has +happened, the gauge update will happen.) + +### `gauge.hide()` + +Removes the gauge from the terminal. + +### `gauge.pulse([name])` + +* **name** – *(optional)* The specific thing that triggered this pulse + +Spins the spinner in the gauge to show output. If **name** is included then +it will be combined with the last name passed to `gauge.show` using the +subsection property of the theme (typically a right facing arrow). + +### `gauge.disable()` + +Hides the gauge and ignores further calls to `show` or `pulse`. + +### `gauge.enable()` + +Shows the gauge and resumes updating when `show` or `pulse` is called. + +### `gauge.setTheme(theme)` + +Change the active theme, will be displayed with the next show or pulse + +### `gauge.setTemplate(template)` + +Change the active template, will be displayed with the next show or pulse + +### Theme Objects + +There are two theme objects available as a part of the module, `Gauge.unicode` and `Gauge.ascii`. +Theme objects have the follow properties: + +| Property | Unicode | ASCII | +| ---------- | ------- | ----- | +| startgroup | ╢ | \| | +| endgroup | ╟ | \| | +| complete | █ | # | +| incomplete | ░ | - | +| spinner | ▀▐▄▌ | -\\\|/ | +| subsection | → | -> | + +*startgroup*, *endgroup* and *subsection* can be as many characters as you want. + +*complete* and *incomplete* should be a single character width each. + +*spinner* is a list of characters to use in turn when displaying an activity +spinner. The Gauge will spin as many characters as you give here. + +### Template Objects + +A template is an array of objects and strings that, after being evaluated, +will be turned into the gauge line. The default template is: + +```javascript +[ + {type: "name", separated: true, maxLength: 25, minWidth: 25, align: "left"}, + {type: "spinner", separated: true}, + {type: "startgroup"}, + {type: "completionbar"}, + {type: "endgroup"} +] +``` + +The various template elements can either be **plain strings**, in which case they will +be be included verbatum in the output. + +If the template element is an object, it can have the following keys: + +* *type* can be: + * `name` – The most recent name passed to `show`; if this is in response to a + `pulse` then the name passed to `pulse` will be appended along with the + subsection property from the theme. + * `spinner` – If you've ever called `pulse` this will be one of the characters + from the spinner property of the theme. + * `startgroup` – The `startgroup` property from the theme. + * `completionbar` – This progress bar itself + * `endgroup` – The `endgroup` property from the theme. +* *separated* – If true, the element will be separated with spaces from things on + either side (and margins count as space, so it won't be indented), but only + if its included. +* *maxLength* – The maximum length for this element. If its value is longer it + will be truncated. +* *minLength* – The minimum length for this element. If its value is shorter it + will be padded according to the *align* value. +* *align* – (Default: left) Possible values "left", "right" and "center". Works + as you'd expect from word processors. +* *length* – Provides a single value for both *minLength* and *maxLength*. If both + *length* and *minLength or *maxLength* are specifed then the latter take precedence. + +### Tracking Completion + +If you have more than one thing going on that you want to track completion +of, you may find the related [are-we-there-yet] helpful. It's `change` +event can be wired up to the `show` method to get a more traditional +progress bar interface. + +[are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md~ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md~ new file mode 100644 index 0000000..eec841b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/README.md~ @@ -0,0 +1,153 @@ +gauge +===== + +A nearly stateless terminal based horizontal guage / progress bar. + +```javascript +var Gauge = require("gauge") + +var gauge = new Gauge() + +gauge.show("test", 0.20) + +gauge.pulse("this") + +gauge.hide() +``` + +![](example.png) + + +### `var gauge = new Gauge([options], [ansiStream])` + +* **options** – *(optional)* An option object. (See [below] for details.) +* **ansiStream** – *(optional)* A stream that's been blessed by the [ansi] + module to include various commands for controlling the cursor in a terminal. + +[ansi]: https://www.npmjs.com/package/ansi +[below]: #theme-objects + +Constructs a new gauge. Gauges are drawn on a single line, and are not drawn +if the current terminal isn't a tty. + +The **options** object can have the following properties, all of which are +optional: + +* maxUpdateFrequency: defaults to 50 msec, the gauge will not be drawn more + than once in this period of time. This applies to `show` and `pulse` + calls, but if you `hide` and then `show` the gauge it will draw it + regardless of time since last draw. +* theme: defaults to Gauge.unicode` if the terminal supports + unicode according to [has-unicode], otherwise it defaults to `Gauge.ascii`. + Details on the [theme object](#theme-objects) are documented elsewhere. +* template: see [documentation elsewhere](#template-objects) for + defaults and details. + +[has-unicode]: https://www.npmjs.com/package/has-unicode + +If **ansiStream** isn't passed in, then one will be constructed from stderr +with `ansi(process.stderr)`. + +### `gauge.show([name, [completed]])` + +* **name** – *(optional)* The name of the current thing contributing to progress. Defaults to the last value used, or "". +* **completed** – *(optional)* The portion completed as a value between 0 and 1. Defaults to the last value used, or 0. + +If `process.stdout.isTTY` is false then this does nothing. If completed is 0 +and `gauge.pulse` has never been called, then similarly nothing will be printed. + +If `maxUpdateFrequency` msec haven't passed since the last call to `show` or +`pulse` then similarly, nothing will be printed. (Actually, the update is +deferred until `maxUpdateFrequency` msec have passed and if nothing else has +happened, the gauge update will happen.) + +### `gauge.hide()` + +Removes the gauge from the terminal. + +### `gauge.pulse([name])` + +* **name** – *(optional)* The specific thing that triggered this pulse + +Spins the spinner in the gauge to show output. If **name** is included then +it will be combined with the last name passed to `gauge.show` using the +subsection property of the theme (typically a right facing arrow). + +### `gauge.disable()` + +Hides the gauge and ignores further calls to `show` or `pulse`. + +### `gauge.enable()` + +Shows the gauge and resumes updating when `show` or `pulse` is called. + +### Theme Objects + +There are two theme objects available as a part of the module, `Gauge.unicode` and `Gauge.ascii`. +Theme objects have the follow properties: + +| Property | Unicode | ASCII | +| ---------- | ------- | ----- | +| startgroup | ╢ | \| | +| endgroup | ╟ | \| | +| complete | █ | # | +| incomplete | ░ | - | +| spinner | ▀▐▄▌ | -\\\|/ | +| subsection | → | -> | + +*startgroup*, *endgroup* and *subsection* can be as many characters as you want. + +*complete* and *incomplete* should be a single character width each. + +*spinner* is a list of characters to use in turn when displaying an activity +spinner. The Gauge will spin as many characters as you give here. + +### Template Objects + +A template is an array of objects and strings that, after being evaluated, +will be turned into the gauge line. The default template is: + +```javascript +[ + {type: "name", separated: true, maxLength: 25, minWidth: 25, align: "left"}, + {type: "spinner", separated: true}, + {type: "startgroup"}, + {type: "completionbar"}, + {type: "endgroup"} +] +``` + +The various template elements can either be **plain strings**, in which case they will +be be included verbatum in the output. + +If the template element is an object, it can have the following keys: + +* *type* can be: + * `name` – The most recent name passed to `show`; if this is in response to a + `pulse` then the name passed to `pulse` will be appended along with the + subsection property from the theme. + * `spinner` – If you've ever called `pulse` this will be one of the characters + from the spinner property of the theme. + * `startgroup` – The `startgroup` property from the theme. + * `completionbar` – This progress bar itself + * `endgroup` – The `endgroup` property from the theme. +* *separated* – If true, the element will be separated with spaces from things on + either side (and margins count as space, so it won't be indented), but only + if its included. +* *maxLength* – The maximum length for this element. If its value is longer it + will be truncated. +* *minLength* – The minimum length for this element. If its value is shorter it + will be padded according to the *align* value. +* *align* – (Default: left) Possible values "left", "right" and "center". Works + as you'd expect from word processors. +* *length* – Provides a single value for both *minLength* and *maxLength*. If both + *length* and *minLength or *maxLength* are specifed then the latter take precedence. + +### Tracking Completion + +If you have more than one thing going on that you want to track completion +of, you may find the related [are-we-there-yet] helpful. It's `change` +event can be wired up to the `show` method to get a more traditional +progress bar interface. + +[are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/example.png b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/example.png new file mode 100644 index 0000000000000000000000000000000000000000..2667cac459e177fb25252516d08c61f978e7b432 GIT binary patch literal 19689 zcmeFYRa9I}-!IsN5FiA%V8Mes1ZdoYyL+(U*0=^paCZ-l6WpEPE{#KQZ7jG$I8C1S zdB3yHnl)=K=3*}9cJEzPyK4Wt>SrCQq#%X*n(#FM06>-gD6RqkyaWLNaP~;>uq(v( zHeLY08(d2WRcz|X8J}~Wf5fvE{4S1ivb-BWyTPrV-yPdp=PbhoU`}H-^Z`7yjJ;Exv&3R zkMLUjasEBx%>kfYta%y0sD|us<6F*3KM|Z7lhQ-=h>Rf&I1?sd)wYTK$;Zx)^N`!x zfl!vC*O1V2XVLORKSW#}f(pPwc6=?>GxqI<7SQ-!muv*Ve**6ERgE(O)&trnb#f{s zKrCaYC3`7#Cmp*DQ(b82+1Gh=0DEFDRsr01ve5Anlfq7(*DpfKZi(NKZe(J3RZeLW zhqRDo#bgSge3GE=DWDVTk-l$8p)+CAF0Ex_9G0Lr70UV;)0=khm$d08>zd>adgC)+ zwAb~WR(h<`PCd0ol7bTg-mzx*Sly%8#UV9tg=P~bn>j&^>->?FN;exmE zU$B)@4`EpJc}5%QCMoTs96=lm>>Ngr6fnoa2t%WH93}oha(Oa|h=Ewn2to|rILU=) zF9OKFai9vMWxvB_*$l1UI^F0Z*YIx?OCTU&|MWyFw9M^2ElC>{=kOuuM!$rWOvXI0 z*dko=ysLDckq*%%q|Ir{B*3&?>xE_l25=~{`|>>5@h6X-?;(=Kn=$6>BFt4$5sj@7 z0gbWI*Aa0u1bkFO;qNZnl2B+;O3~&w-^^}(B=9?IBjaY5>_hDrp*=zH^+)ch%=gzO zgFjikKe%5{E~Nof`eWq5F;@~pB0PI!y>3njP|rFIF&w{q9vPQf97ga^dUBCt@X`rT zv$W5ero`s|%0o2QBjCWzk0aP-RMVU3n5-;RumLR+_XCr%g}fE!B--r!R$60({bI#$ zzugNf3k!%Gjm(X#AJjtj^2*704C~uN)yT$AY|Dh$xv_(WN$zs9saS0D&O5! zi%{*}X!ETJHu7zuH*LPr!`9lkV#T&!!rs{d)CsZUL|5Gy3}^SppWL(cW3~k}1#}~Y zC$Rl#H_;H1I(^KMB)&nrUBJ@)Lei;I#W62&_)-HsW!|zB&bnJc=44*Zogx!CH&;Ts z$*hZ~Rhj63@Idf@<%tbw9rQ)%u0w>`O`+UWXm*!J7Dcb6#zZ%IC!)2bGr`DKc2*`_yCM}9fjBl8TQ5Dd=gkKH z2K|QXhR7%Es`z;^Vyf7Wgj6VTd~^Xl6x(sHrFEt6r3^?>u{VQoPC^fx>l70RZf))jf|X>3N5g^_-VxaGq83NPW6WW7)qgH;%sBtNyYK$r|X$X8@EC+rs0Gn6f6@HK^lRL`O!G||_%Mn1J z9l;gR9ibaBzFFJv5xp6u%UkZcROd)K-T%X@*m)*=8ogvy?WweL`ebfkTB}gG;#3KH zj&m*p%&S|Ycb;MX2q zG_ihJ8ZnF9F}h4a{pRvuW<|H$-=g)xgpUr zEE7USPZR#1)@)*|Dk0w&jD9N3v5q*j8%M4SQ1Vh*6C7|C#4a*ncpJ?%k_JyMh{LDJ9v5s~8s8e%%CYJd6Q5PdUh``C zFY>vgM7qwp^|q-;sC;Sq{>v0CuUh7=@UHako$mS2K*6lR+i0U`h9sH9U!&@xd=$PZ z3@ZG}u;cpylmb>bwXcafoH}Z6IdyHv|H!p2KQNx_SY}*iU%qM*$TnpU<+B{md*|lk zmUPd2&5T|kRo$-;&8#S(m}K#F*MtS0C2G!~!eYgIg<$2r&G1(19?2)_*89ZeQh)8& zR`4yt9qw)2{g0deyW~5e*AwU;QHqe?B7u-H@aJ*FkzOO~;Dh+I_)je!P^*KnP169;agA^MjwpnkNYI;XEh66dZc+ReyeQLrnENeUh9e z`c>3;{b<{6*sb)Z=7~maMXhd=%XR~W0wn*_!A9H$%a8dV%#T**2T6v(nuXD*st2N{{V#|^{ec;IB52H(cC&M^<_&}#(Wm{bxsv$izJJDVQ$_lgTFj1G}p?TUvGxRE%z*Yv}FGd z{WW!$er`YG#dVE${HQZnaaa;oVpZ%~Qod4HXD^ScLs`D}OUTx*AFcx)wJxcy1&tjI zkMu=wPq4v5*28^SH+gV+G!JR9fE5Vzi|wuo49v5$TNd{5^wAXiB({4x*q=_cOc?!W zd?~e!+=gvNGow(>E5TcLIDNABFcl~tQ1FMt(!w*%;=`&?y2F*^a6;0RGx;ua20D*l z{Y=Z{1;RB74Rf;rzwh9!%A;BTu!}94ZGSnB9`Ee$c>}kZJu9(bSt*m`^%A?r7b4@Q^(?xm+=`ve4HFvu z!#}@0?^6A%qUFf(V)I_$Fe_P6T(SLv*-OSt=S=Qe`_lQ>F3sJGJD`D_59D6u#Hpy` zgk`&O-14;ga=q`Y2@+jNV-7d|@dTMP+NIkGXUDmuXv zyW!z~&>#Y+Py!6Uc6W>Y3J&i0{l)b7#Y6&S%e8b6()bNu{%!`ttKrV^GZs#6tAl{A z_vHY9CT!O%;Fdf?m&7RQ3eKT4q;waVR)dQ0X-f8k1iIkh0}W+d3GXNATK_z z2PIJ1h5?_O_k$1*y)Y0*00@MW2vp!@!V`CYEAGc2E^o+>i!JRzE2&2-@!63VTUnS< zT%3tlTv1d^L_vf@L6lirnAV*aPeYViTvAOzLY7-zPh8H*Qi|123|~h^7*{j$i#Ud& zf~35HoSqz)vVs!5rk|Aplc>6pzKXcGO0=wohN}XDx`vp7hJK(ty|KEmhNe2Vz89@= zw4^>LQU&+3wy1@sfsMMAwU?m>cC=9RH5ZLA0~*@-t2l|Qp3ObfrGTm17s{COQS+ua=x0oL>AWu z$p=S7dBrA0M1_Y%7G*{F1;!Oxr8G1~XnQ0VRK?iT#Tq6g#h1nfJyyP z*pz1HR@CWH*q{A9DqNNjO)N?~(#Zc0OLY-g@(V?k(DNmA(#aDS0Y zcS%rjd1YknV0Wo+Voi5mW!rGsm%$3J?E03L%DjQffU26x(YkM44at>F-92@cd99@=c>aFP;Y^oiFKn5$uhf7)^6BA=K<0Fvn3CPemWODrH#CYE*Kn z3j)*#FTOFrcSV>D@gI)p#GLrrNn|i_81oVjPw9&T%{e;~oN?nTvoA(&X?LwId_D@9 zvV|>{F~9%#Jbl04Q@xz#m7il#6i{~=TeSoL9B^;>yb%C^kg>XPQ7rEVtGby##M+Ve z#KIu(Prmb`$=hqHpUJ12*mbg$3=26?#I{2#wafa>c`ZBIhN|asOA6ilQ>qdH=<9{A z$$*$O{K9Vy|JNDo+_@}th|P5>6dv+4bz;z*AiObZ^P zegtkWDfkE9yKMc~dC!f>%b& zwS0k!qGHa(VheOwslzwMOuo&N`LnDfNHZ@Zd_Vt@x9zKb{cN2}P65%0=yqz1Z9&l% zxo@i8^Kh3|Oo9X`$R6-Q8Zq9nXxU~?$Zi@kr=L}%nCp#~_vXJ*hhIU?6!!yZMgQnD zQ5xZ9#t+$4=tR#hzPFy5>#L2Q>9~J)-Xmz%=Fr`GNtGZ_l~HIKzv<5mVh+PknnLp} zZTMbaZaJ>5@mr~+YWG*jLm5QaXomFjFGP%Mrl=PZsI~T_P4S( ze61CxXJ=o1ETZIn`kDlGMsyw&d*>{WPsFb7HSkutGInBJNBLr=sC>Yixg@!65?3Jo zqj-O>>|02co)~cj9vD7O8&n%`L@{M`FkF~cBM3%B!SZqMMKrt`qxhzo>avQF6{@jM zw>;scS5V@?ZR0)38RW^N1AEinjeI=?IG0l?Dj>5#*PDuI>yX`2+%G3}EU^M;!>R5CRh&p%n8FX%R8ztBJ2Z5+n^xXzhGV1S#t)F# z$C`{w_PTedfmh%9&}=$0A*g#Nx$QrO=@>${GGV=rzWtrj21Sl%zM9Q^o_$KASlhQ7 zJzMB-e**7ELC9W>*hs3MQ?$t-n#-2`_^|Y*(}%(zr@SdA;M_Lp0XQ+xwC4r-1HyY_ z)k{GtytkG|Nuuprqh47-f2bBQQk){l{bkjz z#2ncBG41X5fy0mSo2X$5pNYg%F-V*R7ExJTaEC2=sLpOb@RPv=LC(vBnccSccE}9C z68y#Gj^-~?us3#LTUh#zFTe0A2W%kbU7plgFH+kXjZ2jSeJQj@Qa~HcD(;&2$48Lw zpasF=V<4E4+dIl&Omm^+QtOEic=P3`%gQP0UB-Pzdu3GA@V>=z+I^{Qo3U65tk#?! z=W5$lj_Ud9%FS-Qd&dz6Acl9|CS9JfcMq|uzhI?zY*n?64J$nNY$U^4HI)a`xw+nKST5LD(z|uBP>~iLw5HX z?Z~yV_FWZzmb#lkifPkxY2Z!{0Km@FCl}MfCN&i{V!V!8D+f*{R|6H~VL$Sf@!5f} z+XyKlS0g0amDwTr!kRJ6ns$mJTXPOG<#>RQD55)X$6CB*V-5o?FxIeJy+sE=2DIa^ zk5+^dANu4I4P69Fdl{BlH(F_;0K{qDG(-;_q(WCeZ_UNL(L@mr2uA||z%c0=g9IQv z6r%7$8vEFh-$DO(URNk~u=Igs!zbn2mjGdq4({n=jO!@Dx=DoPcP%wRI9Q9aUL1=r zP;p!fQv(CPHZ4xz#tt?B0CB_(Vay)q7ndQ*aw8Q-1YjUS9FdJ*-Fh#75(vh7YXBFM z2Hqq{9Ph?f6!f}`NSp6Cr}|)J)f2tKlh&U7Kq){!XcioHKkWHcLeS9I*Oy$8YBh7b zQSnZ#E#+Xr`vpKn7IYDks~&4l+(5ONY5;njS}M1QWXZ~8xqhA+ZMl{c8+jc!g_*ZBkXGP09N zu}FHub)H)TAhCDs5j0^meu_QsO>XqmPctdhjI*s63soQB5jF8xtORCgV5`^dl7~$S zQij~55(6V4)Z!`27u?)UAyNCiYKoW00Dq{QHC3sx&f-ftdhKTD&1)K!uspjUY?AJO zhhbw>C*#MCn69!H76Y5OD<6n}03Tf-kOs=e5QT;qVb%kYM@KgjN_>*KtbN$50>G3A z;KW=g&eH@VP-cVhyqR!pAyN5%8-;U-bP3!kBL<$yy%$QbF2@t^LUz}?g4-cs#c#t~B`nX#ilMT~we zU_qnbK~km^zBDFVsKW5!;o%a+>doxJ0tu7Bv}cJTta?JxP{bo_k#lOR-AVFnT%ep1 z4ToTku9Td#rGX8JvckKUfV>PS5-#mKEz>B_#l;y}yRy|9PE{+5ZLLyx*B{T(jr0+P zi$@KOe^!=kTRa#&lCTL!{vdJrM`|%GS53OaD)^r-YxSR^1;7dnR`D*UTgIJz_LX^YsL8sdl zEK`aEa&dcSap9gSTmOMG5dlyc z0z+WKFa-8{*f4$#VDeC_fz)46r^gNwgPskvs8xkq#r6W)aG@l&T0 zf0N!CXgxX`ku!h^lfwN4FIVD+zC+o^ob!7x--IK<0U&HHbufsPSM@K%y2xoT-xIK@ zS(#xG5L>;t&&}UQ3DP@c2E*$L)N%Zv4u17fz?o-uTwK98O4`{5d-71Oeqzpv`9)YV zy@1xH$vc-@IrGdr>BC*^P70A4aZwPA5|GHOaurH6a?GnRKcd8@7qK&mLTb|^e}6P^ zy)a~^%zK@G9O`Lhp&`4E=f&|Wj%rbd;M2i@E5taC41a*u;IsRAT$0E86HFpG?dld@ zQI5s396_O$Bd4*NjJi)r975uV{;XgzIwNG``_@y@cR)~4yx+uq8LzUgE)iMI@6VA^ zZ^}Fe_=i~MRDm`5RJaXmf6*0fdGKBHgkGy%wR;Y*Hnf+nFinNLQv9O|$XzldTXJL< z83IQJgG{frL`{>$>;-2sE^9}fmdGJ6p(_p8RLJ)A?bJtz@;+UrHq*jQo+Z+y4hZZ_ zwxxPGxkW5cn-p_bu9{d{W$B)%eT}+ahhlp9@qiMGD+%7e9m=J`V^l#e7RYx-gqr%ROoM@E z4ZGVt4!p%3*=_B@gcu}A8*4u0as~RMm!DI9p0lW4CX^Oak>s~-I1Q;%;*o?WR|OHj z_q(OR;%EA1WWGXm#=#6scFcldE8!k+H)V(bOEcc~kF_4MJiUv&_x(gTB#XA=4eOl& z(8?XpS`Nc~`g$F^nxq6gB6$I`OOJ|B-L9~x{d@rz`9ITJ8QqJdCeK(bGi7|rm`I%H zVFciSnYl*O){V1``E3Ays^iSU!lz;FjinMu3tx!unzt!Ip{(EY6w--qgP)`m7wPs7 zobqWi)>4BgwyJw$Sp`xLnx7VNOqVNLv!r7o%Wq_)%a%PM z$fDm;M&ijNBQc`2cuNr$} zXMqad=>uIAcBbz9ydKy>6B@j?{T93^+QFXzG~aw+Zp zLL|*E1827*VtKXe9@nr_9pH#Tl8j*-_o4Ixe7?4w$8U%g=whRiimx6#B@g z_$jwQ@&Ou|yLUe*G?^Qx=UUX*QL3r6b&k8Ui+?75wtO3LpQktz-jp>;10bstmx|`m z!M*Kslx5G_lPHWC9LkG~c{LS>CzySkVm?Nv+e&-M2zwVg8X)@yM#Y6;2@bqAqbQ=n zJHqcctLeH_2mzM;-EH%1gun8(cTfuvzoCy4jZvnI-Fn=TLzG*K{{7UavvfaCJRqbeLI@;~lN@<7=BJ509vCUu)*bAs(V#m}>%1*(wg@P;XzqK|@e^CELGNK~Iu8QGBQ( z#<@Euc@Y2Yo(3pq+vm2Wi`~alwn(s0dj8TeBHtwJzQJz60~Cvc84s-;85GV)?dks*dMCL06LAgjZL;w zk!rUppF=@o8}20*T?rWpEzTR2eLKpl@UnuJH=)#(URo^kj{Ig6E<`~z4DD!zv}vF> z;v*Q>dXQGUFd*hm`>8QAM)sO7VDy=#=AQ9ZBWn(ngqd0IsYZC44n*MIR^;oU?FG}+T0l<{0@0NJT$;q58J(;4OSK>>6xA6=Q2 z{UN#k1(k67LtVjgUETWxAxPX;zC%Rr~u^shAo%+;tXo1Wiz- ze4s?Sfiww;1NOkzpzT6pnR59?I&MJucW7l$PclpMWp0kIfPPi7>q^CFQ#juX3WSVJ znid#rvQOl!pBLcfrHQu1+aO;TsC^``^yztclBi(+@DtH^O8PV7tVEuFv~$yEVj!F7 zA5-h)rL6qC4QfWSARDmg0DB+)uf_!J!C{^Ry|<3-$o^^}pqr6!*~Y09*Zw=VRgE+}U`^50b4VFsyd)jMYSW-_||7;vUnjinhkX&!jxBN6CJt!_sJs8SeeA z@SRv7)`GPrVP^6xfy-;_mB*k~(X!seAJ7(oAM^}De$%tflUX_{msn9w8dUmnvQ2XS zg;VB+E{wc^;_;0y$QGQRHMAR2-$I97guA)smXJ?c6&}_}fAD>3)Irm6V(@uckZ0YfRcv@vzDs`FFh-`I`K^(!xdOssHa2;> zsx*xEpsDU4FqT!zJ~B?*=Rr%~P#c$ZGt`-G#!EKOu5=z_HEpi>S%fSij-19J$+R-c ze1-`%V0N`tml90Lw%JOkmagVv%Nxi7;rHYtmr&5W_bp_HnVPNj#ZTBVdShj&1xX!a z7dmF9_X*bJ{SEFe2oz+-WhAh%Zd*k&X&(Z9#I|;8<8&b0D5k)F$}0Qqb1Ppg!O%VO zf`HyT2L}#VH5?5+I!>^SG&N25^l=dFjzl1d1Ak2#=e2 z5hiIw-AjF3MM@bNnF4|Wi;E2o1!tqXn@|a4bmhq6C&j0QCu-diQy@^Uhn12O-pqb^ zI!lH9_0T*wr|#DG#rg6OdA-x=1XXDmF#H~(kWKPw>>=JO+P^m?3yLpOAZ#aTDF;a zYo+xfdUa2K4z7{%psQdj>*$A`1%YvQ`5E~4=eSi1_2Jhoi9H*_0Gn|5!7TjD;Wn~Y zsGLP?W_oGFa}v8MnvnH+ZP|7VLK{;7Tter8vNRp$4sHY@h6QnpW<90r_s5k-2lH5h z?e)jGN?Y5m$w&gcc?&w4i>k7VMyg6t@|B~g6=BBH_w@|)G^-g$`#N#3Yi0T_Qv zGB~~yb;{F}3Ecs?hJ}s){(Nj0Ia+=GHD3upJ?BfTWp^PeA#rSEd+K?Mwyx$cRau~P z^6()}I(+(N^nutf9(m2$IBzjD4fc9wXWCHIYyj;u1l8-Tg7YE#T!;iu^=pf#t1=-@ zCmXozgpoPXhd3G+H9IF&V-S_j0vQPgMNM`l89-%c+m@vIq zhEH;wG7lQ8{!u87fBA4*o6%)Q--Twtr`jI&J|tx&YiRDZiU4p%ElVM_`;%Cx1@Es} zIxNV}?95duH4`J}*i=|6*PLu$DwH}h@#ThBRRS@g1L+uycvd-kT`~1Bo(ILChCJ%``|yfh=4x6B;P>_^6uZZd~LDijI3$#dahl!GJiFqN;`sN*1o zGAVA36-1S{TM7qQ4TC}(o=^n|I$+mK9#@G6evZTY+be_K{pv4_N4tvpo`;dCd3y9B z#wzca=0|!4ayt$>%t8>PudtxnZtWlZ;&;|xS%wUVS({ktIN)3NdP;0$Yq_Rccp!o8 zA}~~hdhPoxqx^*sJ+n3h(ywlO!{vllD-B+u;4$Jee1L@R@vi*_t7hSVb5|u2eWJH3 zjXIsGK4E93WWi@$fV*8wRxsD*TF~$qwU{+*z}QpHKjZa4JxqxehUd2xd&ADULSGP2 zl5%m=p*ED5C;Ts>9jo59!!a&DMmBT9r$sv=THsyZ$t7&C6eONNICr_|j62*bT$uI{)8uwe{9lMUfsDi0q{{DdH!T9rmk+R4dN zp^v<4((i$n!&-T}KGwLp6esf~LS3+SkmkdMAM>#8qUfBpDpkCO9=21&Y3g_V@e`7g z{z&ONg^pjuq!mFjy{Mk-20gS!r{Bv&5#+f~I%;UDMn&_qa&*zt54@IjI zQmZkBgr4%Q;SSOO@ex0}2{{%f-8)F$6&ZR99Tz@Np_csiU&i0i1O5c^I zKU=UB>+i>ja6^mehb`NgFOYY`tJEL%Rl;$Tel)0FT~o}b+v^nxLn+|P6)>W8rDt@jSO%Hm1uJxnF^ z=Lw0DMdBFPJ-|EQt^IlO+J72{WW31xU6%XV!Vin-o|8IzrFi>CJXm_^~PapcZ?1=SBkhS%zLwunqd3_tU6$7HYxcr z&{7&Dd)!-&V>f}xAi)za8{nUSO+w%pqIt)n9`=P1F9)6m9aSmpc$6vbMQ82iy20Vw zNZU!L^KVn|-NC!4yO?sj53LU|P+AySfVGCrWIEZHUzz{bi{b-8_ijnpF;33wdo>f@ z%neeW#%h>m{7h^xNXjWQZ@!0z^^I>$SVl0DcO4dVG!06C)L06hHClkUg$|`L>eS@> zkII9S68)Myu_{z9lo`;s{~gA-_{DmvQC^e}JR#PzLX8fF7cL2pYA5NG05yMo8K8~6 z!m#(Y30m~b=lpSSNa!%ih$RYdg3TeylYPn|QN@4NW>2t~y8o_W5K>VflYj~T$ML;4 zAtE5gzm3#zNbo}RxVuC^cX!^K#j%1PUS%=>03@EzS%6SdllWzVR)yhrQDCvad`C2J z?q6yNBS0yO5yt}!?;{*_>Nu*kcab;V%J$=2+b>t2Ln-Je-a{-?Gcz-Fw}@7Od@Z>! z4gXnu|Hun5{t{BfM4q65R}q*{hL%|XP0|NRzU5GhC(?$o&gWUcK26SxUik2l*r+Un zcRk!Ps2LPV*ZGlnR?72+724kM3!&|+L;L@guupQ7DU-pLZPi{}9Ju-Bt~F3ywSDbp zV?rKA@&8W-_CF;}g@+=2a>}sV_Q+dJ*nta((*+g8FD@<$=jpeJk?<}iv{|;a?0j?^ zt!XdVA!q>+m(<*PLSiK0G=wZK1=;59$e>NiUt^D2I^Db zW?nqzB!tT|7hs)LZ;Vd?DdUouz*Fr}869v!_<#+1;8Y+HVi4WJE(ZD5Gn?vAhz#Jm zZ_n9DR;;0%J1)PCX{%q>ubI|RnZnB`Fn35@rex}{xkdIobfIA>fx5$}Rjc>=-%_7X zQ}<{P*@?Hh&PC+8nA}U7o72pK_Nriv%lTgIO)uWW_>Tr=m(QKdz{N!dpuj6(nJ_fj zW#3z{?pxMrMJg{##77-&jdUzZ7;$}8wl$&FspEVSJuY z_3PMK9@n=DXV8SWd1L)FO+!N@C66yL;mZ;@-FGXxH5V)G3-tI_gE??2<0^F~k6WLJ5FrZ`tr=E?1|a&awE`BR zhk0*}6bdW`D}~?&O*^FTu|G6)9E^Z4Nu@Cy?ZC-eA>6^DGN1UU=y>>#?YLd zX`1QEyj~ylnZHx&LnryVMB!3~a@B2K1xu6ucc54A)8u|cH)`4jj4!9Ch3`Ww?`ui3un~ZPS#4XHdMXX5-im8dRIaQkK$uXGx zgt5V5S#MZ?ZlS~uCmnk~$A5Dyoyg#3!sB)H={lpp%tePwaVb(mCR7ICl=jZu^gA3z;=1g?=r*EdjY(~^)nXrSagHob0Q9~p`3-Vm08ur;i0Ai_4hR*Awy z>-VWl9UP%!I!%HN@W(Z&E)-H-Qe;-r!1&`tYq0Ty6#?wM0ND!Nrr<;lDGtwxx7-Fzk=>ol~arlONjS_ryiw;kJ> zQsPv~*~s;bHEEV*&l|+usELye7%j9U3W`+P7*GbWi*+VU29VUFf>C{$0X^EFfb0ub zhJL)mtbZ6qZpy!mg66-Bg5kf6;uIA-6XhE;#*AS6{D<`Uye~# zbIWOaQw#YLwko+ga=UB;j^94V6(S{*@*B*uDy=s{Boc%R>39wSXgb&kXR|I^uKfJj za;(;?B4g#V4;t16@$iQzwVl9a)1JIaCP>|xA@)wQvt8$8j#DTt-goIEp8vX&gjZVG z;=VqM_dEqcfBQuKGX;Nip?4-CXvI&Dylg;^cwIjpO7mP8Eor#~bC6>H;;@XNn(8k- zC*4Xt$ZfE6Wzo~WSx@F1&sH2pwq--AzTsT%85Uug&r)fR34SH8p{;q=ZNwdye~uMMo4(tF8jhH`nVU1H-rp^6E2WLvFL_g_cq1^ft>?y-p^mxqT!VWJrf54Dx19& zndVt%j7-LvyXp@jl+f zh&QqVS4f1u-4%*o9T>l7Yue9{`kGj=%!mgYbSbdmm^Ju*Ltt=(v5>;kxjytK#Zp(8 z+*YX+w0x)K*PK;nny0l-(7=E@?u2oTo~Zc1)sXB2qa+c0h8R!9l}6MNxJM^ej@u=V zL5JGv+PAm4gnoo53#`%0Z!ahXxg`ULcFX4b)kjs>KTUh;aYv2(Di^Zef8O?Uh^QEj z@>8IB_W0Lt?rqnee8HBm{-Rtwcr%}O`91}c-l<~xt+Ly@sBp%@O}dr~rEXr5>aU6| zU$eFyYW5a3th|aTpUKYBU$Ud~57|j1n>8CZNDL2FIpwYqi*62czbX+Uaa1F5x!V8a zMsDwAi>bf_^`FKmSu*%Aq8yEV z1~V21jqXG`NOn@+YeKXwh-f(*c_wZbHj=I=urk9;F*3v9Yg@7#Rfm0eD1D|`+Ow}! zwJNcChG2HnR$ti#%SRv0;Q>pSj&vs%Uz{f+M5lJ1JO!2|3D&F-rvm=%W$gAAUC4o% zV0P~iYc)|15$?I{V3Xlt6?($Q95*QY0Dgt2UOWk(Sd7ZQ)N<-5HOe+;{SlOKrDEf_ z_ThGwC&&;3R{Edz9*-jjum?TUzE)gfM!%h_EiHr!HEk>;Gq_-~CW7!XAEVMt%6G|t zslGmJ-|N~EurezWakKxHO?QGvFi`Zvo%z^tA4B||b^|Q;Nh#cKzVfe11LasKh#Pay zc1o9-JJ1%V8Qx{^6%>y8Gr3D-V$YKJ9|o9w_RIkFNf@<4O`Zv0-A3?uK(3%mfp;Z0 zXR6Cj19tidPu>z}X-xzx<5B)t8PlIW=HhPNGpy(fqfQwdhWg$wX)tBPoQ}U%mj&2a zWp;5cl%1qHFHa&P8K@lnO2FGkp}<|=64at9e{_^T{|IvGdD2Dr`^%>V(ra_b$`tHH zj}9||B~_0~Fx%Ux@L+uMsju$uEb$>t-=sf5ZWHKie=R?hlcS(@2PD$siPL5k0O4SFl*?PX51W z?DeTq{*!UyaL-Hl7<|Kywg9@PG@&0{YQW+qeuyCzBY2OtH9^1qh3 zU@}_PB^THD{OdX)HS5dk=kPkol6ISW$;T7&2OYpiD@dx?+g}un`jP`Sf8O_xZ*_Xb z#mx1@x-zW%X<`(QKB}E|z8QcFKRb7ZC;(|DppWcs2YwZl^EnB%d)%zl^!8H{3cZ2- zfXYS6%qj_-6r{={Cr9BC<3SJb(fm2K9IXZ_s`lQZz~>M>&UlWlZ*#0olp-@Q944fA5b;r`{@?Jr0U+cDR1V#a7^C2GwpdV1V26(CBarL$ z?BV^lG(*ABD7}uB9kHuLSGQ3WU1@n;hqSa#GuP#S!yGB zPOn8lHt~Q%49YVws9k$D;gT>5`acMCjUB17;phqrRjf2m=ODB|KU+(mI6nLxymI;o zX25-g6MGb|PIjHBa51T)V~hLW+&BK+px1U)Udj@MgS^^KH9Kq0&9M)A6e>UaoAfx* zGT)Q?ZS+%#f@i-fOfCj&NK{S?puzz*aQ0qmWjiCg5l*3LJ^l9bWy=+p*!>%pQa+Ft zBkuX3qhfMbX}sczHPlQS_?8eevC^bMt4&M1Fd}ol756@fS=*OFq`ZlMsNt)u=7%v zP43wxla>;N!4NR?hbyG%r)snH0!7Lz3KIIDj`;DGs@n)X*n2VN*kF_7Bfy}rrZTAZ zMbgE5zVD8}SOBINNaGt;?d*D@PW7oYWui6F3&c~~JPH8u5=sK6f_QiH@Q`Y?R7#GFw{iE(JJ#Z7DcvPC1U={GibTmz6C6VDeq zXTSzC(8o1|_gwL}Bdr$my z>Jft|xjrQ6Gwj`B6fKHV8^T1Yk&h^-p;3?k_~(QZY+lC)E9YQm5qg&0Unk!skx-7m z$VVN3or@V(ap($1P6;} zsH2D_XgF}>=$Ph>e~~S&UB3{{kofCL1=w`{UT7L0r1s+s#?TCo4KwRNZ>G6Ss_hEA!yo3r>)r)>B?;b(0~kmmF7I|OROc82^LSNWBq{dnrjCL08&EhF+Qtb7ll^9rze9`}GXW99>B^=+* z77jLrLbw}^LCWKoHz%8Hcv~@dtJ&DO@!U<9!5p7H$j}wn!7$P}Ta`fkD`|G05#WGNk3Y635iEL?F)zLoeQ;D~M;#pCltw}3^MrpaP9>~A8rom~_D zHE-bn7;`-v3{6Ng};xYWaU~$##TA(vmtm=9_0B)3F809+z^0dYT~grsh4LZHWcm)y6{-$+>_~(GL{^xa#6h#c2R9yi zn$=n0iRM*tVS!Ru4_zW_N4^p$`wvUCc!jJ9tdA?dB>v~jDP{(4(DBSw+&;`*Y&Vr< z{|rbZgY{(MiDVBiZZKJwg+T&4c^DD~=oP0SiT{u2q@AaThnpabPNI4L51m|M@J;Si z>=j`BD@g8#nyPxiVmTLBu3c`gJ%h~`%)k58Tvv%x*(!D0)~yd+o;RfK?fZD`R-DU;=g%>Fl5(xU#WuKm zl7S^_-nLe3zINu}|MY8HsnDNvT2t!L@S^10`T8G?#V0rTrBDB{?uiu#s84#y_4(n( zpFj6^RD8?YDrjo4!fUGBiWy#3>rYy~TVeUE3Ro;(it8w9zdP~dc8h}9fAVDxfyOmh zHh%f{-R((ditX7$*MCj;ocm)pq+i*%o9upNy8&vyQtx%@Jd!$=`ZEm^4+hS+3chzl zde#}M1bsq4_vV$aTDf=c6+zi~(&q*L=Zk{7jf-Eb zNI9#cIdhr)YUAx4QodVPw|Q5e)VF%>`@c6k@t~K4w%(#*-AR8Iebx-VwQcv$SZ6UA z;4lvG3?)CN`;dvsr8eM+%GeH2FPD4K;$f%US6-b>?>r-QWNN=j#hQxoXEh^(D}ZVgtbj9w$ug$tE&Ybe8lgLCwulAKVO=B~I%i^K<=?MK z7hiPD2F=hN4^`MyWA|A=Gq>ViEofJcjLUJ=7Re`{OS`|SL?r-MWM_5trH9z@``i3{ zbJaL2>HoROH&(0^w6A)c@vH7r|Cbdi(`B{Z>Aw~g`&rZa^JlBg#F}!u$9BN2uSx6D zKLe-4bT3|1?hA9>S9oVqPkPlw&6G_>naWEJZduZLKHYBF%;HmG`d+r(;2j-(Jr+l_ z|4!FB>LAvAp>c9Mo5s=a&%`_%6K;Jh&@bybW|q0L^6<;XhlfA6edbtJTo+g8Q6d7| zy#dq>TwwL;w81=$d4FsLXZJiT4n11l70_C{YU3Q>T1}JP+R!c)!^MYImpb`(t;qP} z!#DTX3n8U5dB0}Qj&X7SnzRbEWyGOmnW@k<1Kr#vk*PYdB{i+Wnyx|ShdTQnx~@(C z2wILSF-=Qg9;e%@8|DiX!7E9D5ds`Wd~sVa#$|c5hr*1n5B5 _L~%m_MOoXB+X zRA5P0eTJBQmjMbwvbb1>PIV&o3AcpcIDl4 zO>Z%DHr+W9F_$T*6=1XBgv`qqFP}QrEWUC;GpREER>nfH*1un89W|dh_r>qEYv9XE z`Q)Wci!^6n)7~9!92}UHX5PKebLqUJz{RmwkvGj8Ir5)k*4>9=gRfU}njp00i_ I>zopr0Q(ie!T + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md new file mode 100644 index 0000000..e9d3cc3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md @@ -0,0 +1,40 @@ +has-unicode +=========== + +Try to guess if your terminal supports unicode + +```javascript +var hasUnicode = require("has-unicode") + +if (hasUnicode()) { + // the terminal probably has unicode support +} +``` +```javascript +var hasUnicode = require("has-unicode").tryHarder +hasUnicode(function(unicodeSupported) { + if (unicodeSupported) { + // the terminal probably has unicode support + } +}) +``` + +## Detecting Unicode + +What we actually detect is UTF-8 support, as that's what Node itself supports. +If you have a UTF-16 locale then you won't be detected as unicode capable. + +### Windows + +Since at least Windows 7, `cmd` and `powershell` have been unicode capable. +As such, we report any Windows installation as unicode capable. + + +### Unix Like Operating Systems + +We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in +that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. +For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient +for most POSIX systems. While locale data can be put in `/etc/locale.conf` +as well, AFAIK it's always copied into the environment. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md~ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md~ new file mode 100644 index 0000000..e712b70 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/README.md~ @@ -0,0 +1,4 @@ +has-unicode +=========== + +Try to guess if your terminal supports unicode diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/index.js new file mode 100644 index 0000000..edceb70 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/index.js @@ -0,0 +1,18 @@ +"use strict" +var os = require("os") +var child_process = require("child_process") + +var hasUnicode = module.exports = function () { + // Supported Win32 platforms (>XP) support unicode in the console, though + // font support isn't fantastic. + if (os.type() == "Windows_NT") { return true } + + var isUTF8 = /[.]UTF-8/ + if (isUTF8.test(process.env.LC_ALL) + || process.env.LC_CTYPE == 'UTF-8' + || isUTF8.test(process.env.LANG)) { + return true + } + + return false +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/package.json new file mode 100644 index 0000000..fd552a9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/package.json @@ -0,0 +1,53 @@ +{ + "name": "has-unicode", + "version": "1.0.0", + "description": "Try to guess if your terminal supports unicode", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/iarna/has-unicode.git" + }, + "keywords": [ + "unicode", + "terminal" + ], + "author": { + "name": "Rebecca Turner", + "email": "me@re-becca.org" + }, + "license": "ISC", + "bugs": { + "url": "https://github.com/iarna/has-unicode/issues" + }, + "homepage": "https://github.com/iarna/has-unicode", + "devDependencies": { + "require-inject": "^1.1.1", + "tap": "^0.4.13" + }, + "gitHead": "a8c3dcf3be5f0c8f8e26a3e7ffea7da24344a006", + "_id": "has-unicode@1.0.0", + "_shasum": "bac5c44e064c2ffc3b8fcbd8c71afe08f9afc8cc", + "_from": "has-unicode@>=1.0.0 <2.0.0", + "_npmVersion": "2.1.11", + "_nodeVersion": "0.10.33", + "_npmUser": { + "name": "iarna", + "email": "me@re-becca.org" + }, + "maintainers": [ + { + "name": "iarna", + "email": "me@re-becca.org" + } + ], + "dist": { + "shasum": "bac5c44e064c2ffc3b8fcbd8c71afe08f9afc8cc", + "tarball": "http://registry.npmjs.org/has-unicode/-/has-unicode-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/test/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/test/index.js new file mode 100644 index 0000000..2394c14 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/has-unicode/test/index.js @@ -0,0 +1,26 @@ +"use strict" +var test = require("tap").test +var requireInject = require("require-inject") + +test("Windows", function (t) { + t.plan(1) + var hasUnicode = requireInject("../index.js", { + os: { type: function () { return "Windows_NT" } } + }) + t.is(hasUnicode(), true, "Windows is assumed to be unicode aware") +}) +test("Unix Env", function (t) { + t.plan(3) + var hasUnicode = requireInject("../index.js", { + os: { type: function () { return "Linux" } }, + child_process: { exec: function (cmd,cb) { cb(new Error("not available")) } } + }) + process.env.LANG = "en_US.UTF-8" + process.env.LC_ALL = null + t.is(hasUnicode(), true, "Linux with a UTF8 language") + process.env.LANG = null + process.env.LC_ALL = "en_US.UTF-8" + t.is(hasUnicode(), true, "Linux with UTF8 locale") + process.env.LC_ALL = null + t.is(hasUnicode(), false, "Linux without UTF8 language or locale") +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/LICENSE.txt new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/LICENSE.txt @@ -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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/README.md new file mode 100644 index 0000000..9b4891c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/README.md @@ -0,0 +1,20 @@ +# lodash.pad v3.1.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.pad` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.pad +``` + +In Node.js/io.js: + +```js +var pad = require('lodash.pad'); +``` + +See the [documentation](https://lodash.com/docs#pad) or [package source](https://github.com/lodash/lodash/blob/3.1.0-npm-packages/lodash.pad) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/index.js new file mode 100644 index 0000000..d08251b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/index.js @@ -0,0 +1,57 @@ +/** + * lodash 3.1.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.8.2 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var baseToString = require('lodash._basetostring'), + createPadding = require('lodash._createpadding'); + +/** Native method references. */ +var ceil = Math.ceil, + floor = Math.floor; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * Pads `string` on the left and right sides if it is 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 = floor(mid), + rightLength = ceil(mid); + + chars = createPadding('', rightLength, chars); + return chars.slice(0, leftLength) + string + chars; +} + +module.exports = pad; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/LICENSE.txt new file mode 100644 index 0000000..1776432 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js 1.7.0, 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/README.md new file mode 100644 index 0000000..ad04ea9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/README.md @@ -0,0 +1,20 @@ +# lodash._basetostring v3.0.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `baseToString` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash._basetostring +``` + +In Node.js/io.js: + +```js +var baseToString = require('lodash._basetostring'); +``` + +See the [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash._basetostring) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/index.js new file mode 100644 index 0000000..71ac885 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/index.js @@ -0,0 +1,25 @@ +/** + * lodash 3.0.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** + * Converts `value` to a string if it is 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) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); +} + +module.exports = baseToString; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/package.json new file mode 100644 index 0000000..ba2b33c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._basetostring/package.json @@ -0,0 +1,56 @@ +{ + "name": "lodash._basetostring", + "version": "3.0.0", + "description": "The modern build of lodash’s internal `baseToString` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "readme": "# lodash._basetostring v3.0.0\n\nThe [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `baseToString` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.\n\n## Installation\n\nUsing npm:\n\n```bash\n$ {sudo -H} npm i -g npm\n$ npm i --save lodash._basetostring\n```\n\nIn Node.js/io.js:\n\n```js\nvar baseToString = require('lodash._basetostring');\n```\n\nSee the [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash._basetostring) for more details.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash._basetostring@3.0.0", + "_shasum": "75a9a4aaaa2b2a8761111ff5431e7d83c1daf0e2", + "_resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.0.tgz", + "_from": "lodash._basetostring@>=3.0.0 <4.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/LICENSE.txt new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/LICENSE.txt @@ -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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/README.md new file mode 100644 index 0000000..0e1c731 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/README.md @@ -0,0 +1,20 @@ +# lodash._createpadding v3.6.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `createPadding` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash._createpadding +``` + +In Node.js/io.js: + +```js +var createPadding = require('lodash._createpadding'); +``` + +See the [package source](https://github.com/lodash/lodash/blob/3.6.0-npm-packages/lodash._createpadding) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/index.js new file mode 100644 index 0000000..72890bd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/index.js @@ -0,0 +1,39 @@ +/** + * lodash 3.6.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.8.2 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var repeat = require('lodash.repeat'); + +/** Native method references. */ +var ceil = Math.ceil; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * 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, ceil(padLength / chars.length)).slice(0, padLength); +} + +module.exports = createPadding; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt new file mode 100644 index 0000000..1776432 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js 1.7.0, 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md new file mode 100644 index 0000000..d2796e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md @@ -0,0 +1,20 @@ +# lodash.repeat v3.0.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.repeat` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.repeat +``` + +In Node.js/io.js: + +```js +var repeat = require('lodash.repeat'); +``` + +See the [documentation](https://lodash.com/docs#repeat) or [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash.repeat) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js new file mode 100644 index 0000000..68e1008 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js @@ -0,0 +1,57 @@ +/** + * lodash 3.0.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var baseToString = require('lodash._basetostring'); + +/** Native method references. */ +var floor = Math.floor; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * 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 = floor(n / 2); + string += string; + } while (n); + + return result; +} + +module.exports = repeat; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json new file mode 100644 index 0000000..de5156d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json @@ -0,0 +1,81 @@ +{ + "name": "lodash.repeat", + "version": "3.0.0", + "description": "The modern build of lodash’s `_.repeat` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": [ + "lodash", + "lodash-modularized", + "stdlib", + "util" + ], + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash._basetostring": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash.repeat@3.0.0", + "_shasum": "c340f4136c99dc5b2e397b3fd50cffbd172a94b0", + "_from": "lodash.repeat@>=3.0.0 <4.0.0", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + } + ], + "dist": { + "shasum": "c340f4136c99dc5b2e397b3fd50cffbd172a94b0", + "tarball": "http://registry.npmjs.org/lodash.repeat/-/lodash.repeat-3.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash.repeat/-/lodash.repeat-3.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/package.json new file mode 100644 index 0000000..fb8e186 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/node_modules/lodash._createpadding/package.json @@ -0,0 +1,75 @@ +{ + "name": "lodash._createpadding", + "version": "3.6.0", + "description": "The modern build of lodash’s internal `createPadding` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash.repeat": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash._createpadding@3.6.0", + "_shasum": "c466850dd1a05e6bfec54fd0cf0db28b68332d5e", + "_from": "lodash._createpadding@>=3.0.0 <4.0.0", + "_npmVersion": "2.7.3", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + } + ], + "dist": { + "shasum": "c466850dd1a05e6bfec54fd0cf0db28b68332d5e", + "tarball": "http://registry.npmjs.org/lodash._createpadding/-/lodash._createpadding-3.6.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash._createpadding/-/lodash._createpadding-3.6.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/package.json new file mode 100644 index 0000000..6f028c0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.pad/package.json @@ -0,0 +1,98 @@ +{ + "name": "lodash.pad", + "version": "3.1.0", + "description": "The modern build of lodash’s `_.pad` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": [ + "lodash", + "lodash-modularized", + "stdlib", + "util" + ], + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash._basetostring": "^3.0.0", + "lodash._createpadding": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash.pad@3.1.0", + "_shasum": "9f18b1f3749a95e197b5ff2ae752ea9851ada965", + "_from": "lodash.pad@>=3.0.0 <4.0.0", + "_npmVersion": "2.7.3", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + { + "name": "d10", + "email": "demoneaux@gmail.com" + }, + { + "name": "kitcambridge", + "email": "github@kitcambridge.be" + }, + { + "name": "mathias", + "email": "mathias@qiwi.be" + }, + { + "name": "phated", + "email": "blaine@iceddev.com" + } + ], + "dist": { + "shasum": "9f18b1f3749a95e197b5ff2ae752ea9851ada965", + "tarball": "http://registry.npmjs.org/lodash.pad/-/lodash.pad-3.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash.pad/-/lodash.pad-3.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/LICENSE.txt new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/LICENSE.txt @@ -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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/README.md new file mode 100644 index 0000000..641b4d6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/README.md @@ -0,0 +1,20 @@ +# lodash.padleft v3.1.1 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.padLeft` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.padleft +``` + +In Node.js/io.js: + +```js +var padLeft = require('lodash.padleft'); +``` + +See the [documentation](https://lodash.com/docs#padLeft) or [package source](https://github.com/lodash/lodash/blob/3.1.1-npm-packages/lodash.padleft) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/index.js new file mode 100644 index 0000000..2abb69a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/index.js @@ -0,0 +1,50 @@ +/** + * lodash 3.1.1 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * 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 + */ +var baseToString = require('lodash._basetostring'), + createPadding = require('lodash._createpadding'); + +/** + * 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); + }; +} + +/** + * Pads `string` on the left side if it is 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(); + +module.exports = padLeft; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/LICENSE.txt new file mode 100644 index 0000000..1776432 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js 1.7.0, 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/README.md new file mode 100644 index 0000000..ad04ea9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/README.md @@ -0,0 +1,20 @@ +# lodash._basetostring v3.0.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `baseToString` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash._basetostring +``` + +In Node.js/io.js: + +```js +var baseToString = require('lodash._basetostring'); +``` + +See the [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash._basetostring) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/index.js new file mode 100644 index 0000000..71ac885 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/index.js @@ -0,0 +1,25 @@ +/** + * lodash 3.0.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** + * Converts `value` to a string if it is 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) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); +} + +module.exports = baseToString; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/package.json new file mode 100644 index 0000000..ba2b33c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._basetostring/package.json @@ -0,0 +1,56 @@ +{ + "name": "lodash._basetostring", + "version": "3.0.0", + "description": "The modern build of lodash’s internal `baseToString` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "readme": "# lodash._basetostring v3.0.0\n\nThe [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `baseToString` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.\n\n## Installation\n\nUsing npm:\n\n```bash\n$ {sudo -H} npm i -g npm\n$ npm i --save lodash._basetostring\n```\n\nIn Node.js/io.js:\n\n```js\nvar baseToString = require('lodash._basetostring');\n```\n\nSee the [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash._basetostring) for more details.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash._basetostring@3.0.0", + "_shasum": "75a9a4aaaa2b2a8761111ff5431e7d83c1daf0e2", + "_resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.0.tgz", + "_from": "lodash._basetostring@>=3.0.0 <4.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/LICENSE.txt new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/LICENSE.txt @@ -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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/README.md new file mode 100644 index 0000000..0e1c731 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/README.md @@ -0,0 +1,20 @@ +# lodash._createpadding v3.6.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `createPadding` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash._createpadding +``` + +In Node.js/io.js: + +```js +var createPadding = require('lodash._createpadding'); +``` + +See the [package source](https://github.com/lodash/lodash/blob/3.6.0-npm-packages/lodash._createpadding) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/index.js new file mode 100644 index 0000000..72890bd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/index.js @@ -0,0 +1,39 @@ +/** + * lodash 3.6.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.8.2 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var repeat = require('lodash.repeat'); + +/** Native method references. */ +var ceil = Math.ceil; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * 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, ceil(padLength / chars.length)).slice(0, padLength); +} + +module.exports = createPadding; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt new file mode 100644 index 0000000..1776432 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js 1.7.0, 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md new file mode 100644 index 0000000..d2796e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md @@ -0,0 +1,20 @@ +# lodash.repeat v3.0.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.repeat` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.repeat +``` + +In Node.js/io.js: + +```js +var repeat = require('lodash.repeat'); +``` + +See the [documentation](https://lodash.com/docs#repeat) or [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash.repeat) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js new file mode 100644 index 0000000..68e1008 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js @@ -0,0 +1,57 @@ +/** + * lodash 3.0.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var baseToString = require('lodash._basetostring'); + +/** Native method references. */ +var floor = Math.floor; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * 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 = floor(n / 2); + string += string; + } while (n); + + return result; +} + +module.exports = repeat; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json new file mode 100644 index 0000000..de5156d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json @@ -0,0 +1,81 @@ +{ + "name": "lodash.repeat", + "version": "3.0.0", + "description": "The modern build of lodash’s `_.repeat` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": [ + "lodash", + "lodash-modularized", + "stdlib", + "util" + ], + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash._basetostring": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash.repeat@3.0.0", + "_shasum": "c340f4136c99dc5b2e397b3fd50cffbd172a94b0", + "_from": "lodash.repeat@>=3.0.0 <4.0.0", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + } + ], + "dist": { + "shasum": "c340f4136c99dc5b2e397b3fd50cffbd172a94b0", + "tarball": "http://registry.npmjs.org/lodash.repeat/-/lodash.repeat-3.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash.repeat/-/lodash.repeat-3.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/package.json new file mode 100644 index 0000000..fb8e186 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/node_modules/lodash._createpadding/package.json @@ -0,0 +1,75 @@ +{ + "name": "lodash._createpadding", + "version": "3.6.0", + "description": "The modern build of lodash’s internal `createPadding` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash.repeat": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash._createpadding@3.6.0", + "_shasum": "c466850dd1a05e6bfec54fd0cf0db28b68332d5e", + "_from": "lodash._createpadding@>=3.0.0 <4.0.0", + "_npmVersion": "2.7.3", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + } + ], + "dist": { + "shasum": "c466850dd1a05e6bfec54fd0cf0db28b68332d5e", + "tarball": "http://registry.npmjs.org/lodash._createpadding/-/lodash._createpadding-3.6.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash._createpadding/-/lodash._createpadding-3.6.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/package.json new file mode 100644 index 0000000..55b0c25 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padleft/package.json @@ -0,0 +1,98 @@ +{ + "name": "lodash.padleft", + "version": "3.1.1", + "description": "The modern build of lodash’s `_.padLeft` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": [ + "lodash", + "lodash-modularized", + "stdlib", + "util" + ], + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash._basetostring": "^3.0.0", + "lodash._createpadding": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash.padleft@3.1.1", + "_shasum": "150151f1e0245edba15d50af2d71f1d5cff46530", + "_from": "lodash.padleft@>=3.0.0 <4.0.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + { + "name": "d10", + "email": "demoneaux@gmail.com" + }, + { + "name": "kitcambridge", + "email": "github@kitcambridge.be" + }, + { + "name": "mathias", + "email": "mathias@qiwi.be" + }, + { + "name": "phated", + "email": "blaine@iceddev.com" + } + ], + "dist": { + "shasum": "150151f1e0245edba15d50af2d71f1d5cff46530", + "tarball": "http://registry.npmjs.org/lodash.padleft/-/lodash.padleft-3.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash.padleft/-/lodash.padleft-3.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/LICENSE.txt new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/LICENSE.txt @@ -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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/README.md new file mode 100644 index 0000000..bcd6e57 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/README.md @@ -0,0 +1,20 @@ +# lodash.padright v3.1.1 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.padRight` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.padright +``` + +In Node.js/io.js: + +```js +var padRight = require('lodash.padright'); +``` + +See the [documentation](https://lodash.com/docs#padRight) or [package source](https://github.com/lodash/lodash/blob/3.1.1-npm-packages/lodash.padright) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/index.js new file mode 100644 index 0000000..6de81c4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/index.js @@ -0,0 +1,50 @@ +/** + * lodash 3.1.1 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * 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 + */ +var baseToString = require('lodash._basetostring'), + createPadding = require('lodash._createpadding'); + +/** + * 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); + }; +} + +/** + * Pads `string` on the right side if it is 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); + +module.exports = padRight; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/LICENSE.txt new file mode 100644 index 0000000..1776432 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js 1.7.0, 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/README.md new file mode 100644 index 0000000..ad04ea9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/README.md @@ -0,0 +1,20 @@ +# lodash._basetostring v3.0.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `baseToString` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash._basetostring +``` + +In Node.js/io.js: + +```js +var baseToString = require('lodash._basetostring'); +``` + +See the [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash._basetostring) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/index.js new file mode 100644 index 0000000..71ac885 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/index.js @@ -0,0 +1,25 @@ +/** + * lodash 3.0.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ + +/** + * Converts `value` to a string if it is 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) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); +} + +module.exports = baseToString; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/package.json new file mode 100644 index 0000000..ba2b33c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._basetostring/package.json @@ -0,0 +1,56 @@ +{ + "name": "lodash._basetostring", + "version": "3.0.0", + "description": "The modern build of lodash’s internal `baseToString` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "readme": "# lodash._basetostring v3.0.0\n\nThe [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `baseToString` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.\n\n## Installation\n\nUsing npm:\n\n```bash\n$ {sudo -H} npm i -g npm\n$ npm i --save lodash._basetostring\n```\n\nIn Node.js/io.js:\n\n```js\nvar baseToString = require('lodash._basetostring');\n```\n\nSee the [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash._basetostring) for more details.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash._basetostring@3.0.0", + "_shasum": "75a9a4aaaa2b2a8761111ff5431e7d83c1daf0e2", + "_resolved": "https://registry.npmjs.org/lodash._basetostring/-/lodash._basetostring-3.0.0.tgz", + "_from": "lodash._basetostring@>=3.0.0 <4.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/LICENSE.txt new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/LICENSE.txt @@ -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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/README.md new file mode 100644 index 0000000..0e1c731 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/README.md @@ -0,0 +1,20 @@ +# lodash._createpadding v3.6.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) internal `createPadding` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash._createpadding +``` + +In Node.js/io.js: + +```js +var createPadding = require('lodash._createpadding'); +``` + +See the [package source](https://github.com/lodash/lodash/blob/3.6.0-npm-packages/lodash._createpadding) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/index.js new file mode 100644 index 0000000..72890bd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/index.js @@ -0,0 +1,39 @@ +/** + * lodash 3.6.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.8.2 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var repeat = require('lodash.repeat'); + +/** Native method references. */ +var ceil = Math.ceil; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * 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, ceil(padLength / chars.length)).slice(0, padLength); +} + +module.exports = createPadding; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt new file mode 100644 index 0000000..1776432 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js 1.7.0, 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md new file mode 100644 index 0000000..d2796e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/README.md @@ -0,0 +1,20 @@ +# lodash.repeat v3.0.0 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash’s](https://lodash.com/) `_.repeat` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module. + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.repeat +``` + +In Node.js/io.js: + +```js +var repeat = require('lodash.repeat'); +``` + +See the [documentation](https://lodash.com/docs#repeat) or [package source](https://github.com/lodash/lodash/blob/3.0.0-npm-packages/lodash.repeat) for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js new file mode 100644 index 0000000..68e1008 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/index.js @@ -0,0 +1,57 @@ +/** + * lodash 3.0.0 (Custom Build) + * Build: `lodash modern modularize exports="npm" -o ./` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.7.0 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +var baseToString = require('lodash._basetostring'); + +/** Native method references. */ +var floor = Math.floor; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * 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 = floor(n / 2); + string += string; + } while (n); + + return result; +} + +module.exports = repeat; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json new file mode 100644 index 0000000..de5156d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/node_modules/lodash.repeat/package.json @@ -0,0 +1,81 @@ +{ + "name": "lodash.repeat", + "version": "3.0.0", + "description": "The modern build of lodash’s `_.repeat` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": [ + "lodash", + "lodash-modularized", + "stdlib", + "util" + ], + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash._basetostring": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash.repeat@3.0.0", + "_shasum": "c340f4136c99dc5b2e397b3fd50cffbd172a94b0", + "_from": "lodash.repeat@>=3.0.0 <4.0.0", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.35", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + } + ], + "dist": { + "shasum": "c340f4136c99dc5b2e397b3fd50cffbd172a94b0", + "tarball": "http://registry.npmjs.org/lodash.repeat/-/lodash.repeat-3.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash.repeat/-/lodash.repeat-3.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/package.json new file mode 100644 index 0000000..fb8e186 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/node_modules/lodash._createpadding/package.json @@ -0,0 +1,75 @@ +{ + "name": "lodash._createpadding", + "version": "3.6.0", + "description": "The modern build of lodash’s internal `createPadding` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash.repeat": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash._createpadding@3.6.0", + "_shasum": "c466850dd1a05e6bfec54fd0cf0db28b68332d5e", + "_from": "lodash._createpadding@>=3.0.0 <4.0.0", + "_npmVersion": "2.7.3", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + } + ], + "dist": { + "shasum": "c466850dd1a05e6bfec54fd0cf0db28b68332d5e", + "tarball": "http://registry.npmjs.org/lodash._createpadding/-/lodash._createpadding-3.6.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash._createpadding/-/lodash._createpadding-3.6.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/package.json new file mode 100644 index 0000000..2a40f94 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/node_modules/lodash.padright/package.json @@ -0,0 +1,98 @@ +{ + "name": "lodash.padright", + "version": "3.1.1", + "description": "The modern build of lodash’s `_.padRight` as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": [ + "lodash", + "lodash-modularized", + "stdlib", + "util" + ], + "author": { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + "contributors": [ + { + "name": "John-David Dalton", + "email": "john.david.dalton@gmail.com", + "url": "http://allyoucanleet.com/" + }, + { + "name": "Benjamin Tan", + "email": "demoneaux@gmail.com", + "url": "https://d10.github.io/" + }, + { + "name": "Blaine Bublitz", + "email": "blaine@iceddev.com", + "url": "http://www.iceddev.com/" + }, + { + "name": "Kit Cambridge", + "email": "github@kitcambridge.be", + "url": "http://kitcambridge.be/" + }, + { + "name": "Mathias Bynens", + "email": "mathias@qiwi.be", + "url": "https://mathiasbynens.be/" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/lodash/lodash.git" + }, + "scripts": { + "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" + }, + "dependencies": { + "lodash._basetostring": "^3.0.0", + "lodash._createpadding": "^3.0.0" + }, + "bugs": { + "url": "https://github.com/lodash/lodash/issues" + }, + "_id": "lodash.padright@3.1.1", + "_shasum": "79f7770baaa39738c040aeb5465e8d88f2aacec0", + "_from": "lodash.padright@>=3.0.0 <4.0.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + "maintainers": [ + { + "name": "jdalton", + "email": "john.david.dalton@gmail.com" + }, + { + "name": "d10", + "email": "demoneaux@gmail.com" + }, + { + "name": "kitcambridge", + "email": "github@kitcambridge.be" + }, + { + "name": "mathias", + "email": "mathias@qiwi.be" + }, + { + "name": "phated", + "email": "blaine@iceddev.com" + } + ], + "dist": { + "shasum": "79f7770baaa39738c040aeb5465e8d88f2aacec0", + "tarball": "http://registry.npmjs.org/lodash.padright/-/lodash.padright-3.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/lodash.padright/-/lodash.padright-3.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/package.json new file mode 100644 index 0000000..227173e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/package.json @@ -0,0 +1,60 @@ +{ + "name": "gauge", + "version": "1.2.0", + "description": "A terminal based horizontal guage", + "main": "progress-bar.js", + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/iarna/gauge.git" + }, + "keywords": [ + "progressbar", + "progress", + "gauge" + ], + "author": { + "name": "Rebecca Turner", + "email": "me@re-becca.org" + }, + "license": "ISC", + "bugs": { + "url": "https://github.com/iarna/gauge/issues" + }, + "homepage": "https://github.com/iarna/gauge", + "dependencies": { + "ansi": "^0.3.0", + "has-unicode": "^1.0.0", + "lodash.pad": "^3.0.0", + "lodash.padleft": "^3.0.0", + "lodash.padright": "^3.0.0" + }, + "devDependencies": { + "tap": "^0.4.13" + }, + "gitHead": "db15c35374816b3fc3b9e1e54866f31ed7f4a733", + "_id": "gauge@1.2.0", + "_shasum": "3094ab1285633f799814388fc8f2de67b4c012c5", + "_from": "gauge@>=1.2.0 <1.3.0", + "_npmVersion": "2.6.0", + "_nodeVersion": "1.1.0", + "_npmUser": { + "name": "iarna", + "email": "me@re-becca.org" + }, + "maintainers": [ + { + "name": "iarna", + "email": "me@re-becca.org" + } + ], + "dist": { + "shasum": "3094ab1285633f799814388fc8f2de67b4c012c5", + "tarball": "http://registry.npmjs.org/gauge/-/gauge-1.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/gauge/-/gauge-1.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/progress-bar.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/progress-bar.js new file mode 100644 index 0000000..39dbf2a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/gauge/progress-bar.js @@ -0,0 +1,209 @@ +"use strict" +var hasUnicode = require("has-unicode") +var ansi = require("ansi") +var align = { + center: require("lodash.pad"), + left: require("lodash.padright"), + right: require("lodash.padleft") +} +var defaultStream = process.stderr +function isTTY() { + return process.stderr.isTTY +} +function getWritableTTYColumns() { + // One less than the actual as writing to the final column wraps the line + return process.stderr.columns - 1 +} + +var ProgressBar = module.exports = function (options, cursor) { + if (! options) options = {} + if (! cursor && options.write) { + cursor = options + options = {} + } + if (! cursor) { + cursor = ansi(defaultStream) + } + this.cursor = cursor + this.showing = false + this.theme = options.theme || (hasUnicode() ? ProgressBar.unicode : ProgressBar.ascii) + this.template = options.template || [ + {type: "name", separated: true, length: 25}, + {type: "spinner", separated: true}, + {type: "startgroup"}, + {type: "completionbar"}, + {type: "endgroup"} + ] + this.updatefreq = options.maxUpdateFrequency || 50 + this.lastName = "" + this.lastCompleted = 0 + this.spun = 0 + this.last = new Date(0) +} +ProgressBar.prototype = {} + +ProgressBar.unicode = { + startgroup: "╢", + endgroup: "╟", + complete: "█", + incomplete: "░", + spinner: "▀▐▄▌", + subsection: "→" +} + +ProgressBar.ascii = { + startgroup: "|", + endgroup: "|", + complete: "#", + incomplete: "-", + spinner: "-\\|/", + subsection: "->" +} + +ProgressBar.prototype.setTheme = function(theme) { + this.theme = theme +} + +ProgressBar.prototype.setTemplate = function(template) { + this.template = template +} + +ProgressBar.prototype.disable = function() { + this.hide() + this.disabled = true +} + +ProgressBar.prototype.enable = function() { + this.disabled = false + this.show() +} + +ProgressBar.prototype.hide = function() { + if (!isTTY()) return + if (this.disabled) return + this.cursor.show() + if (this.showing) this.cursor.up(1) + this.cursor.horizontalAbsolute(0).eraseLine() + this.showing = false +} + +var repeat = function (str, count) { + var out = "" + for (var ii=0; ii P | |----|\n' ], + [ 'show' ] ]) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/package.json new file mode 100644 index 0000000..d15e6cc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/package.json @@ -0,0 +1,58 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "npmlog", + "description": "logger for npm", + "version": "1.2.1", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/npmlog.git" + }, + "main": "log.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "ansi": "~0.3.0", + "are-we-there-yet": "~1.0.0", + "gauge": "~1.2.0" + }, + "devDependencies": { + "tap": "" + }, + "license": "ISC", + "gitHead": "4e1a73a567036064ded425a7d48c863d53550b4f", + "bugs": { + "url": "https://github.com/isaacs/npmlog/issues" + }, + "homepage": "https://github.com/isaacs/npmlog#readme", + "_id": "npmlog@1.2.1", + "_shasum": "28e7be619609b53f7ad1dd300a10d64d716268b6", + "_from": "npmlog@>=1.2.0 <1.3.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "28e7be619609b53f7ad1dd300a10d64d716268b6", + "tarball": "http://registry.npmjs.org/npmlog/-/npmlog-1.2.1.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + }, + { + "name": "iarna", + "email": "me@re-becca.org" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/npmlog/-/npmlog-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/basic.js new file mode 100644 index 0000000..1afcabd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/basic.js @@ -0,0 +1,228 @@ +var tap = require('tap') +var log = require('../') + +var result = [] +var logEvents = [] +var logInfoEvents = [] +var logPrefixEvents = [] + +var util = require('util') + +var resultExpect = +[ '\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[7msill\u001b[0m \u001b[0m\u001b[35msilly prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[34m\u001b[40mverb\u001b[0m \u001b[0m\u001b[35mverbose prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32minfo\u001b[0m \u001b[0m\u001b[35minfo prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32m\u001b[40mhttp\u001b[0m \u001b[0m\u001b[35mhttp prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[30m\u001b[43mWARN\u001b[0m \u001b[0m\u001b[35mwarn prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35merror prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32minfo\u001b[0m \u001b[0m\u001b[35minfo prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[32m\u001b[40mhttp\u001b[0m \u001b[0m\u001b[35mhttp prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[30m\u001b[43mWARN\u001b[0m \u001b[0m\u001b[35mwarn prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35merror prefix\u001b[0m x = {"foo":{"bar":"baz"}}\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m This is a longer\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m message, with some details\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m and maybe a stack.\n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u001b[31m\u001b[40mERR!\u001b[0m \u001b[0m\u001b[35m404\u001b[0m \n', + '\u001b[0m\u001b[37m\u001b[40mnpm\u001b[0m \u001b[0m\u0007noise\u001b[0m\u001b[35m\u001b[0m LOUD NOISES\n', + '\u001b[0m' ] + +var logPrefixEventsExpect = +[ { id: 2, + level: 'info', + prefix: 'info prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 9, + level: 'info', + prefix: 'info prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 16, + level: 'info', + prefix: 'info prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] } ] + +// should be the same. +var logInfoEventsExpect = logPrefixEventsExpect + +var logEventsExpect = +[ { id: 0, + level: 'silly', + prefix: 'silly prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 1, + level: 'verbose', + prefix: 'verbose prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 2, + level: 'info', + prefix: 'info prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 3, + level: 'http', + prefix: 'http prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 4, + level: 'warn', + prefix: 'warn prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 5, + level: 'error', + prefix: 'error prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 6, + level: 'silent', + prefix: 'silent prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 7, + level: 'silly', + prefix: 'silly prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 8, + level: 'verbose', + prefix: 'verbose prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 9, + level: 'info', + prefix: 'info prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 10, + level: 'http', + prefix: 'http prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 11, + level: 'warn', + prefix: 'warn prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 12, + level: 'error', + prefix: 'error prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 13, + level: 'silent', + prefix: 'silent prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 14, + level: 'silly', + prefix: 'silly prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 15, + level: 'verbose', + prefix: 'verbose prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 16, + level: 'info', + prefix: 'info prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 17, + level: 'http', + prefix: 'http prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 18, + level: 'warn', + prefix: 'warn prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 19, + level: 'error', + prefix: 'error prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 20, + level: 'silent', + prefix: 'silent prefix', + message: 'x = {"foo":{"bar":"baz"}}', + messageRaw: [ 'x = %j', { foo: { bar: 'baz' } } ] }, + { id: 21, + level: 'error', + prefix: '404', + message: 'This is a longer\nmessage, with some details\nand maybe a stack.\n', + messageRaw: [ 'This is a longer\nmessage, with some details\nand maybe a stack.\n' ] }, + { id: 22, + level: 'noise', + prefix: false, + message: 'LOUD NOISES', + messageRaw: [ 'LOUD NOISES' ] } ] + +var Stream = require('stream').Stream +var s = new Stream() +s.write = function (m) { + result.push(m) +} + +s.writable = true +s.isTTY = true +s.end = function () {} + +log.stream = s + +log.heading = 'npm' + + +tap.test('basic', function (t) { + log.on('log', logEvents.push.bind(logEvents)) + log.on('log.info', logInfoEvents.push.bind(logInfoEvents)) + log.on('info prefix', logPrefixEvents.push.bind(logPrefixEvents)) + + console.error('log.level=silly') + log.level = 'silly' + log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) + log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) + log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) + log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) + log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) + log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) + log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) + + console.error('log.level=silent') + log.level = 'silent' + log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) + log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) + log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) + log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) + log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) + log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) + log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) + + console.error('log.level=info') + log.level = 'info' + log.silly('silly prefix', 'x = %j', {foo:{bar:'baz'}}) + log.verbose('verbose prefix', 'x = %j', {foo:{bar:'baz'}}) + log.info('info prefix', 'x = %j', {foo:{bar:'baz'}}) + log.http('http prefix', 'x = %j', {foo:{bar:'baz'}}) + log.warn('warn prefix', 'x = %j', {foo:{bar:'baz'}}) + log.error('error prefix', 'x = %j', {foo:{bar:'baz'}}) + log.silent('silent prefix', 'x = %j', {foo:{bar:'baz'}}) + log.error('404', 'This is a longer\n'+ + 'message, with some details\n'+ + 'and maybe a stack.\n') + log.addLevel('noise', 10000, {beep: true}) + log.noise(false, 'LOUD NOISES') + + t.deepEqual(result.join('').trim(), resultExpect.join('').trim(), 'result') + t.deepEqual(log.record, logEventsExpect, 'record') + t.deepEqual(logEvents, logEventsExpect, 'logEvents') + t.deepEqual(logInfoEvents, logInfoEventsExpect, 'logInfoEvents') + t.deepEqual(logPrefixEvents, logPrefixEventsExpect, 'logPrefixEvents') + + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/progress.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/progress.js new file mode 100644 index 0000000..97b13de --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/npmlog/test/progress.js @@ -0,0 +1,114 @@ +'use strict' + +var test = require('tap').test +var log = require('../log.js') + +var actions = [] +log.gauge = { + enable: function () { + actions.push(['enable']) + }, + disable: function () { + actions.push(['disable']) + }, + hide: function () { + actions.push(['hide']) + }, + show: function (name, completed) { + actions.push(['show', name, completed]) + }, + pulse: function (name) { + actions.push(['pulse', name]) + } +} + +function didActions(t, msg, output) { + var tests = [] + for (var ii = 0; ii < output.length; ++ ii) { + for (var jj = 0; jj < output[ii].length; ++ jj) { + tests.push({cmd: ii, arg: jj}) + } + } + t.is(actions.length, output.length, msg) + tests.forEach(function (test) { + t.is(actions[test.cmd] ? actions[test.cmd][test.arg] : null, + output[test.cmd][test.arg], + msg + ': ' + output[test.cmd] + (test.arg ? ' arg #'+test.arg : '')) + }) + actions = [] +} + + +test('enableProgress', function (t) { + t.plan(6) + log.enableProgress() + didActions(t, 'enableProgress', [ [ 'enable' ], [ 'show', undefined, 0 ] ]) + log.enableProgress() + didActions(t, 'enableProgress again', []) +}) + +test('disableProgress', function (t) { + t.plan(4) + log.disableProgress() + didActions(t, 'disableProgress', [ [ 'hide' ], [ 'disable' ] ]) + log.disableProgress() + didActions(t, 'disableProgress again', []) +}) + +test('showProgress', function (t) { + t.plan(5) + log.showProgress('foo') + didActions(t, 'showProgress disabled', []) + log.enableProgress() + actions = [] + log.showProgress('foo') + didActions(t, 'showProgress', [ [ 'show', 'foo', 0 ] ]) +}) + +test('clearProgress', function (t) { + t.plan(3) + log.clearProgress() + didActions(t, 'clearProgress', [ [ 'hide' ] ]) + log.disableProgress() + actions = [] + log.clearProgress() + didActions(t, 'clearProgress disabled', [ ]) +}) + +test("newItem", function (t) { + t.plan(12) + log.enableProgress() + actions = [] + var a = log.newItem("test", 10) + didActions(t, "newItem", [ [ 'show', undefined, 0 ] ]) + a.completeWork(5) + didActions(t, "newItem:completeWork", [ [ 'show', 'test', 0.5 ] ]) + a.finish() + didActions(t, "newItem:finish", [ [ 'show', 'test', 1 ] ]) +}) + +// test that log objects proxy through. And test that completion status filters up +test("newGroup", function (t) { + t.plan(23) + var a = log.newGroup("newGroup") + didActions(t, "newGroup", [ [ 'show', undefined, 0.5 ] ]) + a.warn("test", "this is a test") + didActions(t, "newGroup:warn", [ [ 'pulse', 'test' ], [ 'hide' ], [ 'show', undefined, 0.5 ] ]) + var b = a.newItem("newGroup2", 10) + didActions(t, "newGroup:newItem", [ [ 'show', 'newGroup', 0.5 ] ]) + b.completeWork(5) + didActions(t, "newGroup:completeWork", [ [ 'show', 'newGroup2', 0.75 ] ]) + a.finish() + didActions(t, "newGroup:finish", [ [ 'show', 'newGroup', 1 ] ]) +}) + +test("newStream", function (t) { + t.plan(13) + var a = log.newStream("newStream", 10) + didActions(t, "newStream", [ [ 'show', undefined, 0.6666666666666666 ] ]) + a.write("abcde") + didActions(t, "newStream", [ [ 'show', 'newStream', 0.8333333333333333 ] ]) + a.write("fghij") + didActions(t, "newStream", [ [ 'show', 'newStream', 1 ] ]) + t.is(log.tracker.completed(), 1, "Overall completion") +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/.npmignore new file mode 100644 index 0000000..13abef4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/.npmignore @@ -0,0 +1,3 @@ +node_modules +node_modules/* +npm_debug.log diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.APACHE2 b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.APACHE2 new file mode 100644 index 0000000..6366c04 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.BSD b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.BSD new file mode 100644 index 0000000..96bb796 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.BSD @@ -0,0 +1,26 @@ +Copyright (c) 2013, Dominic Tarr +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those +of the authors and should not be interpreted as representing official policies, +either expressed or implied, of the FreeBSD Project. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.MIT b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.MIT new file mode 100644 index 0000000..6eafbd7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/README.md new file mode 100644 index 0000000..ea8ebc0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/README.md @@ -0,0 +1,149 @@ +# rc + +The non-configurable configuration loader for lazy people. + +## Usage + +The only option is to pass rc the name of your app, and your default configuration. + +```javascript +var conf = require('rc')(appname, { + //defaults go here. + port: 2468, + + //defaults which are objects will be merged, not replaced + views: { + engine: 'jade' + } +}); +``` + +`rc` will return your configuration options merged with the defaults you specify. +If you pass in a predefined defaults object, it will be mutated: + +```javascript +var conf = {}; +require('rc')(appname, conf); +``` + +If `rc` finds any config files for your app, the returned config object will have +a `configs` array containing their paths: + +```javascript +var appCfg = require('rc')(appname, conf); +appCfg.configs[0] // /etc/appnamerc +appCfg.configs[1] // /home/dominictarr/.config/appname +appCfg.config // same as appCfg.configs[appCfg.configs.length - 1] +``` + +## Standards + +Given your application name (`appname`), rc will look in all the obvious places for configuration. + + * command line arguments (parsed by minimist) + * environment variables prefixed with `${appname}_` + * or use "\_\_" to indicate nested properties
_(e.g. `appname_foo__bar__baz` => `foo.bar.baz`)_ + * if you passed an option `--config file` then from that file + * a local `.${appname}rc` or the first found looking in `./ ../ ../../ ../../../` etc. + * `$HOME/.${appname}rc` + * `$HOME/.${appname}/config` + * `$HOME/.config/${appname}` + * `$HOME/.config/${appname}/config` + * `/etc/${appname}rc` + * `/etc/${appname}/config` + * the defaults object you passed in. + +All configuration sources that were found will be flattened into one object, +so that sources **earlier** in this list override later ones. + + +## Configuration File Formats + +Configuration files (e.g. `.appnamerc`) may be in either [json](http://json.org/example) or [ini](http://en.wikipedia.org/wiki/INI_file) format. The example configurations below are equivalent: + + +#### Formatted as `ini` + +``` +; You can include comments in `ini` format if you want. + +dependsOn=0.10.0 + + +; `rc` has built-in support for ini sections, see? + +[commands] + www = ./commands/www + console = ./commands/repl + + +; You can even do nested sections + +[generators.options] + engine = ejs + +[generators.modules] + new = generate-new + engine = generate-backend + +``` + +#### Formatted as `json` + +```json +{ + // You can even comment your JSON, if you want + "dependsOn": "0.10.0", + "commands": { + "www": "./commands/www", + "console": "./commands/repl" + }, + "generators": { + "options": { + "engine": "ejs" + }, + "modules": { + "new": "generate-new", + "backend": "generate-backend" + } + } +} +``` + +Comments are stripped from JSON config via [strip-json-comments](https://github.com/sindresorhus/strip-json-comments). + +> Since ini, and env variables do not have a standard for types, your application needs be prepared for strings. + + + +## Advanced Usage + +#### Pass in your own `argv` + +You may pass in your own `argv` as the third argument to `rc`. This is in case you want to [use your own command-line opts parser](https://github.com/dominictarr/rc/pull/12). + +```javascript +require('rc')(appname, defaults, customArgvParser); +``` + +## Pass in your own parser + +If you have a special need to use a non-standard parser, +you can do so by passing in the parser as the 4th argument. +(leave the 3rd as null to get the default args parser) + +```javascript +require('rc')(appname, defaults, null, parser); +``` + +This may also be used to force a more strict format, +such as strict, valid JSON only. + +## Note on Performance + +`rc` is running `fs.statSync`-- so make sure you don't use it in a hot code path (e.g. a request handler) + + +## License + +Multi-licensed under the two-clause BSD License, MIT License, or Apache License, version 2.0 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/browser.js new file mode 100644 index 0000000..8c230c5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/browser.js @@ -0,0 +1,7 @@ + +// when this is loaded into the browser, +// just use the defaults... + +module.exports = function (name, defaults) { + return defaults +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/index.js new file mode 100755 index 0000000..31fb515 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/index.js @@ -0,0 +1,60 @@ +#! /usr/bin/env node +var cc = require('./lib/utils') +var join = require('path').join +var deepExtend = require('deep-extend') +var etc = '/etc' +var win = process.platform === "win32" +var home = win + ? process.env.USERPROFILE + : process.env.HOME + +module.exports = function (name, defaults, argv, parse) { + if('string' !== typeof name) + throw new Error('rc(name): name *must* be string') + if(!argv) + argv = require('minimist')(process.argv.slice(2)) + defaults = ( + 'string' === typeof defaults + ? cc.json(defaults) : defaults + ) || {} + + parse = parse || cc.parse + + var env = cc.env(name + '_') + + var configs = [defaults] + var configFiles = [] + function addConfigFile (file) { + if (configFiles.indexOf(file) >= 0) return + var fileConfig = cc.file(file) + if (fileConfig) { + configs.push(parse(fileConfig)) + configFiles.push(file) + } + } + + // which files do we look at? + if (!win) + [join(etc, name, 'config'), + join(etc, name + 'rc')].forEach(addConfigFile) + if (home) + [join(home, '.config', name, 'config'), + join(home, '.config', name), + join(home, '.' + name, 'config'), + join(home, '.' + name + 'rc')].forEach(addConfigFile) + addConfigFile(cc.find('.'+name+'rc')) + if (env.config) addConfigFile(env.config) + if (argv.config) addConfigFile(argv.config) + + return deepExtend.apply(null, configs.concat([ + env, + argv, + configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : null, + ])) +} + +if(!module.parent) { + console.log( + JSON.stringify(module.exports(process.argv[2]), false, 2) + ) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/lib/utils.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/lib/utils.js new file mode 100644 index 0000000..e65e7ec --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/lib/utils.js @@ -0,0 +1,101 @@ +var fs = require('fs') +var ini = require('ini') +var path = require('path') +var stripJsonComments = require('strip-json-comments') + +var parse = exports.parse = function (content, file) { + + //if it ends in .json or starts with { then it must be json. + //must be done this way, because ini accepts everything. + //can't just try and parse it and let it throw if it's not ini. + //everything is ini. even json with a systax error. + + if((file && /\.json$/.test(file)) || /^\s*{/.test(content)) + return JSON.parse(stripJsonComments(content)) + return ini.parse(content) + +} + +var file = exports.file = function () { + var args = [].slice.call(arguments).filter(function (arg) { return arg != null }) + + //path.join breaks if it's a not a string, so just skip this. + for(var i in args) + if('string' !== typeof args[i]) + return + + var file = path.join.apply(null, args) + var content + try { + return fs.readFileSync(file,'utf-8') + } catch (err) { + return + } +} + +var json = exports.json = function () { + var content = file.apply(null, arguments) + return content ? parse(content) : null +} + +var env = exports.env = function (prefix, env) { + env = env || process.env + var obj = {} + var l = prefix.length + for(var k in env) { + if((k.indexOf(prefix)) === 0) { + + var keypath = k.substring(l).split('__') + + // Trim empty strings from keypath array + var _emptyStringIndex + while ((_emptyStringIndex=keypath.indexOf('')) > -1) { + keypath.splice(_emptyStringIndex, 1) + } + + var cursor = obj + keypath.forEach(function _buildSubObj(_subkey,i){ + + // (check for _subkey first so we ignore empty strings) + if (!_subkey) + return + + // If this is the last key, just stuff the value in there + // Assigns actual value from env variable to final key + // (unless it's just an empty string- in that case use the last valid key) + if (i === keypath.length-1) + cursor[_subkey] = env[k] + + + // Build sub-object if nothing already exists at the keypath + if (cursor[_subkey] === undefined) + cursor[_subkey] = {} + + // Increment cursor used to track the object at the current depth + cursor = cursor[_subkey] + + }) + + } + + } + + return obj +} + +var find = exports.find = function () { + var rel = path.join.apply(null, [].slice.call(arguments)) + + function find(start, rel) { + var file = path.join(start, rel) + try { + fs.statSync(file) + return file + } catch (err) { + if(path.dirname(start) !== start) // root + return find(path.dirname(start), rel) + } + } + return find(process.cwd(), rel) +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/.bin/strip-json-comments b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/.bin/strip-json-comments new file mode 120000 index 0000000..63d549f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/.bin/strip-json-comments @@ -0,0 +1 @@ +../strip-json-comments/cli.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/LICENSE new file mode 100644 index 0000000..e950236 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Viacheslav Lotsmanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/README.md new file mode 100644 index 0000000..0457c52 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/README.md @@ -0,0 +1,52 @@ +Node.JS module “Deep Extend” +============================ + +Recursive object extending. + +Install +----- + + npm install deep-extend + +Usage +----- + + var deepExtend = require('deep-extend'); + var obj1 = { + a: 1, + b: 2, + d: { + a: 1, + b: [], + c: { test1: 123, test2: 321 } + }, + f: 5, + g: 123 + }; + var obj2 = { + b: 3, + c: 5, + d: { + b: { first: 'one', second: 'two' }, + c: { test2: 222 } + }, + e: { one: 1, two: 2 }, + f: [], + g: (void 0) + }; + + deepExtend(obj1, obj2); + + console.log(obj1); + /* + { a: 1, + b: 3, + d: + { a: 1, + b: { first: 'one', second: 'two' }, + c: { test1: 123, test2: 222 } }, + f: [], + c: 5, + e: { one: 1, two: 2 }, + g: undefined } + */ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/index.js new file mode 100644 index 0000000..c1f8dae --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/index.js @@ -0,0 +1,90 @@ +/*! + * Node.JS module "Deep Extend" + * @description Recursive object extending. + * @author Viacheslav Lotsmanov (unclechu) + * @license MIT + * + * The MIT License (MIT) + * + * Copyright (c) 2013 Viacheslav Lotsmanov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * Extening object that entered in first argument. + * Returns extended object or false if have no target object or incorrect type. + * If you wish to clone object, simply use that: + * deepExtend({}, yourObj_1, [yourObj_N]) - first arg is new empty object + */ +var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { + if (arguments.length < 1 || typeof arguments[0] !== 'object') { + return false; + } + + if (arguments.length < 2) return arguments[0]; + + var target = arguments[0]; + + // convert arguments to array and cut off target object + var args = Array.prototype.slice.call(arguments, 1); + + var key, val, src, clone, tmpBuf; + + args.forEach(function (obj) { + if (typeof obj !== 'object') return; + + for (key in obj) { + if ( ! (key in obj)) continue; + + src = target[key]; + val = obj[key]; + + if (val === target) continue; + + if (typeof val !== 'object' || val === null) { + target[key] = val; + continue; + } else if (val instanceof Buffer) { + tmpBuf = new Buffer(val.length); + val.copy(tmpBuf); + target[key] = tmpBuf; + continue; + } else if (val instanceof Date) { + target[key] = new Date(val.getTime()); + continue; + } + + if (typeof src !== 'object' || src === null) { + clone = (Array.isArray(val)) ? [] : {}; + target[key] = deepExtend(clone, val); + continue; + } + + if (Array.isArray(val)) { + clone = (Array.isArray(src)) ? src : []; + } else { + clone = (!Array.isArray(src)) ? src : {}; + } + + target[key] = deepExtend(clone, val); + } + }); + + return target; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/package.json new file mode 100644 index 0000000..1093a94 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/package.json @@ -0,0 +1,45 @@ +{ + "name": "deep-extend", + "description": "Recursive object extending.", + "license": "MIT", + "version": "0.2.11", + "homepage": "https://github.com/unclechu/node-deep-extend", + "repository": { + "type": "git", + "url": "git://github.com/unclechu/node-deep-extend.git" + }, + "author": { + "name": "Viacheslav Lotsmanov", + "email": "lotsmanov89@gmail.com", + "url": "unclechu" + }, + "contributors": [ + { + "name": "Romain Prieto", + "url": "https://github.com/rprieto" + } + ], + "main": "index", + "engines": { + "node": ">=0.4" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "~1.19.0", + "should": "~3.3.2" + }, + "directories": { + "test": "./test" + }, + "readme": "Node.JS module “Deep Extend”\r\n============================\r\n\r\nRecursive object extending.\r\n\r\nInstall\r\n-----\r\n\r\n npm install deep-extend\r\n\r\nUsage\r\n-----\r\n\r\n var deepExtend = require('deep-extend');\r\n var obj1 = {\r\n a: 1,\r\n b: 2,\r\n d: {\r\n a: 1,\r\n b: [],\r\n c: { test1: 123, test2: 321 }\r\n },\r\n f: 5,\r\n g: 123\r\n };\r\n var obj2 = {\r\n b: 3,\r\n c: 5,\r\n d: {\r\n b: { first: 'one', second: 'two' },\r\n c: { test2: 222 }\r\n },\r\n e: { one: 1, two: 2 },\r\n f: [],\r\n g: (void 0)\r\n };\r\n\r\n deepExtend(obj1, obj2);\r\n\r\n console.log(obj1);\r\n /*\r\n { a: 1,\r\n b: 3,\r\n d:\r\n { a: 1,\r\n b: { first: 'one', second: 'two' },\r\n c: { test1: 123, test2: 222 } },\r\n f: [],\r\n c: 5,\r\n e: { one: 1, two: 2 },\r\n g: undefined }\r\n */\r\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/unclechu/node-deep-extend/issues" + }, + "_id": "deep-extend@0.2.11", + "_shasum": "7a16ba69729132340506170494bc83f7076fe08f", + "_resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.2.11.tgz", + "_from": "deep-extend@>=0.2.5 <0.3.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/index.spec.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/index.spec.js new file mode 100644 index 0000000..38974a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/index.spec.js @@ -0,0 +1,57 @@ +var should = require('should'); +var extend = require('../index'); + +describe('deep-extend', function() { + + it('can extend on 1 level', function() { + var a = { hello: 1 }; + var b = { world: 2 }; + extend(a, b); + a.should.eql({ + hello: 1, + world: 2 + }); + }); + + it('can extend on 2 levels', function() { + var a = { person: { name: 'John' } }; + var b = { person: { age: 30 } }; + extend(a, b); + a.should.eql({ + person: { name: 'John', age: 30 } + }); + }); + + it('can extend with Buffer values', function() { + var a = { hello: 1 }; + var b = { value: new Buffer('world') }; + extend(a, b); + a.should.eql({ + hello: 1, + value: new Buffer('world') + }); + }); + + it('Buffer is cloned', function () { + var a = { }; + var b = { value: new Buffer('foo') }; + extend(a, b); + a.value.write('bar'); + a.value.toString().should.eql('bar'); + b.value.toString().should.eql('foo'); + }); + + it('Date objects', function () { + var a = { d: new Date() }; + var b = extend({}, a); + b.d.should.instanceOf(Date); + }); + + it('Date object is cloned', function () { + var a = { d: new Date() }; + var b = extend({}, a); + b.d.setTime( (new Date()).getTime() + 100000 ); + b.d.getTime().should.not.eql( a.d.getTime() ); + }); + +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/mocha.opts b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/mocha.opts new file mode 100644 index 0000000..5ada47b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/deep-extend/test/mocha.opts @@ -0,0 +1 @@ +--reporter spec diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/README.md new file mode 100644 index 0000000..33df258 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/README.md @@ -0,0 +1,102 @@ +An ini format parser and serializer for node. + +Sections are treated as nested objects. Items before the first +heading are saved on the object directly. + +## Usage + +Consider an ini-file `config.ini` that looks like this: + + ; this comment is being ignored + scope = global + + [database] + user = dbuser + password = dbpassword + database = use_this_database + + [paths.default] + datadir = /var/lib/data + array[] = first value + array[] = second value + array[] = third value + +You can read, manipulate and write the ini-file like so: + + var fs = require('fs') + , ini = require('ini') + + var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) + + config.scope = 'local' + config.database.database = 'use_another_database' + config.paths.default.tmpdir = '/tmp' + delete config.paths.default.datadir + config.paths.default.array.push('fourth value') + + fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) + +This will result in a file called `config_modified.ini` being written +to the filesystem with the following content: + + [section] + scope=local + [section.database] + user=dbuser + password=dbpassword + database=use_another_database + [section.paths.default] + tmpdir=/tmp + array[]=first value + array[]=second value + array[]=third value + array[]=fourth value + + +## API + +### decode(inistring) + +Decode the ini-style formatted `inistring` into a nested object. + +### parse(inistring) + +Alias for `decode(inistring)` + +### encode(object, [options]) + +Encode the object `object` into an ini-style formatted string. If the +optional parameter `section` is given, then all top-level properties +of the object are put into this section and the `section`-string is +prepended to all sub-sections, see the usage example above. + +The `options` object may contain the following: + +* `section` A string which will be the first `section` in the encoded + ini data. Defaults to none. +* `whitespace` Boolean to specify whether to put whitespace around the + `=` character. By default, whitespace is omitted, to be friendly to + some persnickety old parsers that don't tolerate it well. But some + find that it's more human-readable and pretty with the whitespace. + +For backwards compatibility reasons, if a `string` options is passed +in, then it is assumed to be the `section` value. + +### stringify(object, [options]) + +Alias for `encode(object, [options])` + +### safe(val) + +Escapes the string `val` such that it is safe to be used as a key or +value in an ini-file. Basically escapes quotes. For example + + ini.safe('"unsafe string"') + +would result in + + "\"unsafe string\"" + +### unsafe(val) + +Unescapes the string `val` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/ini.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/ini.js new file mode 100644 index 0000000..ddf5bd9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/ini.js @@ -0,0 +1,190 @@ + +exports.parse = exports.decode = decode +exports.stringify = exports.encode = encode + +exports.safe = safe +exports.unsafe = unsafe + +var eol = process.platform === "win32" ? "\r\n" : "\n" + +function encode (obj, opt) { + var children = [] + , out = "" + + if (typeof opt === "string") { + opt = { + section: opt, + whitespace: false + } + } else { + opt = opt || {} + opt.whitespace = opt.whitespace === true + } + + var separator = opt.whitespace ? " = " : "=" + + Object.keys(obj).forEach(function (k, _, __) { + var val = obj[k] + if (val && Array.isArray(val)) { + val.forEach(function(item) { + out += safe(k + "[]") + separator + safe(item) + "\n" + }) + } + else if (val && typeof val === "object") { + children.push(k) + } else { + out += safe(k) + separator + safe(val) + eol + } + }) + + if (opt.section && out.length) { + out = "[" + safe(opt.section) + "]" + eol + out + } + + children.forEach(function (k, _, __) { + var nk = dotSplit(k).join('\\.') + var section = (opt.section ? opt.section + "." : "") + nk + var child = encode(obj[k], { + section: section, + whitespace: opt.whitespace + }) + if (out.length && child.length) { + out += eol + } + out += child + }) + + return out +} + +function dotSplit (str) { + return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./).map(function (part) { + return part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') + }) +} + +function decode (str) { + var out = {} + , p = out + , section = null + , state = "START" + // section |key = value + , re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i + , lines = str.split(/[\r\n]+/g) + , section = null + + lines.forEach(function (line, _, __) { + if (!line || line.match(/^\s*[;#]/)) return + var match = line.match(re) + if (!match) return + if (match[1] !== undefined) { + section = unsafe(match[1]) + p = out[section] = out[section] || {} + return + } + var key = unsafe(match[2]) + , value = match[3] ? unsafe((match[4] || "")) : true + switch (value) { + case 'true': + case 'false': + case 'null': value = JSON.parse(value) + } + + // Convert keys with '[]' suffix to an array + if (key.length > 2 && key.slice(-2) === "[]") { + key = key.substring(0, key.length - 2) + if (!p[key]) { + p[key] = [] + } + else if (!Array.isArray(p[key])) { + p[key] = [p[key]] + } + } + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (Array.isArray(p[key])) { + p[key].push(value) + } + else { + p[key] = value + } + }) + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + Object.keys(out).filter(function (k, _, __) { + if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k])) return false + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + var parts = dotSplit(k) + , p = out + , l = parts.pop() + , nl = l.replace(/\\\./g, '.') + parts.forEach(function (part, _, __) { + if (!p[part] || typeof p[part] !== "object") p[part] = {} + p = p[part] + }) + if (p === out && nl === l) return false + p[nl] = out[k] + return true + }).forEach(function (del, _, __) { + delete out[del] + }) + + return out +} + +function isQuoted (val) { + return (val.charAt(0) === "\"" && val.slice(-1) === "\"") + || (val.charAt(0) === "'" && val.slice(-1) === "'") +} + +function safe (val) { + return ( typeof val !== "string" + || val.match(/[=\r\n]/) + || val.match(/^\[/) + || (val.length > 1 + && isQuoted(val)) + || val !== val.trim() ) + ? JSON.stringify(val) + : val.replace(/;/g, '\\;').replace(/#/g, "\\#") +} + +function unsafe (val, doUnesc) { + val = (val || "").trim() + if (isQuoted(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") { + val = val.substr(1, val.length - 2); + } + try { val = JSON.parse(val) } catch (_) {} + } else { + // walk the val to find the first not-escaped ; character + var esc = false + var unesc = ""; + for (var i = 0, l = val.length; i < l; i++) { + var c = val.charAt(i) + if (esc) { + if ("\\;#".indexOf(c) !== -1) + unesc += c + else + unesc += "\\" + c + esc = false + } else if (";#".indexOf(c) !== -1) { + break + } else if (c === "\\") { + esc = true + } else { + unesc += c + } + } + if (esc) + unesc += "\\" + return unesc + } + return val +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/package.json new file mode 100644 index 0000000..162817d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/package.json @@ -0,0 +1,53 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "ini", + "description": "An ini encoder/decoder for node", + "version": "1.3.3", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/ini.git" + }, + "main": "ini.js", + "scripts": { + "test": "tap test/*.js" + }, + "engines": { + "node": "*" + }, + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.0" + }, + "license": "ISC", + "gitHead": "566268f1fb8dd3c0f7d968091de7b7fb2b97b483", + "bugs": { + "url": "https://github.com/isaacs/ini/issues" + }, + "homepage": "https://github.com/isaacs/ini", + "_id": "ini@1.3.3", + "_shasum": "c07e34aef1de06aff21d413b458e52b21533a11e", + "_from": "ini@>=1.3.0 <1.4.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "1.1.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "dist": { + "shasum": "c07e34aef1de06aff21d413b458e52b21533a11e", + "tarball": "http://registry.npmjs.org/ini/-/ini-1.3.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ini/-/ini-1.3.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/bar.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/bar.js new file mode 100644 index 0000000..cb16176 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/bar.js @@ -0,0 +1,23 @@ +//test that parse(stringify(obj) deepEqu + +var ini = require('../') +var test = require('tap').test + +var data = { + 'number': {count: 10}, + 'string': {drink: 'white russian'}, + 'boolean': {isTrue: true}, + 'nested boolean': {theDude: {abides: true, rugCount: 1}} +} + + +test('parse(stringify(x)) deepEqual x', function (t) { + + for (var k in data) { + var s = ini.stringify(data[k]) + console.log(s, data[k]) + t.deepEqual(ini.parse(s), data[k]) + } + + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/fixtures/foo.ini b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/fixtures/foo.ini new file mode 100644 index 0000000..fc2080f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/fixtures/foo.ini @@ -0,0 +1,65 @@ +o = p + + a with spaces = b c + +; wrap in quotes to JSON-decode and preserve spaces +" xa n p " = "\"\r\nyoyoyo\r\r\n" + +; wrap in quotes to get a key with a bracket, not a section. +"[disturbing]" = hey you never know + +; Test single quotes +s = 'something' + +; Test mixing quotes + +s1 = "something' + +; Test double quotes +s2 = "something else" + +; Test arrays +zr[] = deedee +ar[] = one +ar[] = three +; This should be included in the array +ar = this is included + +; Test resetting of a value (and not turn it into an array) +br = cold +br = warm + +eq = "eq=eq" + +; a section +[a] +av = a val +e = { o: p, a: { av: a val, b: { c: { e: "this [value]" } } } } +j = "{ o: "p", a: { av: "a val", b: { c: { e: "this [value]" } } } }" +"[]" = a square? + +; Nested array +cr[] = four +cr[] = eight + +; nested child without middle parent +; should create otherwise-empty a.b +[a.b.c] +e = 1 +j = 2 + +; dots in the section name should be literally interpreted +[x\.y\.z] +x.y.z = xyz + +[x\.y\.z.a\.b\.c] +a.b.c = abc + +; this next one is not a comment! it's escaped! +nocomment = this\; this is not a comment + +# Support the use of the number sign (#) as an alternative to the semicolon for indicating comments. +# http://en.wikipedia.org/wiki/INI_file#Comments + +# this next one is not a comment! it's escaped! +noHashComment = this\# this is not a comment diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/foo.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/foo.js new file mode 100644 index 0000000..58102d1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/ini/test/foo.js @@ -0,0 +1,107 @@ +var i = require("../") + , tap = require("tap") + , test = tap.test + , fs = require("fs") + , path = require("path") + , fixture = path.resolve(__dirname, "./fixtures/foo.ini") + , data = fs.readFileSync(fixture, "utf8") + , d + , expectE = 'o=p\n' + + 'a with spaces=b c\n' + + '" xa n p "="\\"\\r\\nyoyoyo\\r\\r\\n"\n' + + '"[disturbing]"=hey you never know\n' + + 's=something\n' + + 's1=\"something\'\n' + + 's2=something else\n' + + 'zr[]=deedee\n' + + 'ar[]=one\n' + + 'ar[]=three\n' + + 'ar[]=this is included\n' + + 'br=warm\n' + + 'eq=\"eq=eq\"\n' + + '\n' + + '[a]\n' + + 'av=a val\n' + + 'e={ o: p, a: ' + + '{ av: a val, b: { c: { e: "this [value]" ' + + '} } } }\nj="\\"{ o: \\"p\\", a: { av:' + + ' \\"a val\\", b: { c: { e: \\"this [value]' + + '\\" } } } }\\""\n"[]"=a square?\n' + + 'cr[]=four\ncr[]=eight\n\n' + +'[a.b.c]\ne=1\n' + + 'j=2\n\n[x\\.y\\.z]\nx.y.z=xyz\n\n' + + '[x\\.y\\.z.a\\.b\\.c]\na.b.c=abc\n' + + 'nocomment=this\\; this is not a comment\n' + + 'noHashComment=this\\# this is not a comment\n' + , expectD = + { o: 'p', + 'a with spaces': 'b c', + " xa n p ":'"\r\nyoyoyo\r\r\n', + '[disturbing]': 'hey you never know', + 's': 'something', + 's1' : '\"something\'', + 's2': 'something else', + 'zr': ['deedee'], + 'ar': ['one', 'three', 'this is included'], + 'br': 'warm', + 'eq': 'eq=eq', + a: + { av: 'a val', + e: '{ o: p, a: { av: a val, b: { c: { e: "this [value]" } } } }', + j: '"{ o: "p", a: { av: "a val", b: { c: { e: "this [value]" } } } }"', + "[]": "a square?", + cr: ['four', 'eight'], + b: { c: { e: '1', j: '2' } } }, + 'x.y.z': { + 'x.y.z': 'xyz', + 'a.b.c': { + 'a.b.c': 'abc', + 'nocomment': 'this\; this is not a comment', + noHashComment: 'this\# this is not a comment' + } + } + } + , expectF = '[prefix.log]\n' + + 'type=file\n\n' + + '[prefix.log.level]\n' + + 'label=debug\n' + + 'value=10\n' + , expectG = '[log]\n' + + 'type = file\n\n' + + '[log.level]\n' + + 'label = debug\n' + + 'value = 10\n' + +test("decode from file", function (t) { + var d = i.decode(data) + t.deepEqual(d, expectD) + t.end() +}) + +test("encode from data", function (t) { + var e = i.encode(expectD) + t.deepEqual(e, expectE) + + var obj = {log: { type:'file', level: {label:'debug', value:10} } } + e = i.encode(obj) + t.notEqual(e.slice(0, 1), '\n', 'Never a blank first line') + t.notEqual(e.slice(-2), '\n\n', 'Never a blank final line') + + t.end() +}) + +test("encode with option", function (t) { + var obj = {log: { type:'file', level: {label:'debug', value:10} } } + e = i.encode(obj, {section: 'prefix'}) + + t.equal(e, expectF) + t.end() +}) + +test("encode with whitespace", function (t) { + var obj = {log: { type:'file', level: {label:'debug', value:10} } } + e = i.encode(obj, {whitespace: true}) + + t.equal(e, expectG) + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/example/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/example/parse.js new file mode 100644 index 0000000..abff3e8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.dir(argv); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/index.js new file mode 100644 index 0000000..71fb830 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/index.js @@ -0,0 +1,187 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {} }; + + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function setArg (key, val) { + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + setArg(m[1], m[2]); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2)); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !flags.bools[aliases[key]] : true)) { + setArg(key, args[i+1]); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true'); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true); + } + } + } + else { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + notFlags.forEach(function(key) { + argv._.push(key); + }); + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/package.json new file mode 100644 index 0000000..a4059f3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/package.json @@ -0,0 +1,52 @@ +{ + "name": "minimist", + "version": "0.0.10", + "description": "parse argument options", + "main": "index.js", + "devDependencies": { + "tape": "~1.0.4", + "tap": "~0.4.0" + }, + "scripts": { + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "readme": "# minimist\n\nparse argument options\n\nThis module is the guts of optimist's argument parser without all the\nfanciful decoration.\n\n[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist)\n\n[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist)\n\n# example\n\n``` js\nvar argv = require('minimist')(process.argv.slice(2));\nconsole.dir(argv);\n```\n\n```\n$ node example/parse.js -a beep -b boop\n{ _: [], a: 'beep', b: 'boop' }\n```\n\n```\n$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz\n{ _: [ 'foo', 'bar', 'baz' ],\n x: 3,\n y: 4,\n n: 5,\n a: true,\n b: true,\n c: true,\n beep: 'boop' }\n```\n\n# methods\n\n``` js\nvar parseArgs = require('minimist')\n```\n\n## var argv = parseArgs(args, opts={})\n\nReturn an argument object `argv` populated with the array arguments from `args`.\n\n`argv._` contains all the arguments that didn't have an option associated with\nthem.\n\nNumeric-looking arguments will be returned as numbers unless `opts.string` or\n`opts.boolean` is set for that argument name.\n\nAny arguments after `'--'` will not be parsed and will end up in `argv._`.\n\noptions can be:\n\n* `opts.string` - a string or array of strings argument names to always treat as\nstrings\n* `opts.boolean` - a string or array of strings to always treat as booleans\n* `opts.alias` - an object mapping string names to strings or arrays of string\nargument names to use as aliases\n* `opts.default` - an object mapping string argument names to default values\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install minimist\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "_id": "minimist@0.0.10", + "_shasum": "de3f98543dbf96082be48ad1a0c7cda836301dcf", + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", + "_from": "minimist@>=0.0.7 <0.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/readme.markdown b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/readme.markdown new file mode 100644 index 0000000..c256353 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/readme.markdown @@ -0,0 +1,73 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) + +[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.dir(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a string or array of strings to always treat as booleans +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/bool.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/bool.js new file mode 100644 index 0000000..749e083 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/bool.js @@ -0,0 +1,119 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dash.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dash.js new file mode 100644 index 0000000..8b034b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dash.js @@ -0,0 +1,24 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/default_bool.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000..f0041ee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/default_bool.js @@ -0,0 +1,20 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dotted.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000..d8b3e85 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/dotted.js @@ -0,0 +1,22 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); + +test('dotted default with no alias', function (t) { + var argv = parse('', {default: {'a.b': 11}}); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/long.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/long.js new file mode 100644 index 0000000..5d3a1e0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/num.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/num.js new file mode 100644 index 0000000..2cc77f4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/num.js @@ -0,0 +1,36 @@ +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse([ '-x', 1234, 789 ]); + t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse.js new file mode 100644 index 0000000..7b4a2a1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse.js @@ -0,0 +1,197 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('string and alias', function(t) { + var x = parse([ '--str', '000123' ], { + string: 's', + alias: { s: 'str' } + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse([ '-s', '000123' ], { + string: 'str', + alias: { str: 's' } + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + t.end(); +}); + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse_modified.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000..21851b0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: ['123'] }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/short.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/short.js new file mode 100644 index 0000000..d513a1c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/whitespace.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000..8a52a58 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/cli.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/cli.js new file mode 100755 index 0000000..ac4da48 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/cli.js @@ -0,0 +1,41 @@ +#!/usr/bin/env node +'use strict'; +var fs = require('fs'); +var strip = require('./strip-json-comments'); +var input = process.argv[2]; + + +function getStdin(cb) { + var ret = ''; + + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', function (data) { + ret += data; + }); + + process.stdin.on('end', function () { + cb(ret); + }); +} + +if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) { + console.log('strip-json-comments > '); + console.log('or'); + console.log('cat | strip-json-comments > '); + return; +} + +if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) { + console.log(require('./package').version); + return; +} + +if (input) { + process.stdout.write(strip(fs.readFileSync(input, 'utf8'))); + return; +} + +getStdin(function (data) { + process.stdout.write(strip(data)); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/package.json new file mode 100644 index 0000000..119d4ea --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/package.json @@ -0,0 +1,61 @@ +{ + "name": "strip-json-comments", + "version": "0.1.3", + "description": "Strip comments from JSON. Lets you use comments in your JSON files!", + "keywords": [ + "json", + "strip", + "remove", + "delete", + "trim", + "comments", + "multiline", + "parse", + "config", + "configuration", + "conf", + "settings", + "util", + "env", + "environment", + "cli", + "bin" + ], + "license": "MIT", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "files": [ + "cli.js", + "strip-json-comments.js" + ], + "main": "strip-json-comments", + "bin": { + "strip-json-comments": "cli.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/strip-json-comments.git" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "*" + }, + "engines": { + "node": ">=0.8.0" + }, + "readme": "# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments)\n\n> Strip comments from JSON. Lets you use comments in your JSON files!\n\nThis is now possible:\n\n```js\n{\n\t// rainbows\n\t\"unicorn\": /* ❤ */ \"cake\"\n}\n```\n\nIt will remove single-line comments `//` and mult-line comments `/**/`.\n\nAlso available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin and a [require hook](https://github.com/uTest/autostrip-json-comments).\n\n\n*There's already [json-comments](https://npmjs.org/package/json-comments), but it's only for Node.js and uses a naive regex to strip comments which fails on simple cases like `{\"a\":\"//\"}`. This module however parses out the comments.*\n\n\n## Install\n\n```sh\n$ npm install --save strip-json-comments\n```\n\n```sh\n$ bower install --save strip-json-comments\n```\n\n```sh\n$ component install sindresorhus/strip-json-comments\n```\n\n\n## Usage\n\n```js\nvar json = '{/*rainbows*/\"unicorn\":\"cake\"}';\nJSON.parse(stripJsonComments(json));\n//=> {unicorn: 'cake'}\n```\n\n\n## API\n\n### stripJsonComments(input)\n\n#### input\n\nType: `string`\n\nAccepts a string with JSON and returns a string without comments.\n\n\n## CLI\n\n```sh\n$ npm install --global strip-json-comments\n```\n\n```sh\n$ strip-json-comments --help\n\nstrip-json-comments > \n# or\ncat | strip-json-comments > \n```\n\n\n## License\n\nMIT © [Sindre Sorhus](http://sindresorhus.com)\n", + "readmeFilename": "readme.md", + "bugs": { + "url": "https://github.com/sindresorhus/strip-json-comments/issues" + }, + "homepage": "https://github.com/sindresorhus/strip-json-comments#readme", + "_id": "strip-json-comments@0.1.3", + "_shasum": "164c64e370a8a3cc00c9e01b539e569823f0ee54", + "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-0.1.3.tgz", + "_from": "strip-json-comments@>=0.1.0 <0.2.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/readme.md new file mode 100644 index 0000000..ad6a178 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/readme.md @@ -0,0 +1,74 @@ +# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments) + +> Strip comments from JSON. Lets you use comments in your JSON files! + +This is now possible: + +```js +{ + // rainbows + "unicorn": /* ❤ */ "cake" +} +``` + +It will remove single-line comments `//` and mult-line comments `/**/`. + +Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin and a [require hook](https://github.com/uTest/autostrip-json-comments). + + +*There's already [json-comments](https://npmjs.org/package/json-comments), but it's only for Node.js and uses a naive regex to strip comments which fails on simple cases like `{"a":"//"}`. This module however parses out the comments.* + + +## Install + +```sh +$ npm install --save strip-json-comments +``` + +```sh +$ bower install --save strip-json-comments +``` + +```sh +$ component install sindresorhus/strip-json-comments +``` + + +## Usage + +```js +var json = '{/*rainbows*/"unicorn":"cake"}'; +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` + + +## API + +### stripJsonComments(input) + +#### input + +Type: `string` + +Accepts a string with JSON and returns a string without comments. + + +## CLI + +```sh +$ npm install --global strip-json-comments +``` + +```sh +$ strip-json-comments --help + +strip-json-comments > +# or +cat | strip-json-comments > +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/strip-json-comments.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/strip-json-comments.js new file mode 100644 index 0000000..2e7fdef --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/node_modules/strip-json-comments/strip-json-comments.js @@ -0,0 +1,64 @@ +/*! + strip-json-comments + Strip comments from JSON. Lets you use comments in your JSON files! + https://github.com/sindresorhus/strip-json-comments + by Sindre Sorhus + MIT License +*/ +(function () { + 'use strict'; + + function stripJsonComments(str) { + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var ret = ''; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && str[i - 1] !== '\\' && currentChar === '"') { + insideString = !insideString; + } + + if (insideString) { + ret += currentChar; + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + insideComment = 'single'; + i++; + } else if (insideComment === 'single' && currentChar + nextChar === '\r\n') { + insideComment = false; + i++; + } else if (insideComment === 'single' && currentChar === '\n') { + insideComment = false; + } else if (!insideComment && currentChar + nextChar === '/*') { + insideComment = 'multi'; + i++; + continue; + } else if (insideComment === 'multi' && currentChar + nextChar === '*/') { + insideComment = false; + i++; + continue; + } + + if (insideComment) { + continue; + } + + ret += currentChar; + } + + return ret; + } + + if (typeof module !== 'undefined' && module.exports) { + module.exports = stripJsonComments; + } else { + window.stripJsonComments = stripJsonComments; + } +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/package.json new file mode 100644 index 0000000..29440c9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/package.json @@ -0,0 +1,60 @@ +{ + "name": "rc", + "version": "1.0.3", + "description": "hardwired configuration loader", + "main": "index.js", + "browserify": "browser.js", + "scripts": { + "test": "set -e; node test/test.js; node test/ini.js; node test/nested-env-vars.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/dominictarr/rc.git" + }, + "license": "(BSD OR MIT OR Apache2)", + "keywords": [ + "config", + "rc", + "unix", + "defaults" + ], + "bin": { + "rc": "./index.js" + }, + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "dependencies": { + "minimist": "~0.0.7", + "deep-extend": "~0.2.5", + "strip-json-comments": "0.1.x", + "ini": "~1.3.0" + }, + "gitHead": "2a4f80785efa317eaf38499fa1f9dcd3c60e54e9", + "bugs": { + "url": "https://github.com/dominictarr/rc/issues" + }, + "homepage": "https://github.com/dominictarr/rc", + "_id": "rc@1.0.3", + "_shasum": "51bf28d21f13a9324528a9633460161ad9a39f77", + "_from": "rc@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dominictarr", + "email": "dominic.tarr@gmail.com" + }, + "maintainers": [ + { + "name": "dominictarr", + "email": "dominic.tarr@gmail.com" + } + ], + "dist": { + "shasum": "51bf28d21f13a9324528a9633460161ad9a39f77", + "tarball": "http://registry.npmjs.org/rc/-/rc-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/rc/-/rc-1.0.3.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/ini.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/ini.js new file mode 100644 index 0000000..e6857f8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/ini.js @@ -0,0 +1,16 @@ +var cc =require('../lib/utils') +var INI = require('ini') +var assert = require('assert') + +function test(obj) { + + var _json, _ini + var json = cc.parse (_json = JSON.stringify(obj)) + var ini = cc.parse (_ini = INI.stringify(obj)) + console.log(_ini, _json) + assert.deepEqual(json, ini) +} + + +test({hello: true}) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/nested-env-vars.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/nested-env-vars.js new file mode 100644 index 0000000..314979f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/nested-env-vars.js @@ -0,0 +1,39 @@ + +var n = 'rc'+Math.random() +var assert = require('assert') + + +// Basic usage +process.env[n+'_someOpt__a'] = 42 +process.env[n+'_someOpt__x__'] = 99 +process.env[n+'_someOpt__a__b'] = 186 +process.env[n+'_someOpt__x__y'] = 1862 +process.env[n+'_someOpt__z'] = 186577 + +// Should ignore empty strings from orphaned '__' +process.env[n+'_someOpt__z__x__'] = 18629 +process.env[n+'_someOpt__w__w__'] = 18629 + +// Leading '__' should ignore everything up to 'z' +process.env[n+'___z__i__'] = 9999 + +var config = require('../')(n, { + option: true +}) + +console.log('\n\n------ nested-env-vars ------\n',config) + +assert.equal(config.option, true) +assert.equal(config.someOpt.a, 42) +assert.equal(config.someOpt.x, 99) +// Should not override `a` once it's been set +assert.equal(config.someOpt.a/*.b*/, 42) +// Should not override `x` once it's been set +assert.equal(config.someOpt.x/*.y*/, 99) +assert.equal(config.someOpt.z, 186577) +// Should not override `z` once it's been set +assert.equal(config.someOpt.z/*.x*/, 186577) +assert.equal(config.someOpt.w.w, 18629) +assert.equal(config.z.i, 9999) + + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/test.js new file mode 100644 index 0000000..4f63351 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rc/test/test.js @@ -0,0 +1,59 @@ + +var n = 'rc'+Math.random() +var assert = require('assert') + +process.env[n+'_envOption'] = 42 + +var config = require('../')(n, { + option: true +}) + +console.log(config) + +assert.equal(config.option, true) +assert.equal(config.envOption, 42) + +var customArgv = require('../')(n, { + option: true +}, { // nopt-like argv + option: false, + envOption: 24, + argv: { + remain: [], + cooked: ['--no-option', '--envOption', '24'], + original: ['--no-option', '--envOption=24'] + } +}) + +console.log(customArgv) + +assert.equal(customArgv.option, false) +assert.equal(customArgv.envOption, 24) + +var fs = require('fs') +var path = require('path') +var jsonrc = path.resolve('.' + n + 'rc'); + +fs.writeFileSync(jsonrc, [ + '{', + '// json overrides default', + '"option": false,', + '/* env overrides json */', + '"envOption": 24', + '}' +].join('\n')); + +var commentedJSON = require('../')(n, { + option: true +}) + +fs.unlinkSync(jsonrc); + +console.log(commentedJSON) + +assert.equal(commentedJSON.option, false) +assert.equal(commentedJSON.envOption, 42) + +assert.equal(commentedJSON.config, jsonrc) +assert.equal(commentedJSON.configs.length, 1) +assert.equal(commentedJSON.configs[0], jsonrc) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.eslintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.eslintrc new file mode 100644 index 0000000..e79f481 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.eslintrc @@ -0,0 +1,45 @@ +{ + "env": { + "node": true + }, + "rules": { + // 2-space indentation + "indent": [2, 2], + // Disallow semi-colons, unless needed to disambiguate statement + "semi": [2, "never"], + // Require strings to use single quotes + "quotes": [2, "single"], + // Require curly braces for all control statements + "curly": 2, + // Disallow using variables and functions before they've been defined + "no-use-before-define": 2, + // Allow any case for variable naming + "camelcase": 0, + // Disallow unused variables, except as function arguments + "no-unused-vars": [2, {"args":"none"}], + // Allow leading underscores for method names + // REASON: we use underscores to denote private methods + "no-underscore-dangle": 0, + // Allow multi spaces around operators since they are + // used for alignment. This is not consistent in the + // code. + "no-multi-spaces": 0, + // Style rule is: most objects use { beforeColon: false, afterColon: true }, unless aligning which uses: + // + // { + // beforeColon : true, + // afterColon : true + // } + // + // eslint can't handle this, so the check is disabled. + "key-spacing": 0, + // Allow shadowing vars in outer scope (needs discussion) + "no-shadow": 0, + // Use if () { } + // ^ space + "space-after-keywords": [2, "always"], + // Use if () { } + // ^ space + "space-before-blocks": [2, "always"] + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.npmignore new file mode 100644 index 0000000..53fc9ef --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.npmignore @@ -0,0 +1,3 @@ +coverage +tests +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.travis.yml new file mode 100644 index 0000000..bd0f638 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "io.js" + - "0.12" + - "0.10" +after_script: ./node_modules/.bin/istanbul cover ./node_modules/tape/bin/tape tests/test-*.js --report lcovonly && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js --verbose +webhooks: + urls: https://webhooks.gitter.im/e/237280ed4796c19cc626 + on_success: change # options: [always|never|change] default: always + on_failure: always # options: [always|never|change] default: always + on_start: false # default: false +sudo: false diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CHANGELOG.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CHANGELOG.md new file mode 100644 index 0000000..2de0061 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CHANGELOG.md @@ -0,0 +1,493 @@ +## Change Log + +### v2.57.0 (2015/05/31) +- [#1615](https://github.com/request/request/pull/1615) Replace '.client' with '.socket' as the former was deprecated in 2.2.0. (@ChALkeR) + +### v2.56.0 (2015/05/28) +- [#1610](https://github.com/request/request/pull/1610) Bump module dependencies (@simov) +- [#1600](https://github.com/request/request/pull/1600) Extract the querystring logic into separate module (@simov) +- [#1607](https://github.com/request/request/pull/1607) Re-generate certificates (@simov) +- [#1599](https://github.com/request/request/pull/1599) Move getProxyFromURI logic below the check for Invaild URI (#1595) (@simov) +- [#1598](https://github.com/request/request/pull/1598) Fix the way http verbs are defined in order to please intellisense IDEs (@simov, @flannelJesus) +- [#1591](https://github.com/request/request/pull/1591) A few minor fixes: (@simov) +- [#1584](https://github.com/request/request/pull/1584) Refactor test-default tests (according to comments in #1430) (@simov) +- [#1585](https://github.com/request/request/pull/1585) Fixing documentation regarding TLS options (#1583) (@mainakae) +- [#1574](https://github.com/request/request/pull/1574) Refresh the oauth_nonce on redirect (#1573) (@simov) +- [#1570](https://github.com/request/request/pull/1570) Discovered tests that weren't properly running (@seanstrom) +- [#1569](https://github.com/request/request/pull/1569) Fix pause before response arrives (@kevinoid) +- [#1558](https://github.com/request/request/pull/1558) Emit error instead of throw (@simov) +- [#1568](https://github.com/request/request/pull/1568) Fix stall when piping gzipped response (@kevinoid) +- [#1560](https://github.com/request/request/pull/1560) Update combined-stream (@apechimp) +- [#1543](https://github.com/request/request/pull/1543) Initial support for oauth_body_hash on json payloads (@simov, @aesopwolf) +- [#1541](https://github.com/request/request/pull/1541) Fix coveralls (@simov) +- [#1540](https://github.com/request/request/pull/1540) Fix recursive defaults for convenience methods (@simov) +- [#1536](https://github.com/request/request/pull/1536) More eslint style rules (@froatsnook) +- [#1533](https://github.com/request/request/pull/1533) Adding dependency status bar to README.md (@YasharF) +- [#1539](https://github.com/request/request/pull/1539) ensure the latest version of har-validator is included (@ahmadnassri) +- [#1516](https://github.com/request/request/pull/1516) forever+pool test (@devTristan) + +### v2.55.0 (2015/04/05) +- [#1520](https://github.com/request/request/pull/1520) Refactor defaults (@simov) +- [#1525](https://github.com/request/request/pull/1525) Delete request headers with undefined value. (@froatsnook) +- [#1521](https://github.com/request/request/pull/1521) Add promise tests (@simov) +- [#1518](https://github.com/request/request/pull/1518) Fix defaults (@simov) +- [#1515](https://github.com/request/request/pull/1515) Allow static invoking of convenience methods (@simov) +- [#1505](https://github.com/request/request/pull/1505) Fix multipart boundary extraction regexp (@simov) +- [#1510](https://github.com/request/request/pull/1510) Fix basic auth form data (@simov) + +### v2.54.0 (2015/03/24) +- [#1501](https://github.com/request/request/pull/1501) HTTP Archive 1.2 support (@ahmadnassri) +- [#1486](https://github.com/request/request/pull/1486) Add a test for the forever agent (@akshayp) +- [#1500](https://github.com/request/request/pull/1500) Adding handling for no auth method and null bearer (@philberg) +- [#1498](https://github.com/request/request/pull/1498) Add table of contents in readme (@simov) +- [#1477](https://github.com/request/request/pull/1477) Add support for qs options via qsOptions key (@simov) +- [#1496](https://github.com/request/request/pull/1496) Parameters encoded to base 64 should be decoded as UTF-8, not ASCII. (@albanm) +- [#1494](https://github.com/request/request/pull/1494) Update eslint (@froatsnook) +- [#1474](https://github.com/request/request/pull/1474) Require Colon in Basic Auth (@erykwalder) +- [#1481](https://github.com/request/request/pull/1481) Fix baseUrl and redirections. (@burningtree) +- [#1469](https://github.com/request/request/pull/1469) Feature/base url (@froatsnook) +- [#1459](https://github.com/request/request/pull/1459) Add option to time request/response cycle (including rollup of redirects) (@aaron-em) +- [#1468](https://github.com/request/request/pull/1468) Re-enable io.js/node 0.12 build (@simov, @mikeal, @BBB) +- [#1442](https://github.com/request/request/pull/1442) Fixed the issue with strictSSL tests on 0.12 & io.js by explicitly setting a cipher that matches the cert. (@BBB, @nicolasmccurdy, @simov, @0x4139) +- [#1460](https://github.com/request/request/pull/1460) localAddress or proxy config is lost when redirecting (@simov, @0x4139) +- [#1453](https://github.com/request/request/pull/1453) Test on Node.js 0.12 and io.js with allowed failures (@nicolasmccurdy) +- [#1426](https://github.com/request/request/pull/1426) Fixing tests to pass on io.js and node 0.12 (only test-https.js stiff failing) (@mikeal) +- [#1446](https://github.com/request/request/pull/1446) Missing HTTP referer header with redirects Fixes #1038 (@simov, @guimonz) +- [#1428](https://github.com/request/request/pull/1428) Deprecate Node v0.8.x (@nylen) +- [#1436](https://github.com/request/request/pull/1436) Add ability to set a requester without setting default options (@tikotzky) +- [#1435](https://github.com/request/request/pull/1435) dry up verb methods (@sethpollack) +- [#1423](https://github.com/request/request/pull/1423) Allow fully qualified multipart content-type header (@simov) +- [#1430](https://github.com/request/request/pull/1430) Fix recursive requester (@tikotzky) +- [#1429](https://github.com/request/request/pull/1429) Throw error when making HEAD request with a body (@tikotzky) +- [#1419](https://github.com/request/request/pull/1419) Add note that the project is broken in 0.12.x (@nylen) +- [#1413](https://github.com/request/request/pull/1413) Fix basic auth (@simov) +- [#1397](https://github.com/request/request/pull/1397) Improve pipe-from-file tests (@nylen) + +### v2.53.0 (2015/02/02) +- [#1396](https://github.com/request/request/pull/1396) Do not rfc3986 escape JSON bodies (@nylen, @simov) +- [#1392](https://github.com/request/request/pull/1392) Improve `timeout` option description (@watson) + +### v2.52.0 (2015/02/02) +- [#1383](https://github.com/request/request/pull/1383) Add missing HTTPS options that were not being passed to tunnel (@brichard19) (@nylen, @brichard19) +- [#1388](https://github.com/request/request/pull/1388) Upgrade mime-types package version (@roderickhsiao) +- [#1389](https://github.com/request/request/pull/1389) Revise Setup Tunnel Function (@seanstrom) +- [#1374](https://github.com/request/request/pull/1374) Allow explicitly disabling tunneling for proxied https destinations (@nylen) +- [#1376](https://github.com/request/request/pull/1376) Use karma-browserify for tests. Add browser test coverage reporter. (@eiriksm) +- [#1366](https://github.com/request/request/pull/1366) Refactor OAuth into separate module (@simov) +- [#1373](https://github.com/request/request/pull/1373) Rewrite tunnel test to be pure Node.js (@nylen) +- [#1371](https://github.com/request/request/pull/1371) Upgrade test reporter (@nylen) +- [#1360](https://github.com/request/request/pull/1360) Refactor basic, bearer, digest auth logic into separate class (@simov) +- [#1354](https://github.com/request/request/pull/1354) Remove circular dependency from debugging code (@nylen) +- [#1351](https://github.com/request/request/pull/1351) Move digest auth into private prototype method (@simov) +- [#1352](https://github.com/request/request/pull/1352) Update hawk dependency to ~2.3.0 (@mridgway) +- [#1353](https://github.com/request/request/pull/1353) Correct travis-ci badge (@dogancelik) +- [#1349](https://github.com/request/request/pull/1349) Make sure we return on errored browser requests. (@eiriksm) +- [#1346](https://github.com/request/request/pull/1346) getProxyFromURI Extraction Refactor (@seanstrom) +- [#1337](https://github.com/request/request/pull/1337) Standardize test ports on 6767 (@nylen) +- [#1341](https://github.com/request/request/pull/1341) Emit FormData error events as Request error events (@nylen, @rwky) +- [#1343](https://github.com/request/request/pull/1343) Clean up readme badges, and add Travis and Coveralls badges (@nylen) +- [#1345](https://github.com/request/request/pull/1345) Update README.md (@Aaron-Hartwig) +- [#1338](https://github.com/request/request/pull/1338) Always wait for server.close() callback in tests (@nylen) +- [#1342](https://github.com/request/request/pull/1342) Add mock https server and redo start of browser tests for this purpose. (@eiriksm) +- [#1339](https://github.com/request/request/pull/1339) Improve auth docs (@nylen) +- [#1335](https://github.com/request/request/pull/1335) Add support for OAuth plaintext signature method (@simov) +- [#1332](https://github.com/request/request/pull/1332) Add clean script to remove test-browser.js after the tests run (@seanstrom) +- [#1327](https://github.com/request/request/pull/1327) Fix errors generating coverage reports. (@nylen) +- [#1330](https://github.com/request/request/pull/1330) Return empty buffer upon empty response body and encoding is set to null (@seanstrom) +- [#1326](https://github.com/request/request/pull/1326) Use faster container-based infrastructure on Travis (@nylen) +- [#1315](https://github.com/request/request/pull/1315) Implement rfc3986 option (@simov, @nylen, @apoco, @DullReferenceException, @mmalecki, @oliamb, @cliffcrosland, @LewisJEllis, @eiriksm, @poislagarde) +- [#1314](https://github.com/request/request/pull/1314) Detect urlencoded form data header via regex (@simov) +- [#1317](https://github.com/request/request/pull/1317) Improve OAuth1.0 server side flow example (@simov) + +### v2.51.0 (2014/12/10) +- [#1310](https://github.com/request/request/pull/1310) Revert changes introduced in https://github.com/request/request/pull/1282 (@simov) + +### v2.50.0 (2014/12/09) +- [#1308](https://github.com/request/request/pull/1308) Add browser test to keep track of browserify compability. (@eiriksm) +- [#1299](https://github.com/request/request/pull/1299) Add optional support for jsonReviver (@poislagarde) +- [#1277](https://github.com/request/request/pull/1277) Add Coveralls configuration (@simov) +- [#1307](https://github.com/request/request/pull/1307) Upgrade form-data, add back browserify compability. Fixes #455. (@eiriksm) +- [#1305](https://github.com/request/request/pull/1305) Fix typo in README.md (@LewisJEllis) +- [#1288](https://github.com/request/request/pull/1288) Update README.md to explain custom file use case (@cliffcrosland) + +### v2.49.0 (2014/11/28) +- [#1295](https://github.com/request/request/pull/1295) fix(proxy): no-proxy false positive (@oliamb) +- [#1292](https://github.com/request/request/pull/1292) Upgrade `caseless` to 0.8.1 (@mmalecki) +- [#1276](https://github.com/request/request/pull/1276) Set transfer encoding for multipart/related to chunked by default (@simov) +- [#1275](https://github.com/request/request/pull/1275) Fix multipart content-type headers detection (@simov) +- [#1269](https://github.com/request/request/pull/1269) adds streams example for review (@tbuchok) +- [#1238](https://github.com/request/request/pull/1238) Add examples README.md (@simov) + +### v2.48.0 (2014/11/12) +- [#1263](https://github.com/request/request/pull/1263) Fixed a syntax error / typo in README.md (@xna2) +- [#1253](https://github.com/request/request/pull/1253) Add multipart chunked flag (@simov, @nylen) +- [#1251](https://github.com/request/request/pull/1251) Clarify that defaults() does not modify global defaults (@nylen) +- [#1250](https://github.com/request/request/pull/1250) Improve documentation for pool and maxSockets options (@nylen) +- [#1237](https://github.com/request/request/pull/1237) Documenting error handling when using streams (@vmattos) +- [#1244](https://github.com/request/request/pull/1244) Finalize changelog command (@nylen) +- [#1241](https://github.com/request/request/pull/1241) Fix typo (@alexanderGugel) +- [#1223](https://github.com/request/request/pull/1223) Show latest version number instead of "upcoming" in changelog (@nylen) +- [#1236](https://github.com/request/request/pull/1236) Document how to use custom CA in README (#1229) (@hypesystem) +- [#1228](https://github.com/request/request/pull/1228) Support for oauth with RSA-SHA1 signing (@nylen) +- [#1216](https://github.com/request/request/pull/1216) Made json and multipart options coexist (@nylen, @simov) +- [#1225](https://github.com/request/request/pull/1225) Allow header white/exclusive lists in any case. (@RReverser) + +### v2.47.0 (2014/10/26) +- [#1222](https://github.com/request/request/pull/1222) Move from mikeal/request to request/request (@nylen) +- [#1220](https://github.com/request/request/pull/1220) update qs dependency to 2.3.1 (@FredKSchott) +- [#1212](https://github.com/request/request/pull/1212) Improve tests/test-timeout.js (@nylen) +- [#1219](https://github.com/request/request/pull/1219) remove old globalAgent workaround for node 0.4 (@request) +- [#1214](https://github.com/request/request/pull/1214) Remove cruft left over from optional dependencies (@nylen) +- [#1215](https://github.com/request/request/pull/1215) Add proxyHeaderExclusiveList option for proxy-only headers. (@RReverser) +- [#1211](https://github.com/request/request/pull/1211) Allow 'Host' header instead of 'host' and remember case across redirects (@nylen) +- [#1208](https://github.com/request/request/pull/1208) Improve release script (@nylen) +- [#1213](https://github.com/request/request/pull/1213) Support for custom cookie store (@nylen, @mitsuru) +- [#1197](https://github.com/request/request/pull/1197) Clean up some code around setting the agent (@FredKSchott) +- [#1209](https://github.com/request/request/pull/1209) Improve multipart form append test (@simov) +- [#1207](https://github.com/request/request/pull/1207) Update changelog (@nylen) +- [#1185](https://github.com/request/request/pull/1185) Stream multipart/related bodies (@simov) + +### v2.46.0 (2014/10/23) +- [#1198](https://github.com/request/request/pull/1198) doc for TLS/SSL protocol options (@shawnzhu) +- [#1200](https://github.com/request/request/pull/1200) Add a Gitter chat badge to README.md (@gitter-badger) +- [#1196](https://github.com/request/request/pull/1196) Upgrade taper test reporter to v0.3.0 (@nylen) +- [#1199](https://github.com/request/request/pull/1199) Fix lint error: undeclared var i (@nylen) +- [#1191](https://github.com/request/request/pull/1191) Move self.proxy decision logic out of init and into a helper (@FredKSchott) +- [#1190](https://github.com/request/request/pull/1190) Move _buildRequest() logic back into init (@FredKSchott) +- [#1186](https://github.com/request/request/pull/1186) Support Smarter Unix URL Scheme (@FredKSchott) +- [#1178](https://github.com/request/request/pull/1178) update form documentation for new usage (@FredKSchott) +- [#1180](https://github.com/request/request/pull/1180) Enable no-mixed-requires linting rule (@nylen) +- [#1184](https://github.com/request/request/pull/1184) Don't forward authorization header across redirects to different hosts (@nylen) +- [#1183](https://github.com/request/request/pull/1183) Correct README about pre and postamble CRLF using multipart and not mult... (@netpoetica) +- [#1179](https://github.com/request/request/pull/1179) Lint tests directory (@nylen) +- [#1169](https://github.com/request/request/pull/1169) add metadata for form-data file field (@dotcypress) +- [#1173](https://github.com/request/request/pull/1173) remove optional dependencies (@seanstrom) +- [#1165](https://github.com/request/request/pull/1165) Cleanup event listeners and remove function creation from init (@FredKSchott) +- [#1174](https://github.com/request/request/pull/1174) update the request.cookie docs to have a valid cookie example (@seanstrom) +- [#1168](https://github.com/request/request/pull/1168) create a detach helper and use detach helper in replace of nextTick (@seanstrom) +- [#1171](https://github.com/request/request/pull/1171) in post can send form data and use callback (@MiroRadenovic) +- [#1159](https://github.com/request/request/pull/1159) accept charset for x-www-form-urlencoded content-type (@seanstrom) +- [#1157](https://github.com/request/request/pull/1157) Update README.md: body with json=true (@Rob--W) +- [#1164](https://github.com/request/request/pull/1164) Disable tests/test-timeout.js on Travis (@nylen) +- [#1153](https://github.com/request/request/pull/1153) Document how to run a single test (@nylen) +- [#1144](https://github.com/request/request/pull/1144) adds documentation for the "response" event within the streaming section (@tbuchok) +- [#1162](https://github.com/request/request/pull/1162) Update eslintrc file to no longer allow past errors (@FredKSchott) +- [#1155](https://github.com/request/request/pull/1155) Support/use self everywhere (@seanstrom) +- [#1161](https://github.com/request/request/pull/1161) fix no-use-before-define lint warnings (@emkay) +- [#1156](https://github.com/request/request/pull/1156) adding curly brackets to get rid of lint errors (@emkay) +- [#1151](https://github.com/request/request/pull/1151) Fix localAddress test on OS X (@nylen) +- [#1145](https://github.com/request/request/pull/1145) documentation: fix outdated reference to setCookieSync old name in README (@FredKSchott) +- [#1131](https://github.com/request/request/pull/1131) Update pool documentation (@FredKSchott) +- [#1143](https://github.com/request/request/pull/1143) Rewrite all tests to use tape (@nylen) +- [#1137](https://github.com/request/request/pull/1137) Add ability to specifiy querystring lib in options. (@jgrund) +- [#1138](https://github.com/request/request/pull/1138) allow hostname and port in place of host on uri (@cappslock) +- [#1134](https://github.com/request/request/pull/1134) Fix multiple redirects and `self.followRedirect` (@blakeembrey) +- [#1130](https://github.com/request/request/pull/1130) documentation fix: add note about npm test for contributing (@FredKSchott) +- [#1120](https://github.com/request/request/pull/1120) Support/refactor request setup tunnel (@seanstrom) +- [#1129](https://github.com/request/request/pull/1129) linting fix: convert double quote strings to use single quotes (@FredKSchott) +- [#1124](https://github.com/request/request/pull/1124) linting fix: remove unneccesary semi-colons (@FredKSchott) + +### v2.45.0 (2014/10/06) +- [#1128](https://github.com/request/request/pull/1128) Add test for setCookie regression (@nylen) +- [#1127](https://github.com/request/request/pull/1127) added tests around using objects as values in a query string (@bcoe) +- [#1103](https://github.com/request/request/pull/1103) Support/refactor request constructor (@nylen, @seanstrom) +- [#1119](https://github.com/request/request/pull/1119) add basic linting to request library (@FredKSchott) +- [#1121](https://github.com/request/request/pull/1121) Revert "Explicitly use sync versions of cookie functions" (@nylen) +- [#1118](https://github.com/request/request/pull/1118) linting fix: Restructure bad empty if statement (@FredKSchott) +- [#1117](https://github.com/request/request/pull/1117) Fix a bad check for valid URIs (@FredKSchott) +- [#1113](https://github.com/request/request/pull/1113) linting fix: space out operators (@FredKSchott) +- [#1116](https://github.com/request/request/pull/1116) Fix typo in `noProxyHost` definition (@FredKSchott) +- [#1114](https://github.com/request/request/pull/1114) linting fix: Added a `new` operator that was missing when creating and throwing a new error (@FredKSchott) +- [#1096](https://github.com/request/request/pull/1096) No_proxy support (@samcday) +- [#1107](https://github.com/request/request/pull/1107) linting-fix: remove unused variables (@FredKSchott) +- [#1112](https://github.com/request/request/pull/1112) linting fix: Make return values consistent and more straitforward (@FredKSchott) +- [#1111](https://github.com/request/request/pull/1111) linting fix: authPieces was getting redeclared (@FredKSchott) +- [#1105](https://github.com/request/request/pull/1105) Use strict mode in request (@FredKSchott) +- [#1110](https://github.com/request/request/pull/1110) linting fix: replace lazy '==' with more strict '===' (@FredKSchott) +- [#1109](https://github.com/request/request/pull/1109) linting fix: remove function call from if-else conditional statement (@FredKSchott) +- [#1102](https://github.com/request/request/pull/1102) Fix to allow setting a `requester` on recursive calls to `request.defaults` (@tikotzky) +- [#1095](https://github.com/request/request/pull/1095) Tweaking engines in package.json (@pdehaan) +- [#1082](https://github.com/request/request/pull/1082) Forward the socket event from the httpModule request (@seanstrom) +- [#972](https://github.com/request/request/pull/972) Clarify gzip handling in the README (@kevinoid) +- [#1089](https://github.com/request/request/pull/1089) Mention that encoding defaults to utf8, not Buffer (@stuartpb) +- [#1088](https://github.com/request/request/pull/1088) Fix cookie example in README.md and make it more clear (@pipi32167) +- [#1027](https://github.com/request/request/pull/1027) Add support for multipart form data in request options. (@crocket) +- [#1076](https://github.com/request/request/pull/1076) use Request.abort() to abort the request when the request has timed-out (@seanstrom) +- [#1068](https://github.com/request/request/pull/1068) add optional postamble required by .NET multipart requests (@netpoetica) + +### v2.43.0 (2014/09/18) +- [#1057](https://github.com/request/request/pull/1057) Defaults should not overwrite defined options (@davidwood) +- [#1046](https://github.com/request/request/pull/1046) Propagate datastream errors, useful in case gzip fails. (@ZJONSSON, @Janpot) +- [#1063](https://github.com/request/request/pull/1063) copy the input headers object #1060 (@finnp) +- [#1031](https://github.com/request/request/pull/1031) Explicitly use sync versions of cookie functions (@ZJONSSON) +- [#1056](https://github.com/request/request/pull/1056) Fix redirects when passing url.parse(x) as URL to convenience method (@nylen) + +### v2.42.0 (2014/09/04) +- [#1053](https://github.com/request/request/pull/1053) Fix #1051 Parse auth properly when using non-tunneling proxy (@isaacs) + +### v2.41.0 (2014/09/04) +- [#1050](https://github.com/request/request/pull/1050) Pass whitelisted headers to tunneling proxy. Organize all tunneling logic. (@isaacs, @Feldhacker) +- [#1035](https://github.com/request/request/pull/1035) souped up nodei.co badge (@rvagg) +- [#1048](https://github.com/request/request/pull/1048) Aws is now possible over a proxy (@steven-aerts) +- [#1039](https://github.com/request/request/pull/1039) extract out helper functions to a helper file (@seanstrom) +- [#1021](https://github.com/request/request/pull/1021) Support/refactor indexjs (@seanstrom) +- [#1033](https://github.com/request/request/pull/1033) Improve and document debug options (@nylen) +- [#1034](https://github.com/request/request/pull/1034) Fix readme headings (@nylen) +- [#1030](https://github.com/request/request/pull/1030) Allow recursive request.defaults (@tikotzky) +- [#1029](https://github.com/request/request/pull/1029) Fix a couple of typos (@nylen) +- [#675](https://github.com/request/request/pull/675) Checking for SSL fault on connection before reading SSL properties (@VRMink) +- [#989](https://github.com/request/request/pull/989) Added allowRedirect function. Should return true if redirect is allowed or false otherwise (@doronin) +- [#1025](https://github.com/request/request/pull/1025) [fixes #1023] Set self._ended to true once response has ended (@mridgway) +- [#1020](https://github.com/request/request/pull/1020) Add back removed debug metadata (@FredKSchott) +- [#1008](https://github.com/request/request/pull/1008) Moving to module instead of cutomer buffer concatenation. (@mikeal) +- [#770](https://github.com/request/request/pull/770) Added dependency badge for README file; (@timgluz, @mafintosh, @lalitkapoor, @stash, @bobyrizov) +- [#1016](https://github.com/request/request/pull/1016) toJSON no longer results in an infinite loop, returns simple objects (@FredKSchott) +- [#1018](https://github.com/request/request/pull/1018) Remove pre-0.4.4 HTTPS fix (@mmalecki) +- [#1006](https://github.com/request/request/pull/1006) Migrate to caseless, fixes #1001 (@mikeal) +- [#995](https://github.com/request/request/pull/995) Fix parsing array of objects (@sjonnet19) +- [#999](https://github.com/request/request/pull/999) Fix fallback for browserify for optional modules. (@eiriksm) +- [#996](https://github.com/request/request/pull/996) Wrong oauth signature when multiple same param keys exist [updated] (@bengl, @hyjin) + +### v2.40.0 (2014/08/06) +- [#992](https://github.com/request/request/pull/992) Fix security vulnerability. Update qs (@poeticninja) +- [#988](https://github.com/request/request/pull/988) “--” -> “—” (@upisfree) +- [#987](https://github.com/request/request/pull/987) Show optional modules as being loaded by the module that reqeusted them (@iarna) + +### v2.39.0 (2014/07/24) +- [#976](https://github.com/request/request/pull/976) Update README.md (@pvoznenko) + +### v2.38.0 (2014/07/22) +- [#952](https://github.com/request/request/pull/952) Adding support to client certificate with proxy use case (@ofirshaked) +- [#884](https://github.com/request/request/pull/884) Documented tough-cookie installation. (@wbyoung) +- [#935](https://github.com/request/request/pull/935) Correct repository url (@fritx) +- [#963](https://github.com/request/request/pull/963) Update changelog (@nylen) +- [#960](https://github.com/request/request/pull/960) Support gzip with encoding on node pre-v0.9.4 (@kevinoid) +- [#953](https://github.com/request/request/pull/953) Add async Content-Length computation when using form-data (@LoicMahieu) +- [#844](https://github.com/request/request/pull/844) Add support for HTTP[S]_PROXY environment variables. Fixes #595. (@jvmccarthy) +- [#946](https://github.com/request/request/pull/946) defaults: merge headers (@aj0strow) + +### v2.37.0 (2014/07/07) +- [#957](https://github.com/request/request/pull/957) Silence EventEmitter memory leak warning #311 (@watson) +- [#955](https://github.com/request/request/pull/955) check for content-length header before setting it in nextTick (@camilleanne) +- [#951](https://github.com/request/request/pull/951) Add support for gzip content decoding (@kevinoid) +- [#949](https://github.com/request/request/pull/949) Manually enter querystring in form option (@charlespwd) +- [#944](https://github.com/request/request/pull/944) Make request work with browserify (@eiriksm) +- [#943](https://github.com/request/request/pull/943) New mime module (@eiriksm) +- [#927](https://github.com/request/request/pull/927) Bump version of hawk dep. (@samccone) +- [#907](https://github.com/request/request/pull/907) append secureOptions to poolKey (@medovob) + +### v2.35.0 (2014/05/17) +- [#901](https://github.com/request/request/pull/901) Fixes #555 (@pigulla) +- [#897](https://github.com/request/request/pull/897) merge with default options (@vohof) +- [#891](https://github.com/request/request/pull/891) fixes 857 - options object is mutated by calling request (@lalitkapoor) +- [#869](https://github.com/request/request/pull/869) Pipefilter test (@tgohn) +- [#866](https://github.com/request/request/pull/866) Fix typo (@dandv) +- [#861](https://github.com/request/request/pull/861) Add support for RFC 6750 Bearer Tokens (@phedny) +- [#809](https://github.com/request/request/pull/809) upgrade tunnel-proxy to 0.4.0 (@ksato9700) +- [#850](https://github.com/request/request/pull/850) Fix word consistency in readme (@0xNobody) +- [#810](https://github.com/request/request/pull/810) add some exposition to mpu example in README.md (@mikermcneil) +- [#840](https://github.com/request/request/pull/840) improve error reporting for invalid protocols (@FND) +- [#821](https://github.com/request/request/pull/821) added secureOptions back (@nw) +- [#815](https://github.com/request/request/pull/815) Create changelog based on pull requests (@lalitkapoor) + +### v2.34.0 (2014/02/18) +- [#516](https://github.com/request/request/pull/516) UNIX Socket URL Support (@lyuzashi) +- [#801](https://github.com/request/request/pull/801) 794 ignore cookie parsing and domain errors (@lalitkapoor) +- [#802](https://github.com/request/request/pull/802) Added the Apache license to the package.json. (@keskival) +- [#793](https://github.com/request/request/pull/793) Adds content-length calculation when submitting forms using form-data li... (@Juul) +- [#785](https://github.com/request/request/pull/785) Provide ability to override content-type when `json` option used (@vvo) +- [#781](https://github.com/request/request/pull/781) simpler isReadStream function (@joaojeronimo) + +### v2.32.0 (2014/01/16) +- [#767](https://github.com/request/request/pull/767) Use tough-cookie CookieJar sync API (@stash) +- [#764](https://github.com/request/request/pull/764) Case-insensitive authentication scheme (@bobyrizov) +- [#763](https://github.com/request/request/pull/763) Upgrade tough-cookie to 0.10.0 (@stash) +- [#744](https://github.com/request/request/pull/744) Use Cookie.parse (@lalitkapoor) +- [#757](https://github.com/request/request/pull/757) require aws-sign2 (@mafintosh) + +### v2.31.0 (2014/01/08) +- [#645](https://github.com/request/request/pull/645) update twitter api url to v1.1 (@mick) +- [#746](https://github.com/request/request/pull/746) README: Markdown code highlight (@weakish) +- [#745](https://github.com/request/request/pull/745) updating setCookie example to make it clear that the callback is required (@emkay) +- [#742](https://github.com/request/request/pull/742) Add note about JSON output body type (@iansltx) +- [#741](https://github.com/request/request/pull/741) README example is using old cookie jar api (@emkay) +- [#736](https://github.com/request/request/pull/736) Fix callback arguments documentation (@mmalecki) + +### v2.30.0 (2013/12/13) +- [#732](https://github.com/request/request/pull/732) JSHINT: Creating global 'for' variable. Should be 'for (var ...'. (@Fritz-Lium) +- [#730](https://github.com/request/request/pull/730) better HTTP DIGEST support (@dai-shi) +- [#728](https://github.com/request/request/pull/728) Fix TypeError when calling request.cookie (@scarletmeow) + +### v2.29.0 (2013/12/06) +- [#727](https://github.com/request/request/pull/727) fix requester bug (@jchris) + +### v2.28.0 (2013/12/04) +- [#724](https://github.com/request/request/pull/724) README.md: add custom HTTP Headers example. (@tcort) +- [#719](https://github.com/request/request/pull/719) Made a comment gender neutral. (@unsetbit) +- [#715](https://github.com/request/request/pull/715) Request.multipart no longer crashes when header 'Content-type' present (@pastaclub) +- [#710](https://github.com/request/request/pull/710) Fixing listing in callback part of docs. (@lukasz-zak) +- [#696](https://github.com/request/request/pull/696) Edited README.md for formatting and clarity of phrasing (@Zearin) +- [#694](https://github.com/request/request/pull/694) Typo in README (@VRMink) +- [#690](https://github.com/request/request/pull/690) Handle blank password in basic auth. (@diversario) +- [#682](https://github.com/request/request/pull/682) Optional dependencies (@Turbo87) +- [#683](https://github.com/request/request/pull/683) Travis CI support (@Turbo87) +- [#674](https://github.com/request/request/pull/674) change cookie module,to tough-cookie.please check it . (@sxyizhiren) +- [#666](https://github.com/request/request/pull/666) make `ciphers` and `secureProtocol` to work in https request (@richarddong) +- [#656](https://github.com/request/request/pull/656) Test case for #304. (@diversario) +- [#662](https://github.com/request/request/pull/662) option.tunnel to explicitly disable tunneling (@seanmonstar) +- [#659](https://github.com/request/request/pull/659) fix failure when running with NODE_DEBUG=request, and a test for that (@jrgm) +- [#630](https://github.com/request/request/pull/630) Send random cnonce for HTTP Digest requests (@wprl) + +### v2.27.0 (2013/08/15) +- [#619](https://github.com/request/request/pull/619) decouple things a bit (@joaojeronimo) + +### v2.26.0 (2013/08/07) +- [#613](https://github.com/request/request/pull/613) Fixes #583, moved initialization of self.uri.pathname (@lexander) +- [#605](https://github.com/request/request/pull/605) Only include ":" + pass in Basic Auth if it's defined (fixes #602) (@bendrucker) + +### v2.24.0 (2013/07/23) +- [#596](https://github.com/request/request/pull/596) Global agent is being used when pool is specified (@Cauldrath) +- [#594](https://github.com/request/request/pull/594) Emit complete event when there is no callback (@RomainLK) +- [#601](https://github.com/request/request/pull/601) Fixed a small typo (@michalstanko) + +### v2.23.0 (2013/07/23) +- [#589](https://github.com/request/request/pull/589) Prevent setting headers after they are sent (@geek) +- [#587](https://github.com/request/request/pull/587) Global cookie jar disabled by default (@threepointone) + +### v2.22.0 (2013/07/05) +- [#544](https://github.com/request/request/pull/544) Update http-signature version. (@davidlehn) +- [#581](https://github.com/request/request/pull/581) Fix spelling of "ignoring." (@bigeasy) +- [#568](https://github.com/request/request/pull/568) use agentOptions to create agent when specified in request (@SamPlacette) +- [#564](https://github.com/request/request/pull/564) Fix redirections (@criloz) +- [#541](https://github.com/request/request/pull/541) The exported request function doesn't have an auth method (@tschaub) +- [#542](https://github.com/request/request/pull/542) Expose Request class (@regality) + +### v2.21.0 (2013/04/30) +- [#536](https://github.com/request/request/pull/536) Allow explicitly empty user field for basic authentication. (@mikeando) +- [#532](https://github.com/request/request/pull/532) fix typo (@fredericosilva) +- [#497](https://github.com/request/request/pull/497) Added redirect event (@Cauldrath) +- [#503](https://github.com/request/request/pull/503) Fix basic auth for passwords that contain colons (@tonistiigi) +- [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway421) +- [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka) + +### v2.17.0 (2013/04/22) +- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway421) +- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway421) +- [#519](https://github.com/request/request/pull/519) Update internal path state on post-creation QS changes (@jblebrun) +- [#510](https://github.com/request/request/pull/510) Add HTTP Signature support. (@davidlehn) +- [#502](https://github.com/request/request/pull/502) Fix POST (and probably other) requests that are retried after 401 Unauthorized (@nylen) +- [#508](https://github.com/request/request/pull/508) Honor the .strictSSL option when using proxies (tunnel-agent) (@jhs) +- [#512](https://github.com/request/request/pull/512) Make password optional to support the format: http://username@hostname/ (@pajato1) +- [#513](https://github.com/request/request/pull/513) add 'localAddress' support (@yyfrankyy) +- [#498](https://github.com/request/request/pull/498) Moving response emit above setHeaders on destination streams (@kenperkins) +- [#490](https://github.com/request/request/pull/490) Empty response body (3-rd argument) must be passed to callback as an empty string (@Olegas) +- [#479](https://github.com/request/request/pull/479) Changing so if Accept header is explicitly set, sending json does not ov... (@RoryH) +- [#475](https://github.com/request/request/pull/475) Use `unescape` from `querystring` (@shimaore) +- [#473](https://github.com/request/request/pull/473) V0.10 compat (@isaacs) +- [#471](https://github.com/request/request/pull/471) Using querystring library from visionmedia (@kbackowski) +- [#461](https://github.com/request/request/pull/461) Strip the UTF8 BOM from a UTF encoded response (@kppullin) +- [#460](https://github.com/request/request/pull/460) hawk 0.10.0 (@hueniverse) +- [#462](https://github.com/request/request/pull/462) if query params are empty, then request path shouldn't end with a '?' (merges cleanly now) (@jaipandya) +- [#456](https://github.com/request/request/pull/456) hawk 0.9.0 (@hueniverse) +- [#429](https://github.com/request/request/pull/429) Copy options before adding callback. (@nrn, @nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki) +- [#454](https://github.com/request/request/pull/454) Destroy the response if present when destroying the request (clean merge) (@mafintosh) +- [#310](https://github.com/request/request/pull/310) Twitter Oauth Stuff Out of Date; Now Updated (@joemccann, @isaacs, @mscdex) +- [#413](https://github.com/request/request/pull/413) rename googledoodle.png to .jpg (@nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki) +- [#448](https://github.com/request/request/pull/448) Convenience method for PATCH (@mloar) +- [#444](https://github.com/request/request/pull/444) protect against double callbacks on error path (@spollack) +- [#433](https://github.com/request/request/pull/433) Added support for HTTPS cert & key (@mmalecki) +- [#430](https://github.com/request/request/pull/430) Respect specified {Host,host} headers, not just {host} (@andrewschaaf) +- [#415](https://github.com/request/request/pull/415) Fixed a typo. (@jerem) +- [#338](https://github.com/request/request/pull/338) Add more auth options, including digest support (@nylen) +- [#403](https://github.com/request/request/pull/403) Optimize environment lookup to happen once only (@mmalecki) +- [#398](https://github.com/request/request/pull/398) Add more reporting to tests (@mmalecki) +- [#388](https://github.com/request/request/pull/388) Ensure "safe" toJSON doesn't break EventEmitters (@othiym23) +- [#381](https://github.com/request/request/pull/381) Resolving "Invalid signature. Expected signature base string: " (@landeiro) +- [#380](https://github.com/request/request/pull/380) Fixes missing host header on retried request when using forever agent (@mac-) +- [#376](https://github.com/request/request/pull/376) Headers lost on redirect (@kapetan) +- [#375](https://github.com/request/request/pull/375) Fix for missing oauth_timestamp parameter (@jplock) +- [#374](https://github.com/request/request/pull/374) Correct Host header for proxy tunnel CONNECT (@youurayy) +- [#370](https://github.com/request/request/pull/370) Twitter reverse auth uses x_auth_mode not x_auth_type (@drudge) +- [#369](https://github.com/request/request/pull/369) Don't remove x_auth_mode for Twitter reverse auth (@drudge) +- [#344](https://github.com/request/request/pull/344) Make AWS auth signing find headers correctly (@nlf) +- [#363](https://github.com/request/request/pull/363) rfc3986 on base_uri, now passes tests (@jeffmarshall) +- [#362](https://github.com/request/request/pull/362) Running `rfc3986` on `base_uri` in `oauth.hmacsign` instead of just `encodeURIComponent` (@jeffmarshall) +- [#361](https://github.com/request/request/pull/361) Don't create a Content-Length header if we already have it set (@danjenkins) +- [#360](https://github.com/request/request/pull/360) Delete self._form along with everything else on redirect (@jgautier) +- [#355](https://github.com/request/request/pull/355) stop sending erroneous headers on redirected requests (@azylman) +- [#332](https://github.com/request/request/pull/332) Fix #296 - Only set Content-Type if body exists (@Marsup) +- [#343](https://github.com/request/request/pull/343) Allow AWS to work in more situations, added a note in the README on its usage (@nlf) +- [#320](https://github.com/request/request/pull/320) request.defaults() doesn't need to wrap jar() (@StuartHarris) +- [#322](https://github.com/request/request/pull/322) Fix + test for piped into request bumped into redirect. #321 (@alexindigo) +- [#326](https://github.com/request/request/pull/326) Do not try to remove listener from an undefined connection (@strk) +- [#318](https://github.com/request/request/pull/318) Pass servername to tunneling secure socket creation (@isaacs) +- [#317](https://github.com/request/request/pull/317) Workaround for #313 (@isaacs) +- [#293](https://github.com/request/request/pull/293) Allow parser errors to bubble up to request (@mscdex) +- [#290](https://github.com/request/request/pull/290) A test for #289 (@isaacs) +- [#280](https://github.com/request/request/pull/280) Like in node.js print options if NODE_DEBUG contains the word request (@Filirom1) +- [#207](https://github.com/request/request/pull/207) Fix #206 Change HTTP/HTTPS agent when redirecting between protocols (@isaacs) +- [#214](https://github.com/request/request/pull/214) documenting additional behavior of json option (@jphaas) +- [#272](https://github.com/request/request/pull/272) Boundary begins with CRLF? (@elspoono, @timshadel, @naholyr, @nanodocumet, @TehShrike) +- [#284](https://github.com/request/request/pull/284) Remove stray `console.log()` call in multipart generator. (@bcherry) +- [#241](https://github.com/request/request/pull/241) Composability updates suggested by issue #239 (@polotek) +- [#282](https://github.com/request/request/pull/282) OAuth Authorization header contains non-"oauth_" parameters (@jplock) +- [#279](https://github.com/request/request/pull/279) fix tests with boundary by injecting boundry from header (@benatkin) +- [#273](https://github.com/request/request/pull/273) Pipe back pressure issue (@mafintosh) +- [#268](https://github.com/request/request/pull/268) I'm not OCD seriously (@TehShrike) +- [#263](https://github.com/request/request/pull/263) Bug in OAuth key generation for sha1 (@nanodocumet) +- [#265](https://github.com/request/request/pull/265) uncaughtException when redirected to invalid URI (@naholyr) +- [#262](https://github.com/request/request/pull/262) JSON test should check for equality (@timshadel) +- [#261](https://github.com/request/request/pull/261) Setting 'pool' to 'false' does NOT disable Agent pooling (@timshadel) +- [#249](https://github.com/request/request/pull/249) Fix for the fix of your (closed) issue #89 where self.headers[content-length] is set to 0 for all methods (@sethbridges, @polotek, @zephrax, @jeromegn) +- [#255](https://github.com/request/request/pull/255) multipart allow body === '' ( the empty string ) (@Filirom1) +- [#260](https://github.com/request/request/pull/260) fixed just another leak of 'i' (@sreuter) +- [#246](https://github.com/request/request/pull/246) Fixing the set-cookie header (@jeromegn) +- [#243](https://github.com/request/request/pull/243) Dynamic boundary (@zephrax) +- [#240](https://github.com/request/request/pull/240) don't error when null is passed for options (@polotek) +- [#211](https://github.com/request/request/pull/211) Replace all occurrences of special chars in RFC3986 (@chriso) +- [#224](https://github.com/request/request/pull/224) Multipart content-type change (@janjongboom) +- [#217](https://github.com/request/request/pull/217) need to use Authorization (titlecase) header with Tumblr OAuth (@visnup) +- [#203](https://github.com/request/request/pull/203) Fix cookie and redirect bugs and add auth support for HTTPS tunnel (@milewise) +- [#199](https://github.com/request/request/pull/199) Tunnel (@isaacs) +- [#198](https://github.com/request/request/pull/198) Bugfix on forever usage of util.inherits (@isaacs) +- [#197](https://github.com/request/request/pull/197) Make ForeverAgent work with HTTPS (@isaacs) +- [#193](https://github.com/request/request/pull/193) Fixes GH-119 (@goatslacker) +- [#188](https://github.com/request/request/pull/188) Add abort support to the returned request (@itay) +- [#176](https://github.com/request/request/pull/176) Querystring option (@csainty) +- [#182](https://github.com/request/request/pull/182) Fix request.defaults to support (uri, options, callback) api (@twilson63) +- [#180](https://github.com/request/request/pull/180) Modified the post, put, head and del shortcuts to support uri optional param (@twilson63) +- [#179](https://github.com/request/request/pull/179) fix to add opts in .pipe(stream, opts) (@substack) +- [#177](https://github.com/request/request/pull/177) Issue #173 Support uri as first and optional config as second argument (@twilson63) +- [#170](https://github.com/request/request/pull/170) can't create a cookie in a wrapped request (defaults) (@fabianonunes) +- [#168](https://github.com/request/request/pull/168) Picking off an EasyFix by adding some missing mimetypes. (@serby) +- [#161](https://github.com/request/request/pull/161) Fix cookie jar/headers.cookie collision (#125) (@papandreou) +- [#162](https://github.com/request/request/pull/162) Fix issue #159 (@dpetukhov) +- [#90](https://github.com/request/request/pull/90) add option followAllRedirects to follow post/put redirects (@jroes) +- [#148](https://github.com/request/request/pull/148) Retry Agent (@thejh) +- [#146](https://github.com/request/request/pull/146) Multipart should respect content-type if previously set (@apeace) +- [#144](https://github.com/request/request/pull/144) added "form" option to readme (@petejkim) +- [#133](https://github.com/request/request/pull/133) Fixed cookies parsing (@afanasy) +- [#135](https://github.com/request/request/pull/135) host vs hostname (@iangreenleaf) +- [#132](https://github.com/request/request/pull/132) return the body as a Buffer when encoding is set to null (@jahewson) +- [#112](https://github.com/request/request/pull/112) Support using a custom http-like module (@jhs) +- [#104](https://github.com/request/request/pull/104) Cookie handling contains bugs (@janjongboom) +- [#121](https://github.com/request/request/pull/121) Another patch for cookie handling regression (@jhurliman) +- [#117](https://github.com/request/request/pull/117) Remove the global `i` (@3rd-Eden) +- [#110](https://github.com/request/request/pull/110) Update to Iris Couch URL (@jhs) +- [#86](https://github.com/request/request/pull/86) Can't post binary to multipart requests (@developmentseed) +- [#105](https://github.com/request/request/pull/105) added test for proxy option. (@dominictarr) +- [#102](https://github.com/request/request/pull/102) Implemented cookies - closes issue 82: https://github.com/mikeal/request/issues/82 (@alessioalex) +- [#97](https://github.com/request/request/pull/97) Typo in previous pull causes TypeError in non-0.5.11 versions (@isaacs) +- [#96](https://github.com/request/request/pull/96) Authless parsed url host support (@isaacs) +- [#81](https://github.com/request/request/pull/81) Enhance redirect handling (@danmactough) +- [#78](https://github.com/request/request/pull/78) Don't try to do strictSSL for non-ssl connections (@isaacs) +- [#76](https://github.com/request/request/pull/76) Bug when a request fails and a timeout is set (@Marsup) +- [#70](https://github.com/request/request/pull/70) add test script to package.json (@isaacs, @aheckmann) +- [#73](https://github.com/request/request/pull/73) Fix #71 Respect the strictSSL flag (@isaacs) +- [#69](https://github.com/request/request/pull/69) Flatten chunked requests properly (@isaacs) +- [#67](https://github.com/request/request/pull/67) fixed global variable leaks (@aheckmann) +- [#66](https://github.com/request/request/pull/66) Do not overwrite established content-type headers for read stream deliver (@voodootikigod) +- [#53](https://github.com/request/request/pull/53) Parse json: Issue #51 (@benatkin) +- [#45](https://github.com/request/request/pull/45) Added timeout option (@mbrevoort) +- [#35](https://github.com/request/request/pull/35) The "end" event isn't emitted for some responses (@voxpelli) +- [#31](https://github.com/request/request/pull/31) Error on piping a request to a destination (@tobowers) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CONTRIBUTING.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CONTRIBUTING.md new file mode 100644 index 0000000..06b1968 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/CONTRIBUTING.md @@ -0,0 +1,44 @@ +# This is an OPEN Open Source Project + +----------------------------------------- + +## What? + +Individuals making significant and valuable contributions are given +commit-access to the project to contribute as they see fit. This project is +more like an open wiki than a standard guarded open source project. + +## Rules + +There are a few basic ground-rules for contributors: + +1. **No `--force` pushes** or modifying the Git history in any way. +1. **Non-master branches** ought to be used for ongoing work. +1. **External API changes and significant modifications** ought to be subject + to an **internal pull-request** to solicit feedback from other contributors. +1. Internal pull-requests to solicit feedback are *encouraged* for any other + non-trivial contribution but left to the discretion of the contributor. +1. For significant changes wait a full 24 hours before merging so that active + contributors who are distributed throughout the world have a chance to weigh + in. +1. Contributors should attempt to adhere to the prevailing code-style. +1. Run `npm test` locally before submitting your PR, to catch any easy to miss + style & testing issues. To diagnose test failures, there are two ways to + run a single test file: + - `node_modules/.bin/taper tests/test-file.js` - run using the default + [`taper`](https://github.com/nylen/taper) test reporter. + - `node tests/test-file.js` - view the raw + [tap](https://testanything.org/) output. + + +## Releases + +Declaring formal releases remains the prerogative of the project maintainer. + +## Changes to this arrangement + +This is an experiment and feedback is welcome! This document may also be +subject to pull-requests or changes by contributors where you believe you have +something valuable to add or change. + +----------------------------------------- diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/README.md new file mode 100644 index 0000000..d8bd405 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/README.md @@ -0,0 +1,1058 @@ + +# Request - Simplified HTTP client + +[![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/) + +[![Build status](https://img.shields.io/travis/request/request.svg?style=flat-square)](https://travis-ci.org/request/request) +[![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat-square)](https://coveralls.io/r/request/request) +[![Dependency Status](https://img.shields.io/david/request/request.svg?style=flat-square)](https://david-dm.org/request/request) +[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge) + + +## Super simple to use + +Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. + +```js +var request = require('request'); +request('http://www.google.com', function (error, response, body) { + if (!error && response.statusCode == 200) { + console.log(body) // Show the HTML for the Google homepage. + } +}) +``` + + +## Table of contents + +- [Streaming](#streaming) +- [Forms](#forms) +- [HTTP Authentication](#http-authentication) +- [Custom HTTP Headers](#custom-http-headers) +- [OAuth Signing](#oauth-signing) +- [Proxies](#proxies) +- [Unix Domain Sockets](#unix-domain-sockets) +- [TLS/SSL Protocol](#tlsssl-protocol) +- [Support for HAR 1.2](#support-for-har-12) +- [**All Available Options**](#requestoptions-callback) + +Request also offers [convenience methods](#convenience-methods) like +`request.defaults` and `request.post`, and there are +lots of [usage examples](#examples) and several +[debugging techniques](#debugging). + + +--- + + +## Streaming + +You can stream any response to a file stream. + +```js +request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) +``` + +You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one). + +```js +fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) +``` + +Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers. + +```js +request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) +``` + +Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage). + +```js +request + .get('http://google.com/img.png') + .on('response', function(response) { + console.log(response.statusCode) // 200 + console.log(response.headers['content-type']) // 'image/png' + }) + .pipe(request.put('http://mysite.com/img.png')) +``` + +To easily handle errors when streaming requests, listen to the `error` event before piping: + +```js +request + .get('http://mysite.com/doodle.png') + .on('error', function(err) { + console.log(err) + }) + .pipe(fs.createWriteStream('doodle.png')) +``` + +Now let’s get fancy. + +```js +http.createServer(function (req, resp) { + if (req.url === '/doodle.png') { + if (req.method === 'PUT') { + req.pipe(request.put('http://mysite.com/doodle.png')) + } else if (req.method === 'GET' || req.method === 'HEAD') { + request.get('http://mysite.com/doodle.png').pipe(resp) + } + } +}) +``` + +You can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do: + +```js +http.createServer(function (req, resp) { + if (req.url === '/doodle.png') { + var x = request('http://mysite.com/doodle.png') + req.pipe(x) + x.pipe(resp) + } +}) +``` + +And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :) + +```js +req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) +``` + +Also, none of this new functionality conflicts with requests previous features, it just expands them. + +```js +var r = request.defaults({'proxy':'http://localproxy.com'}) + +http.createServer(function (req, resp) { + if (req.url === '/doodle.png') { + r.get('http://google.com/doodle.png').pipe(resp) + } +}) +``` + +You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. + +[back to top](#table-of-contents) + + +--- + + +## Forms + +`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API. + + +#### application/x-www-form-urlencoded (URL-Encoded Forms) + +URL-encoded forms are simple. + +```js +request.post('http://service.com/upload', {form:{key:'value'}}) +// or +request.post('http://service.com/upload').form({key:'value'}) +// or +request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }) +``` + + +#### multipart/form-data (Multipart Form Uploads) + +For `multipart/form-data` we use the [form-data](https://github.com/felixge/node-form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option. + + +```js +var formData = { + // Pass a simple key-value pair + my_field: 'my_value', + // Pass data via Buffers + my_buffer: new Buffer([1, 2, 3]), + // Pass data via Streams + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), + // Pass multiple values /w an Array + attachments: [ + fs.createReadStream(__dirname + '/attachment1.jpg'), + fs.createReadStream(__dirname + '/attachment2.jpg') + ], + // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS} + // Use case: for some types of streams, you'll need to provide "file"-related information manually. + // See the `form-data` README for more information about options: https://github.com/felixge/node-form-data + custom_file: { + value: fs.createReadStream('/dev/urandom'), + options: { + filename: 'topsecret.jpg', + contentType: 'image/jpg' + } + } +}; +request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.) + +```js +// NOTE: Advanced use-case, for normal use see 'formData' usage above +var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...}) +var form = r.form(); +form.append('my_field', 'my_value'); +form.append('my_buffer', new Buffer([1, 2, 3])); +form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'}); +``` +See the [form-data README](https://github.com/felixge/node-form-data) for more information & examples. + + +#### multipart/related + +Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options. + +```js + request({ + method: 'PUT', + preambleCRLF: true, + postambleCRLF: true, + uri: 'http://service.com/upload', + multipart: [ + { + 'content-type': 'application/json' + body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + }, + { body: 'I am an attachment' }, + { body: fs.createReadStream('image.png') } + ], + // alternatively pass an object containing additional options + multipart: { + chunked: false, + data: [ + { + 'content-type': 'application/json', + body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + }, + { body: 'I am an attachment' } + ] + } + }, + function (error, response, body) { + if (error) { + return console.error('upload failed:', error); + } + console.log('Upload successful! Server responded with:', body); + }) +``` + +[back to top](#table-of-contents) + + +--- + + +## HTTP Authentication + +```js +request.get('http://some.server.com/').auth('username', 'password', false); +// or +request.get('http://some.server.com/', { + 'auth': { + 'user': 'username', + 'pass': 'password', + 'sendImmediately': false + } +}); +// or +request.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); +// or +request.get('http://some.server.com/', { + 'auth': { + 'bearer': 'bearerToken' + } +}); +``` + +If passed as an option, `auth` should be a hash containing values: + +- `user` || `username` +- `pass` || `password` +- `sendImmediately` (optional) +- `bearer` (optional) + +The method form takes parameters +`auth(username, password, sendImmediately, bearer)`. + +`sendImmediately` defaults to `true`, which causes a basic or bearer +authentication header to be sent. If `sendImmediately` is `false`, then +`request` will retry with a proper authentication header after receiving a +`401` response from the server (which must contain a `WWW-Authenticate` header +indicating the required authentication method). + +Note that you can also specify basic authentication using the URL itself, as +detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the +`user:password` before the host with an `@` sign: + +```js +var username = 'username', + password = 'password', + url = 'http://' + username + ':' + password + '@some.server.com'; + +request({url: url}, function (error, response, body) { + // Do more stuff with 'body' here +}); +``` + +Digest authentication is supported, but it only works with `sendImmediately` +set to `false`; otherwise `request` will send basic authentication on the +initial request, which will probably cause the request to fail. + +Bearer authentication is supported, and is activated when the `bearer` value is +available. The value may be either a `String` or a `Function` returning a +`String`. Using a function to supply the bearer token is particularly useful if +used in conjuction with `defaults` to allow a single function to supply the +last known token at the time of sending a request, or to compute one on the fly. + +[back to top](#table-of-contents) + + +--- + + +## Custom HTTP Headers + +HTTP Headers, such as `User-Agent`, can be set in the `options` object. +In the example below, we call the github API to find out the number +of stars and forks for the request repository. This requires a +custom `User-Agent` header as well as https. + +```js +var request = require('request'); + +var options = { + url: 'https://api.github.com/repos/request/request', + headers: { + 'User-Agent': 'request' + } +}; + +function callback(error, response, body) { + if (!error && response.statusCode == 200) { + var info = JSON.parse(body); + console.log(info.stargazers_count + " Stars"); + console.log(info.forks_count + " Forks"); + } +} + +request(options, callback); +``` + +[back to top](#table-of-contents) + + +--- + + +## OAuth Signing + +[OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The +default signing algorithm is +[HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2): + +```js +// OAuth1.0 - 3-legged server side flow (Twitter example) +// step 1 +var qs = require('querystring') + , oauth = + { callback: 'http://mysite.com/callback/' + , consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + } + , url = 'https://api.twitter.com/oauth/request_token' + ; +request.post({url:url, oauth:oauth}, function (e, r, body) { + // Ideally, you would take the body in the response + // and construct a URL that a user clicks on (like a sign in button). + // The verifier is only available in the response after a user has + // verified with twitter that they are authorizing your app. + + // step 2 + var req_data = qs.parse(body) + var uri = 'https://api.twitter.com/oauth/authenticate' + + '?' + qs.stringify({oauth_token: req_data.oauth_token}) + // redirect the user to the authorize uri + + // step 3 + // after the user is redirected back to your server + var auth_data = qs.parse(body) + , oauth = + { consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + , token: auth_data.oauth_token + , token_secret: req_data.oauth_token_secret + , verifier: auth_data.oauth_verifier + } + , url = 'https://api.twitter.com/oauth/access_token' + ; + request.post({url:url, oauth:oauth}, function (e, r, body) { + // ready to make signed requests on behalf of the user + var perm_data = qs.parse(body) + , oauth = + { consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + , token: perm_data.oauth_token + , token_secret: perm_data.oauth_token_secret + } + , url = 'https://api.twitter.com/1.1/users/show.json' + , qs = + { screen_name: perm_data.screen_name + , user_id: perm_data.user_id + } + ; + request.get({url:url, oauth:oauth, json:true}, function (e, r, user) { + console.log(user) + }) + }) +}) +``` + +For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make +the following changes to the OAuth options object: +* Pass `signature_method : 'RSA-SHA1'` +* Instead of `consumer_secret`, specify a `private_key` string in + [PEM format](http://how2ssl.com/articles/working_with_pem_files/) + +For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make +the following changes to the OAuth options object: +* Pass `signature_method : 'PLAINTEXT'` + +To send OAuth parameters via query params or in a post body as described in The +[Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param) +section of the oauth1 spec: +* Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth + options object. +* `transport_method` defaults to `'header'` + +To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either +* Manually generate the body hash and pass it as a string `body_hash: '...'` +* Automatically generate the body hash by passing `body_hash: true` + +[back to top](#table-of-contents) + + +--- + + +## Proxies + +If you specify a `proxy` option, then the request (and any subsequent +redirects) will be sent via a connection to the proxy server. + +If your endpoint is an `https` url, and you are using a proxy, then +request will send a `CONNECT` request to the proxy server *first*, and +then use the supplied connection to connect to the endpoint. + +That is, first it will make a request like: + +``` +HTTP/1.1 CONNECT endpoint-server.com:80 +Host: proxy-server.com +User-Agent: whatever user agent you specify +``` + +and then the proxy server make a TCP connection to `endpoint-server` +on port `80`, and return a response that looks like: + +``` +HTTP/1.1 200 OK +``` + +At this point, the connection is left open, and the client is +communicating directly with the `endpoint-server.com` machine. + +See [the wikipedia page on HTTP Tunneling](http://en.wikipedia.org/wiki/HTTP_tunnel) +for more information. + +By default, when proxying `http` traffic, request will simply make a +standard proxied `http` request. This is done by making the `url` +section of the initial line of the request a fully qualified url to +the endpoint. + +For example, it will make a single request that looks like: + +``` +HTTP/1.1 GET http://endpoint-server.com/some-url +Host: proxy-server.com +Other-Headers: all go here + +request body or whatever +``` + +Because a pure "http over http" tunnel offers no additional security +or other features, it is generally simpler to go with a +straightforward HTTP proxy in this case. However, if you would like +to force a tunneling proxy, you may set the `tunnel` option to `true`. + +You can also make a standard proxied `http` request by explicitly setting +`tunnel : false`, but **note that this will allow the proxy to see the traffic +to/from the destination server**. + +If you are using a tunneling proxy, you may set the +`proxyHeaderWhiteList` to share certain headers with the proxy. + +You can also set the `proxyHeaderExclusiveList` to share certain +headers only with the proxy and not with destination host. + +By default, this set is: + +``` +accept +accept-charset +accept-encoding +accept-language +accept-ranges +cache-control +content-encoding +content-language +content-length +content-location +content-md5 +content-range +content-type +connection +date +expect +max-forwards +pragma +proxy-authorization +referer +te +transfer-encoding +user-agent +via +``` + +Note that, when using a tunneling proxy, the `proxy-authorization` +header and any headers from custom `proxyHeaderExclusiveList` are +*never* sent to the endpoint server, but only to the proxy server. + + +### Controlling proxy behaviour using environment variables + +The following environment variables are respected by `request`: + + * `HTTP_PROXY` / `http_proxy` + * `HTTPS_PROXY` / `https_proxy` + * `NO_PROXY` / `no_proxy` + +When `HTTP_PROXY` / `http_proxy` are set, they will be used to proxy non-SSL requests that do not have an explicit `proxy` configuration option present. Similarly, `HTTPS_PROXY` / `https_proxy` will be respected for SSL requests that do not have an explicit `proxy` configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the `proxy` configuration option. Furthermore, the `proxy` configuration option can be explicitly set to false / null to opt out of proxying altogether for that request. + +`request` is also aware of the `NO_PROXY`/`no_proxy` environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to `*` to opt out of the implicit proxy configuration of the other environment variables. + +Here's some examples of valid `no_proxy` values: + + * `google.com` - don't proxy HTTP/HTTPS requests to Google. + * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google. + * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo! + * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether. + +[back to top](#table-of-contents) + + +--- + + +## UNIX Domain Sockets + +`request` supports making requests to [UNIX Domain Sockets](http://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme: + +```js +/* Pattern */ 'http://unix:SOCKET:PATH' +/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path') +``` + +Note: The `SOCKET` path is assumed to be absolute to the root of the host file system. + +[back to top](#table-of-contents) + + +--- + + +## TLS/SSL Protocol + +TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be +set directly in `options` object, in the `agentOptions` property of the `options` object, or even in `https.globalAgent.options`. Keep in mind that, although `agentOptions` allows for a slightly wider range of configurations, the recommendend way is via `options` object directly, as using `agentOptions` or `https.globalAgent.options` would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent). + +```js +var fs = require('fs') + , path = require('path') + , certFile = path.resolve(__dirname, 'ssl/client.crt') + , keyFile = path.resolve(__dirname, 'ssl/client.key') + , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem') + , request = require('request'); + +var options = { + url: 'https://api.some-server.com/', + cert: fs.readFileSync(certFile), + key: fs.readFileSync(keyFile), + passphrase: 'password', + ca: fs.readFileSync(caFile) + } +}; + +request.get(options); +``` + +### Using `options.agentOptions` + +In the example below, we call an API requires client side SSL certificate +(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol: + +```js +var fs = require('fs') + , path = require('path') + , certFile = path.resolve(__dirname, 'ssl/client.crt') + , keyFile = path.resolve(__dirname, 'ssl/client.key') + , request = require('request'); + +var options = { + url: 'https://api.some-server.com/', + agentOptions: { + cert: fs.readFileSync(certFile), + key: fs.readFileSync(keyFile), + // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format: + // pfx: fs.readFileSync(pfxFilePath), + passphrase: 'password', + securityOptions: 'SSL_OP_NO_SSLv3' + } +}; + +request.get(options); +``` + +It is able to force using SSLv3 only by specifying `secureProtocol`: + +```js +request.get({ + url: 'https://api.some-server.com/', + agentOptions: { + secureProtocol: 'SSLv3_method' + } +}); +``` + +It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs). +This can be useful, for example, when using self-signed certificates. +To allow a different certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the `agentOptions`: + +```js +request.get({ + url: 'https://api.some-server.com/', + agentOptions: { + ca: fs.readFileSync('ca.cert.pem') + } +}); +``` + +[back to top](#table-of-contents) + + +--- + +## Support for HAR 1.2 + +The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`. + +a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching. + +```js + var request = require('request') + request({ + // will be ignored + method: 'GET' + uri: 'http://www.google.com', + + // HTTP Archive Request Object + har: { + url: 'http://www.mockbin.com/har' + method: 'POST', + headers: [ + { + name: 'content-type', + value: 'application/x-www-form-urlencoded' + } + ], + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { + name: 'foo', + value: 'bar' + }, + { + name: 'hello', + value: 'world' + } + ] + } + } + }) + + // a POST request will be sent to http://www.mockbin.com + // with body an application/x-www-form-urlencoded body: + // foo=bar&hello=world +``` + +[back to top](#table-of-contents) + + +--- + +## request(options, callback) + +The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional. + +- `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()` +- `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string. +- `method` - http method (default: `"GET"`) +- `headers` - http headers (default: `{}`) + +--- + +- `qs` - object containing querystring values to be appended to the `uri` +- `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}` +- `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat` +- `useQuerystring` - If true, use `querystring` to stringify and parse + querystrings, otherwise use `qs` (default: `false`). Set this option to + `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the + default `foo[0]=bar&foo[1]=baz`. + +--- + +- `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer` or `String`, unless `json` is `true`. If `json` is `true`, then `body` must be a JSON-serializable object. +- `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above. +- `formData` - Data to pass for a `multipart/form-data` request. See + [Forms](#forms) section above. +- `multipart` - array of objects which contain their own headers and `body` + attributes. Sends a `multipart/related` request. See [Forms](#forms) section + above. + - Alternatively you can pass in an object `{chunked: false, data: []}` where + `chunked` is used to specify whether the request is sent in + [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) + In non-chunked requests, data items with body streams are not allowed. +- `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request. +- `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request. +- `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON. +- `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body. + +--- + +- `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above. +- `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above. +- `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example). +- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`. Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services) +- `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options. + +--- + +- `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise. +- `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`) +- `maxRedirects` - the maximum number of redirects to follow (default: `10`) +- `removeRefererHeader` - removes the referer header when a redirect happens (default: `false`). + +--- + +- `encoding` - Encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). +- `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below. +- `jar` - If `true` and `tough-cookie` is installed, remember cookies for future use (or define your custom cookie jar; see examples section) + +--- + +- `pool` - An object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as [your options allow for it](request.js#L747)). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. + - A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`). + - Note that if you are sending multiple requests in a loop and creating + multiple new `pool` objects, `maxSockets` will not work as intended. To + work around this, either use [`request.defaults`](#requestdefaultsoptions) + with your pool options or create the pool object with the `maxSockets` + property outside of the loop. +- `timeout` - Integer containing the number of milliseconds to wait for a + request to respond before aborting the request. Note that if the underlying + TCP connection cannot be established, the OS-wide TCP connection timeout will + overrule the `timeout` option ([the default in Linux is around 20 seconds](http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout)). +- `localAddress` - Local interface to bind for network connections. +- `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`) +- `strictSSL` - If `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option. +- `agentOptions` - Object containing user agent options. See documentation above. **Note:** [see tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +- `tunnel` - controls the behavior of + [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling) + as follows: + - `undefined` (default) - `true` if the destination is `https` or a previous + request in the redirect chain used a tunneling proxy, `false` otherwise + - `true` - always tunnel to the destination by making a `CONNECT` request to + the proxy + - `false` - request the destination as a `GET` request. +- `proxyHeaderWhiteList` - A whitelist of headers to send to a + tunneling proxy. +- `proxyHeaderExclusiveList` - A whitelist of headers to send + exclusively to a tunneling proxy and not to destination. + +--- + +- `time` - If `true`, the request-response cycle (including all redirects) is timed at millisecond resolution, and the result provided on the response's `elapsedTime` property. + +--- + +- `har` - A [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)* + +The callback argument gets 3 arguments: + +1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object) +2. An [`http.IncomingMessage`](http://nodejs.org/api/http.html#http_http_incomingmessage) object +3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied) + +[back to top](#table-of-contents) + + +--- + +## Convenience methods + +There are also shorthand methods for different HTTP METHODs and some other conveniences. + + +### request.defaults(options) + +This method **returns a wrapper** around the normal request API that defaults +to whatever options you pass to it. + +**Note:** `request.defaults()` **does not** modify the global request API; +instead, it **returns a wrapper** that has your default settings applied to it. + +**Note:** You can call `.defaults()` on the wrapper that is returned from +`request.defaults` to add/override defaults that were previously defaulted. + +For example: +```js +//requests using baseRequest() will set the 'x-token' header +var baseRequest = request.defaults({ + headers: {x-token: 'my-token'} +}) + +//requests using specialRequest() will include the 'x-token' header set in +//baseRequest and will also include the 'special' header +var specialRequest = baseRequest.defaults({ + headers: {special: 'special value'} +}) +``` + +### request.put + +Same as `request()`, but defaults to `method: "PUT"`. + +```js +request.put(url) +``` + +### request.patch + +Same as `request()`, but defaults to `method: "PATCH"`. + +```js +request.patch(url) +``` + +### request.post + +Same as `request()`, but defaults to `method: "POST"`. + +```js +request.post(url) +``` + +### request.head + +Same as `request()`, but defaults to `method: "HEAD"`. + +```js +request.head(url) +``` + +### request.del + +Same as `request()`, but defaults to `method: "DELETE"`. + +```js +request.del(url) +``` + +### request.get + +Same as `request()` (for uniformity). + +```js +request.get(url) +``` +### request.cookie + +Function that creates a new cookie. + +```js +request.cookie('key1=value1') +``` +### request.jar() + +Function that creates a new cookie jar. + +```js +request.jar() +``` + +[back to top](#table-of-contents) + + +--- + + +## Debugging + +There are at least three ways to debug the operation of `request`: + +1. Launch the node process like `NODE_DEBUG=request node script.js` + (`lib,request,otherlib` works too). + +2. Set `require('request').debug = true` at any time (this does the same thing + as #1). + +3. Use the [request-debug module](https://github.com/nylen/request-debug) to + view request and response headers and bodies. + +[back to top](#table-of-contents) + + +--- + + +## Examples: + +```js + var request = require('request') + , rand = Math.floor(Math.random()*100000000).toString() + ; + request( + { method: 'PUT' + , uri: 'http://mikeal.iriscouch.com/testjs/' + rand + , multipart: + [ { 'content-type': 'application/json' + , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + } + , { body: 'I am an attachment' } + ] + } + , function (error, response, body) { + if(response.statusCode == 201){ + console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) + } else { + console.log('error: '+ response.statusCode) + console.log(body) + } + } + ) +``` + +For backwards-compatibility, response compression is not supported by default. +To accept gzip-compressed responses, set the `gzip` option to `true`. Note +that the body data passed through `request` is automatically decompressed +while the response object is unmodified and will contain compressed data if +the server sent a compressed response. + +```js + var request = require('request') + request( + { method: 'GET' + , uri: 'http://www.google.com' + , gzip: true + } + , function (error, response, body) { + // body is the decompressed response body + console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')) + console.log('the decoded data is: ' + body) + } + ).on('data', function(data) { + // decompressed data as it is received + console.log('decoded chunk: ' + data) + }) + .on('response', function(response) { + // unmodified http.IncomingMessage object + response.on('data', function(data) { + // compressed data as it is received + console.log('received ' + data.length + ' bytes of compressed data') + }) + }) +``` + +Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`) and install `tough-cookie`. + +```js +var request = request.defaults({jar: true}) +request('http://www.google.com', function () { + request('http://images.google.com') +}) +``` + +To use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`) + +```js +var j = request.jar() +var request = request.defaults({jar:j}) +request('http://www.google.com', function () { + request('http://images.google.com') +}) +``` + +OR + +```js +var j = request.jar(); +var cookie = request.cookie('key1=value1'); +var url = 'http://www.google.com'; +j.setCookie(cookie, url); +request({url: url, jar: j}, function () { + request('http://images.google.com') +}) +``` + +To use a custom cookie store (such as a +[`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore) +which supports saving to and restoring from JSON files), pass it as a parameter +to `request.jar()`: + +```js +var FileCookieStore = require('tough-cookie-filestore'); +// NOTE - currently the 'cookies.json' file must already exist! +var j = request.jar(new FileCookieStore('cookies.json')); +request = request.defaults({ jar : j }) +request('http://www.google.com', function() { + request('http://images.google.com') +}) +``` + +The cookie store must be a +[`tough-cookie`](https://github.com/goinstant/tough-cookie) +store and it must support synchronous operations; see the +[`CookieStore` API docs](https://github.com/goinstant/tough-cookie/#cookiestore-api) +for details. + +To inspect your cookie jar after a request: + +```js +var j = request.jar() +request({url: 'http://www.google.com', jar: j}, function () { + var cookie_string = j.getCookieString(uri); // "key1=value1; key2=value2; ..." + var cookies = j.getCookies(uri); + // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] +}) +``` + +[back to top](#table-of-contents) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/disabled.appveyor.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/disabled.appveyor.yml new file mode 100644 index 0000000..238f3d6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/disabled.appveyor.yml @@ -0,0 +1,36 @@ +# http://www.appveyor.com/docs/appveyor-yml + +# Fix line endings in Windows. (runs before repo cloning) +init: + - git config --global core.autocrlf input + +# Test against these versions of Node.js. +environment: + matrix: + - nodejs_version: "0.10" + - nodejs_version: "0.8" + - nodejs_version: "0.11" + +# Allow failing jobs for bleeding-edge Node.js versions. +matrix: + allow_failures: + - nodejs_version: "0.11" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node 0.STABLE.latest + - ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) + # Typical npm stuff. + - npm install + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - ps: "npm test # PowerShell" # Pass comment to PS for easier debugging + - cmd: npm test + +# Don't actually build. +build: off + +# Set build version format here instead of in the admin panel. +version: "{build}" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/examples/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/examples/README.md new file mode 100644 index 0000000..526d71b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/examples/README.md @@ -0,0 +1,115 @@ + +# Authentication + +## OAuth + +### OAuth1.0 Refresh Token + +- http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html#anchor4 +- https://developer.yahoo.com/oauth/guide/oauth-refreshaccesstoken.html + +```js +request.post('https://api.login.yahoo.com/oauth/v2/get_token', { + oauth: { + consumer_key: '...', + consumer_secret: '...', + token: '...', + token_secret: '...', + session_handle: '...' + } +}, function (err, res, body) { + var result = require('querystring').parse(body) + // assert.equal(typeof result, 'object') +}) +``` + +### OAuth2 Refresh Token + +- https://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-6 + +```js +request.post('https://accounts.google.com/o/oauth2/token', { + form: { + grant_type: 'refresh_token', + client_id: '...', + client_secret: '...', + refresh_token: '...' + }, + json: true +}, function (err, res, body) { + // assert.equal(typeof body, 'object') +}) +``` + +# Multipart + +## multipart/form-data + +### Flickr Image Upload + +- https://www.flickr.com/services/api/upload.api.html + +```js +request.post('https://up.flickr.com/services/upload', { + oauth: { + consumer_key: '...', + consumer_secret: '...', + token: '...', + token_secret: '...' + }, + // all meta data should be included here for proper signing + qs: { + title: 'My cat is awesome', + description: 'Sent on ' + new Date(), + is_public: 1 + }, + // again the same meta data + the actual photo + formData: { + title: 'My cat is awesome', + description: 'Sent on ' + new Date(), + is_public: 1, + photo:fs.createReadStream('cat.png') + }, + json: true +}, function (err, res, body) { + // assert.equal(typeof body, 'object') +}) +``` + +# Streams + +## `POST` data + +Use Request as a Writable stream to easily `POST` Readable streams (like files, other HTTP requests, or otherwise). + +TL;DR: Pipe a Readable Stream onto Request via: + +``` +READABLE.pipe(request.post(URL)); +``` + +A more detailed example: + +```js +var fs = require('fs') + , path = require('path') + , http = require('http') + , request = require('request') + , TMP_FILE_PATH = path.join(path.sep, 'tmp', 'foo') +; + +// write a temporary file: +fs.writeFileSync(TMP_FILE_PATH, 'foo bar baz quk\n'); + +http.createServer(function(req, res) { + console.log('the server is receiving data!\n'); + req + .on('end', res.end.bind(res)) + .pipe(process.stdout) + ; +}).listen(3000).unref(); + +fs.createReadStream(TMP_FILE_PATH) + .pipe(request.post('http://127.0.0.1:3000')) +; +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/index.js new file mode 100755 index 0000000..5872824 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/index.js @@ -0,0 +1,159 @@ +// Copyright 2010-2012 Mikeal Rogers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict' + +var extend = require('util')._extend + , cookies = require('./lib/cookies') + , helpers = require('./lib/helpers') + +var isFunction = helpers.isFunction + , paramsHaveRequestBody = helpers.paramsHaveRequestBody + + +// organize params for patch, post, put, head, del +function initParams(uri, options, callback) { + if (typeof options === 'function') { + callback = options + } + + var params = {} + if (typeof options === 'object') { + params = extend({}, options) + params = extend(params, {uri: uri}) + } else if (typeof uri === 'string') { + params = extend({}, {uri: uri}) + } else { + params = extend({}, uri) + } + + params.callback = callback + return params +} + +function request (uri, options, callback) { + if (typeof uri === 'undefined') { + throw new Error('undefined is not a valid uri or options object.') + } + + var params = initParams(uri, options, callback) + + if (params.method === 'HEAD' && paramsHaveRequestBody(params)) { + throw new Error('HTTP HEAD requests MUST NOT include a request body.') + } + + return new request.Request(params) +} + +function verbFunc (verb) { + var method = verb === 'del' ? 'DELETE' : verb.toUpperCase() + return function (uri, options, callback) { + var params = initParams(uri, options, callback) + params.method = method + return request(params, params.callback) + } +} + +// define like this to please codeintel/intellisense IDEs +request.get = verbFunc('get') +request.head = verbFunc('head') +request.post = verbFunc('post') +request.put = verbFunc('put') +request.patch = verbFunc('patch') +request.del = verbFunc('del') + +request.jar = function (store) { + return cookies.jar(store) +} + +request.cookie = function (str) { + return cookies.parse(str) +} + +function wrapRequestMethod (method, options, requester, verb) { + + return function (uri, opts, callback) { + var params = initParams(uri, opts, callback) + + var headerlessOptions = extend({}, options) + delete headerlessOptions.headers + params = extend(headerlessOptions, params) + + if (options.headers) { + var headers = extend({}, options.headers) + params.headers = extend(headers, params.headers) + } + + if (verb) { + params.method = (verb === 'del' ? 'DELETE' : verb.toUpperCase()) + } + + if (isFunction(requester)) { + method = requester + } + + return method(params, params.callback) + } +} + +request.defaults = function (options, requester) { + var self = this + + if (typeof options === 'function') { + requester = options + options = {} + } + + var defaults = wrapRequestMethod(self, options, requester) + + var verbs = ['get', 'head', 'post', 'put', 'patch', 'del'] + verbs.forEach(function(verb) { + defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb) + }) + + defaults.cookie = wrapRequestMethod(self.cookie, options, requester) + defaults.jar = self.jar + defaults.defaults = self.defaults + return defaults +} + +request.forever = function (agentOptions, optionsArg) { + var options = {} + if (optionsArg) { + options = extend({}, optionsArg) + } + if (agentOptions) { + options.agentOptions = agentOptions + } + + options.forever = true + return request.defaults(options) +} + +// Exports + +module.exports = request +request.Request = require('./request') +request.initParams = initParams + +// Backwards compatibility for request.debug +Object.defineProperty(request, 'debug', { + enumerable : true, + get : function() { + return request.Request.debug + }, + set : function(debug) { + request.Request.debug = debug + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/auth.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/auth.js new file mode 100644 index 0000000..1be1f42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/auth.js @@ -0,0 +1,153 @@ +'use strict' + +var caseless = require('caseless') + , uuid = require('node-uuid') + , helpers = require('./helpers') + +var md5 = helpers.md5 + , toBase64 = helpers.toBase64 + + +function Auth (request) { + // define all public properties here + this.request = request + this.hasAuth = false + this.sentAuth = false + this.bearerToken = null + this.user = null + this.pass = null +} + +Auth.prototype.basic = function (user, pass, sendImmediately) { + var self = this + if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) { + self.request.emit('error', new Error('auth() received invalid user or password')) + } + self.user = user + self.pass = pass + self.hasAuth = true + var header = user + ':' + (pass || '') + if (sendImmediately || typeof sendImmediately === 'undefined') { + var authHeader = 'Basic ' + toBase64(header) + self.sentAuth = true + return authHeader + } +} + +Auth.prototype.bearer = function (bearer, sendImmediately) { + var self = this + self.bearerToken = bearer + self.hasAuth = true + if (sendImmediately || typeof sendImmediately === 'undefined') { + if (typeof bearer === 'function') { + bearer = bearer() + } + var authHeader = 'Bearer ' + (bearer || '') + self.sentAuth = true + return authHeader + } +} + +Auth.prototype.digest = function (method, path, authHeader) { + // TODO: More complete implementation of RFC 2617. + // - check challenge.algorithm + // - support algorithm="MD5-sess" + // - handle challenge.domain + // - support qop="auth-int" only + // - handle Authentication-Info (not necessarily?) + // - check challenge.stale (not necessarily?) + // - increase nc (not necessarily?) + // For reference: + // http://tools.ietf.org/html/rfc2617#section-3 + // https://github.com/bagder/curl/blob/master/lib/http_digest.c + + var self = this + + var challenge = {} + var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi + for (;;) { + var match = re.exec(authHeader) + if (!match) { + break + } + challenge[match[1]] = match[2] || match[3] + } + + var ha1 = md5(self.user + ':' + challenge.realm + ':' + self.pass) + var ha2 = md5(method + ':' + path) + var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' + var nc = qop && '00000001' + var cnonce = qop && uuid().replace(/-/g, '') + var digestResponse = qop + ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) + : md5(ha1 + ':' + challenge.nonce + ':' + ha2) + var authValues = { + username: self.user, + realm: challenge.realm, + nonce: challenge.nonce, + uri: path, + qop: qop, + response: digestResponse, + nc: nc, + cnonce: cnonce, + algorithm: challenge.algorithm, + opaque: challenge.opaque + } + + authHeader = [] + for (var k in authValues) { + if (authValues[k]) { + if (k === 'qop' || k === 'nc' || k === 'algorithm') { + authHeader.push(k + '=' + authValues[k]) + } else { + authHeader.push(k + '="' + authValues[k] + '"') + } + } + } + authHeader = 'Digest ' + authHeader.join(', ') + self.sentAuth = true + return authHeader +} + +Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) { + var self = this + , request = self.request + + var authHeader + if (bearer === undefined && user === undefined) { + self.request.emit('error', new Error('no auth mechanism defined')) + } else if (bearer !== undefined) { + authHeader = self.bearer(bearer, sendImmediately) + } else { + authHeader = self.basic(user, pass, sendImmediately) + } + if (authHeader) { + request.setHeader('authorization', authHeader) + } +} + +Auth.prototype.onResponse = function (response) { + var self = this + , request = self.request + + if (!self.hasAuth || self.sentAuth) { return null } + + var c = caseless(response.headers) + + var authHeader = c.get('www-authenticate') + var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() + request.debug('reauth', authVerb) + + switch (authVerb) { + case 'basic': + return self.basic(self.user, self.pass, true) + + case 'bearer': + return self.bearer(self.bearerToken, true) + + case 'digest': + return self.digest(request.method, request.path, authHeader) + } +} + +exports.Auth = Auth diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/cookies.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/cookies.js new file mode 100644 index 0000000..adde7c6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/cookies.js @@ -0,0 +1,39 @@ +'use strict' + +var tough = require('tough-cookie') + +var Cookie = tough.Cookie + , CookieJar = tough.CookieJar + + +exports.parse = function(str) { + if (str && str.uri) { + str = str.uri + } + if (typeof str !== 'string') { + throw new Error('The cookie function only accepts STRING as param') + } + return Cookie.parse(str) +} + +// Adapt the sometimes-Async api of tough.CookieJar to our requirements +function RequestJar(store) { + var self = this + self._jar = new CookieJar(store) +} +RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) { + var self = this + return self._jar.setCookieSync(cookieOrStr, uri, options || {}) +} +RequestJar.prototype.getCookieString = function(uri) { + var self = this + return self._jar.getCookieStringSync(uri) +} +RequestJar.prototype.getCookies = function(uri) { + var self = this + return self._jar.getCookiesSync(uri) +} + +exports.jar = function(store) { + return new RequestJar(store) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/copy.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/copy.js new file mode 100644 index 0000000..ad162a5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/copy.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = +function copy (obj) { + var o = {} + Object.keys(obj).forEach(function (i) { + o[i] = obj[i] + }) + return o +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/getProxyFromURI.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/getProxyFromURI.js new file mode 100644 index 0000000..c2013a6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/getProxyFromURI.js @@ -0,0 +1,79 @@ +'use strict' + +function formatHostname(hostname) { + // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' + return hostname.replace(/^\.*/, '.').toLowerCase() +} + +function parseNoProxyZone(zone) { + zone = zone.trim().toLowerCase() + + var zoneParts = zone.split(':', 2) + , zoneHost = formatHostname(zoneParts[0]) + , zonePort = zoneParts[1] + , hasPort = zone.indexOf(':') > -1 + + return {hostname: zoneHost, port: zonePort, hasPort: hasPort} +} + +function uriInNoProxy(uri, noProxy) { + var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') + , hostname = formatHostname(uri.hostname) + , noProxyList = noProxy.split(',') + + // iterate through the noProxyList until it finds a match. + return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) { + var isMatchedAt = hostname.indexOf(noProxyZone.hostname) + , hostnameMatched = ( + isMatchedAt > -1 && + (isMatchedAt === hostname.length - noProxyZone.hostname.length) + ) + + if (noProxyZone.hasPort) { + return (port === noProxyZone.port) && hostnameMatched + } + + return hostnameMatched + }) +} + +function getProxyFromURI(uri) { + // Decide the proper request proxy to use based on the request URI object and the + // environmental variables (NO_PROXY, HTTP_PROXY, etc.) + // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html) + + var noProxy = process.env.NO_PROXY || process.env.no_proxy || '' + + // if the noProxy is a wildcard then return null + + if (noProxy === '*') { + return null + } + + // if the noProxy is not empty and the uri is found return null + + if (noProxy !== '' && uriInNoProxy(uri, noProxy)) { + return null + } + + // Check for HTTP or HTTPS Proxy in environment Else default to null + + if (uri.protocol === 'http:') { + return process.env.HTTP_PROXY || + process.env.http_proxy || null + } + + if (uri.protocol === 'https:') { + return process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy || null + } + + // if none of that works, return null + // (What uri protocol are you using then?) + + return null +} + +module.exports = getProxyFromURI diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/har.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/har.js new file mode 100644 index 0000000..83453a3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/har.js @@ -0,0 +1,205 @@ +'use strict' + +var fs = require('fs') +var qs = require('querystring') +var validate = require('har-validator') +var util = require('util') + +function Har (request) { + this.request = request +} + +Har.prototype.reducer = function (obj, pair) { + // new property ? + if (obj[pair.name] === undefined) { + obj[pair.name] = pair.value + return obj + } + + // existing? convert to array + var arr = [ + obj[pair.name], + pair.value + ] + + obj[pair.name] = arr + + return obj +} + +Har.prototype.prep = function (data) { + // construct utility properties + data.queryObj = {} + data.headersObj = {} + data.postData.jsonObj = false + data.postData.paramsObj = false + + // construct query objects + if (data.queryString && data.queryString.length) { + data.queryObj = data.queryString.reduce(this.reducer, {}) + } + + // construct headers objects + if (data.headers && data.headers.length) { + // loweCase header keys + data.headersObj = data.headers.reduceRight(function (headers, header) { + headers[header.name] = header.value + return headers + }, {}) + } + + // construct Cookie header + if (data.cookies && data.cookies.length) { + var cookies = data.cookies.map(function (cookie) { + return cookie.name + '=' + cookie.value + }) + + if (cookies.length) { + data.headersObj.cookie = cookies.join('; ') + } + } + + // prep body + switch (data.postData.mimeType) { + case 'multipart/mixed': + case 'multipart/related': + case 'multipart/form-data': + case 'multipart/alternative': + // reset values + data.postData.mimeType = 'multipart/form-data' + break + + case 'application/x-www-form-urlencoded': + if (!data.postData.params) { + data.postData.text = '' + } else { + data.postData.paramsObj = data.postData.params.reduce(this.reducer, {}) + + // always overwrite + data.postData.text = qs.stringify(data.postData.paramsObj) + } + break + + case 'text/json': + case 'text/x-json': + case 'application/json': + case 'application/x-json': + data.postData.mimeType = 'application/json' + + if (data.postData.text) { + try { + data.postData.jsonObj = JSON.parse(data.postData.text) + } catch (e) { + this.request.debug(e) + + // force back to text/plain + data.postData.mimeType = 'text/plain' + } + } + break + } + + return data +} + +Har.prototype.options = function (options) { + // skip if no har property defined + if (!options.har) { + return options + } + + var har = util._extend({}, options.har) + + // only process the first entry + if (har.log && har.log.entries) { + har = har.log.entries[0] + } + + // add optional properties to make validation successful + har.url = har.url || options.url || options.uri || options.baseUrl || '/' + har.httpVersion = har.httpVersion || 'HTTP/1.1' + har.queryString = har.queryString || [] + har.headers = har.headers || [] + har.cookies = har.cookies || [] + har.postData = har.postData || {} + har.postData.mimeType = har.postData.mimeType || 'application/octet-stream' + + har.bodySize = 0 + har.headersSize = 0 + har.postData.size = 0 + + if (!validate.request(har)) { + return options + } + + // clean up and get some utility properties + var req = this.prep(har) + + // construct new options + if (req.url) { + options.url = req.url + } + + if (req.method) { + options.method = req.method + } + + if (Object.keys(req.queryObj).length) { + options.qs = req.queryObj + } + + if (Object.keys(req.headersObj).length) { + options.headers = req.headersObj + } + + switch (req.postData.mimeType) { + case 'application/x-www-form-urlencoded': + options.form = req.postData.paramsObj + break + + case 'application/json': + if (req.postData.jsonObj) { + options.body = req.postData.jsonObj + options.json = true + } + break + + case 'multipart/form-data': + options.formData = {} + + req.postData.params.forEach(function (param) { + var attachment = {} + + if (!param.fileName && !param.fileName && !param.contentType) { + options.formData[param.name] = param.value + return + } + + // attempt to read from disk! + if (param.fileName && !param.value) { + attachment.value = fs.createReadStream(param.fileName) + } else if (param.value) { + attachment.value = param.value + } + + if (param.fileName) { + attachment.options = { + filename: param.fileName, + contentType: param.contentType ? param.contentType : null + } + } + + options.formData[param.name] = attachment + }) + break + + default: + if (req.postData.text) { + options.body = req.postData.text + } + } + + return options +} + +exports.Har = Har diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/helpers.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/helpers.js new file mode 100644 index 0000000..1d588ca --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/helpers.js @@ -0,0 +1,55 @@ +'use strict' + +var jsonSafeStringify = require('json-stringify-safe') + , crypto = require('crypto') + +function deferMethod() { + if (typeof setImmediate === 'undefined') { + return process.nextTick + } + + return setImmediate +} + +function isFunction(value) { + return typeof value === 'function' +} + +function paramsHaveRequestBody(params) { + return ( + params.body || + params.requestBodyStream || + (params.json && typeof params.json !== 'boolean') || + params.multipart + ) +} + +function safeStringify (obj) { + var ret + try { + ret = JSON.stringify(obj) + } catch (e) { + ret = jsonSafeStringify(obj) + } + return ret +} + +function md5 (str) { + return crypto.createHash('md5').update(str).digest('hex') +} + +function isReadStream (rs) { + return rs.readable && rs.path && rs.mode +} + +function toBase64 (str) { + return (new Buffer(str || '', 'utf8')).toString('base64') +} + +exports.isFunction = isFunction +exports.paramsHaveRequestBody = paramsHaveRequestBody +exports.safeStringify = safeStringify +exports.md5 = md5 +exports.isReadStream = isReadStream +exports.toBase64 = toBase64 +exports.defer = deferMethod() diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/multipart.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/multipart.js new file mode 100644 index 0000000..0361858 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/multipart.js @@ -0,0 +1,109 @@ +'use strict' + +var uuid = require('node-uuid') + , CombinedStream = require('combined-stream') + , isstream = require('isstream') + + +function Multipart (request) { + this.request = request + this.boundary = uuid() + this.chunked = false + this.body = null +} + +Multipart.prototype.isChunked = function (options) { + var self = this + , chunked = false + , parts = options.data || options + + if (!parts.forEach) { + self.request.emit('error', new Error('Argument error, options.multipart.')) + } + + if (options.chunked !== undefined) { + chunked = options.chunked + } + + if (self.request.getHeader('transfer-encoding') === 'chunked') { + chunked = true + } + + if (!chunked) { + parts.forEach(function (part) { + if (typeof part.body === 'undefined') { + self.request.emit('error', new Error('Body attribute missing in multipart.')) + } + if (isstream(part.body)) { + chunked = true + } + }) + } + + return chunked +} + +Multipart.prototype.setHeaders = function (chunked) { + var self = this + + if (chunked && !self.request.hasHeader('transfer-encoding')) { + self.request.setHeader('transfer-encoding', 'chunked') + } + + var header = self.request.getHeader('content-type') + + if (!header || header.indexOf('multipart') === -1) { + self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary) + } else { + if (header.indexOf('boundary') !== -1) { + self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1') + } else { + self.request.setHeader('content-type', header + '; boundary=' + self.boundary) + } + } +} + +Multipart.prototype.build = function (parts, chunked) { + var self = this + var body = chunked ? new CombinedStream() : [] + + function add (part) { + return chunked ? body.append(part) : body.push(new Buffer(part)) + } + + if (self.request.preambleCRLF) { + add('\r\n') + } + + parts.forEach(function (part) { + var preamble = '--' + self.boundary + '\r\n' + Object.keys(part).forEach(function (key) { + if (key === 'body') { return } + preamble += key + ': ' + part[key] + '\r\n' + }) + preamble += '\r\n' + add(preamble) + add(part.body) + add('\r\n') + }) + add('--' + self.boundary + '--') + + if (self.request.postambleCRLF) { + add('\r\n') + } + + return body +} + +Multipart.prototype.onRequest = function (options) { + var self = this + + var chunked = self.isChunked(options) + , parts = options.data || options + + self.setHeaders(chunked) + self.chunked = chunked + self.body = self.build(parts, chunked) +} + +exports.Multipart = Multipart diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/oauth.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/oauth.js new file mode 100644 index 0000000..8405972 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/oauth.js @@ -0,0 +1,144 @@ +'use strict' + +var qs = require('qs') + , caseless = require('caseless') + , uuid = require('node-uuid') + , oauth = require('oauth-sign') + , crypto = require('crypto') + + +function OAuth (request) { + this.request = request + this.params = null +} + +OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) { + var oa = {} + for (var i in _oauth) { + oa['oauth_' + i] = _oauth[i] + } + if (!oa.oauth_version) { + oa.oauth_version = '1.0' + } + if (!oa.oauth_timestamp) { + oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString() + } + if (!oa.oauth_nonce) { + oa.oauth_nonce = uuid().replace(/-/g, '') + } + if (!oa.oauth_signature_method) { + oa.oauth_signature_method = 'HMAC-SHA1' + } + + var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key + delete oa.oauth_consumer_secret + delete oa.oauth_private_key + + var token_secret = oa.oauth_token_secret + delete oa.oauth_token_secret + + var realm = oa.oauth_realm + delete oa.oauth_realm + delete oa.oauth_transport_method + + var baseurl = uri.protocol + '//' + uri.host + uri.pathname + var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&')) + + oa.oauth_signature = oauth.sign( + oa.oauth_signature_method, + method, + baseurl, + params, + consumer_secret_or_private_key, + token_secret) + + if (realm) { + oa.realm = realm + } + + return oa +} + +OAuth.prototype.buildBodyHash = function(_oauth, body) { + if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) { + this.request.emit('error', new Error('oauth: ' + _oauth.signature_method + + ' signature_method not supported with body_hash signing.')) + } + + var shasum = crypto.createHash('sha1') + shasum.update(body || '') + var sha1 = shasum.digest('hex') + + return new Buffer(sha1).toString('base64') +} + +OAuth.prototype.concatParams = function (oa, sep, wrap) { + wrap = wrap || '' + + var params = Object.keys(oa).filter(function (i) { + return i !== 'realm' && i !== 'oauth_signature' + }).sort() + + if (oa.realm) { + params.splice(0, 1, 'realm') + } + params.push('oauth_signature') + + return params.map(function (i) { + return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap + }).join(sep) +} + +OAuth.prototype.onRequest = function (_oauth) { + var self = this + self.params = _oauth + + var uri = self.request.uri || {} + , method = self.request.method || '' + , headers = caseless(self.request.headers) + , body = self.request.body || '' + , qsLib = self.request.qsLib || qs + + var form + , query + , contentType = headers.get('content-type') || '' + , formContentType = 'application/x-www-form-urlencoded' + , transport = _oauth.transport_method || 'header' + + if (contentType.slice(0, formContentType.length) === formContentType) { + contentType = formContentType + form = body + } + if (uri.query) { + query = uri.query + } + if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) { + self.request.emit('error', new Error('oauth: transport_method of body requires POST ' + + 'and content-type ' + formContentType)) + } + + if (!form && typeof _oauth.body_hash === 'boolean') { + _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString()) + } + + var oa = self.buildParams(_oauth, uri, method, query, form, qsLib) + + switch (transport) { + case 'header': + self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"')) + break + + case 'query': + self.request.path = (query ? '&' : '?') + self.concatParams(oa, '&') + break + + case 'body': + self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&') + break + + default: + self.request.emit('error', new Error('oauth: transport_method invalid')) + } +} + +exports.OAuth = OAuth diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/querystring.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/querystring.js new file mode 100644 index 0000000..baf5e80 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/querystring.js @@ -0,0 +1,51 @@ +'use strict' + +var qs = require('qs') + , querystring = require('querystring') + + +function Querystring (request) { + this.request = request + this.lib = null + this.useQuerystring = null + this.parseOptions = null + this.stringifyOptions = null +} + +Querystring.prototype.init = function (options) { + if (this.lib) {return} + + this.useQuerystring = options.useQuerystring + this.lib = (this.useQuerystring ? querystring : qs) + + this.parseOptions = options.qsParseOptions || {} + this.stringifyOptions = options.qsStringifyOptions || {} +} + +Querystring.prototype.stringify = function (obj) { + return (this.useQuerystring) + ? this.rfc3986(this.lib.stringify(obj, + this.stringifyOptions.sep || null, + this.stringifyOptions.eq || null, + this.stringifyOptions)) + : this.lib.stringify(obj, this.stringifyOptions) +} + +Querystring.prototype.parse = function (str) { + return (this.useQuerystring) + ? this.lib.parse(str, + this.parseOptions.sep || null, + this.parseOptions.eq || null, + this.parseOptions) + : this.lib.parse(str, this.parseOptions) +} + +Querystring.prototype.rfc3986 = function (str) { + return str.replace(/[!'()*]/g, function (c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} + +Querystring.prototype.unescape = querystring.unescape + +exports.Querystring = Querystring diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/redirect.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/redirect.js new file mode 100644 index 0000000..1d46502 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/lib/redirect.js @@ -0,0 +1,153 @@ +'use strict' + +var url = require('url') +var isUrl = /^https?:/ + +function Redirect (request) { + this.request = request + this.followRedirect = true + this.followRedirects = true + this.followAllRedirects = false + this.allowRedirect = function () {return true} + this.maxRedirects = 10 + this.redirects = [] + this.redirectsFollowed = 0 + this.removeRefererHeader = false +} + +Redirect.prototype.onRequest = function (options) { + var self = this + + if (options.maxRedirects !== undefined) { + self.maxRedirects = options.maxRedirects + } + if (typeof options.followRedirect === 'function') { + self.allowRedirect = options.followRedirect + } + if (options.followRedirect !== undefined) { + self.followRedirects = !!options.followRedirect + } + if (options.followAllRedirects !== undefined) { + self.followAllRedirects = options.followAllRedirects + } + if (self.followRedirects || self.followAllRedirects) { + self.redirects = self.redirects || [] + } + if (options.removeRefererHeader !== undefined) { + self.removeRefererHeader = options.removeRefererHeader + } +} + +Redirect.prototype.redirectTo = function (response) { + var self = this + , request = self.request + + var redirectTo = null + if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) { + var location = response.caseless.get('location') + request.debug('redirect', location) + + if (self.followAllRedirects) { + redirectTo = location + } else if (self.followRedirects) { + switch (request.method) { + case 'PATCH': + case 'PUT': + case 'POST': + case 'DELETE': + // Do not follow redirects + break + default: + redirectTo = location + break + } + } + } else if (response.statusCode === 401) { + var authHeader = request._auth.onResponse(response) + if (authHeader) { + request.setHeader('authorization', authHeader) + redirectTo = request.uri + } + } + return redirectTo +} + +Redirect.prototype.onResponse = function (response) { + var self = this + , request = self.request + + var redirectTo = self.redirectTo(response) + if (!redirectTo || !self.allowRedirect.call(request, response)) { + return false + } + + request.debug('redirect to', redirectTo) + + // ignore any potential response body. it cannot possibly be useful + // to us at this point. + // response.resume should be defined, but check anyway before calling. Workaround for browserify. + if (response.resume) { + response.resume() + } + + if (self.redirectsFollowed >= self.maxRedirects) { + request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href)) + return false + } + self.redirectsFollowed += 1 + + if (!isUrl.test(redirectTo)) { + redirectTo = url.resolve(request.uri.href, redirectTo) + } + + var uriPrev = request.uri + request.uri = url.parse(redirectTo) + + // handle the case where we change protocol from https to http or vice versa + if (request.uri.protocol !== uriPrev.protocol) { + request._updateProtocol() + } + + self.redirects.push( + { statusCode : response.statusCode + , redirectUri: redirectTo + } + ) + if (self.followAllRedirects && response.statusCode !== 401 && response.statusCode !== 307) { + request.method = 'GET' + } + // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215 + delete request.src + delete request.req + delete request.agent + delete request._started + if (response.statusCode !== 401 && response.statusCode !== 307) { + // Remove parameters from the previous response, unless this is the second request + // for a server that requires digest authentication. + delete request.body + delete request._form + if (request.headers) { + request.removeHeader('host') + request.removeHeader('content-type') + request.removeHeader('content-length') + if (request.uri.hostname !== request.originalHost.split(':')[0]) { + // Remove authorization if changing hostnames (but not if just + // changing ports or protocols). This matches the behavior of curl: + // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710 + request.removeHeader('authorization') + } + } + } + + if (!self.removeRefererHeader) { + request.setHeader('referer', request.uri.href) + } + + request.emit('redirect') + + request.init() + + return true +} + +exports.Redirect = Redirect diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/har-validator b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/har-validator new file mode 120000 index 0000000..c6ec163 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/har-validator @@ -0,0 +1 @@ +../har-validator/bin/har-validator \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/uuid b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/uuid new file mode 120000 index 0000000..80eb14a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/.bin/uuid @@ -0,0 +1 @@ +../node-uuid/bin/uuid \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/README.md new file mode 100644 index 0000000..763564e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/README.md @@ -0,0 +1,4 @@ +aws-sign +======== + +AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/index.js new file mode 100644 index 0000000..576e49d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/index.js @@ -0,0 +1,202 @@ + +/*! + * knox - auth + * Copyright(c) 2010 LearnBoost + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var crypto = require('crypto') + , parse = require('url').parse + ; + +/** + * Valid keys. + */ + +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] + +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ + +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) +} + +module.exports = authorization +module.exports.authorization = authorization + +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ + +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} + +module.exports.hmacSha1 = hmacSha1 + +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ + +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) +} +module.exports.sign = sign + +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ + +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery + +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.queryStringToSign = stringToSign + +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign + +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ + +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) + } + return buf.sort().join('\n') +} +module.exports.canonicalizeHeaders = canonicalizeHeaders + +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ + +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; + + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) + + return path + (buf.length ? '?' + buf.sort().join('&') : '') +} +module.exports.canonicalizeResource = canonicalizeResource diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/package.json new file mode 100644 index 0000000..89adc7d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/aws-sign2/package.json @@ -0,0 +1,30 @@ +{ + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "name": "aws-sign2", + "description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.", + "version": "0.5.0", + "repository": { + "url": "git+https://github.com/mikeal/aws-sign.git" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "readme": "aws-sign\n========\n\nAWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mikeal/aws-sign/issues" + }, + "homepage": "https://github.com/mikeal/aws-sign#readme", + "_id": "aws-sign2@0.5.0", + "_shasum": "c57103f7a17fc037f02d7c2e64b602ea223f7d63", + "_resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.5.0.tgz", + "_from": "aws-sign2@>=0.5.0 <0.6.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.jshintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.jshintrc new file mode 100644 index 0000000..c8ef3ca --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.jshintrc @@ -0,0 +1,59 @@ +{ + "predef": [ ] + , "bitwise": false + , "camelcase": false + , "curly": false + , "eqeqeq": false + , "forin": false + , "immed": false + , "latedef": false + , "noarg": true + , "noempty": true + , "nonew": true + , "plusplus": false + , "quotmark": true + , "regexp": false + , "undef": true + , "unused": true + , "strict": false + , "trailing": true + , "maxlen": 120 + , "asi": true + , "boss": true + , "debug": true + , "eqnull": true + , "esnext": true + , "evil": true + , "expr": true + , "funcscope": false + , "globalstrict": false + , "iterator": false + , "lastsemic": true + , "laxbreak": true + , "laxcomma": true + , "loopfunc": true + , "multistr": false + , "onecase": false + , "proto": false + , "regexdash": false + , "scripturl": true + , "smarttabs": false + , "shadow": false + , "sub": true + , "supernew": false + , "validthis": true + , "browser": true + , "couch": false + , "devel": false + , "dojo": false + , "mootools": false + , "node": true + , "nonstandard": true + , "prototypejs": false + , "rhino": false + , "worker": true + , "wsh": false + , "nomen": false + , "onevar": false + , "passfail": false +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.npmignore new file mode 100644 index 0000000..40b878d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.npmignore @@ -0,0 +1 @@ +node_modules/ \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.travis.yml new file mode 100644 index 0000000..7ddb9c9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - 0.8 + - "0.10" +branches: + only: + - master +notifications: + email: + - rod@vagg.org +script: npm test \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/LICENSE.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/LICENSE.md new file mode 100644 index 0000000..ccb2479 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2014 bl contributors +---------------------------------- + +*bl contributors listed at * + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/README.md new file mode 100644 index 0000000..6b7fb6d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/README.md @@ -0,0 +1,198 @@ +# bl *(BufferList)* + +**A Node.js Buffer list collector, reader and streamer thingy.** + +[![NPM](https://nodei.co/npm/bl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/bl/) +[![NPM](https://nodei.co/npm-dl/bl.png?months=6&height=3)](https://nodei.co/npm/bl/) + +**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! + +The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. + +```js +const BufferList = require('bl') + +var bl = new BufferList() +bl.append(new Buffer('abcd')) +bl.append(new Buffer('efg')) +bl.append('hi') // bl will also accept & convert Strings +bl.append(new Buffer('j')) +bl.append(new Buffer([ 0x3, 0x4 ])) + +console.log(bl.length) // 12 + +console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' +console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' +console.log(bl.slice(3, 6).toString('ascii')) // 'def' +console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' +console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' + +// or just use toString! +console.log(bl.toString()) // 'abcdefghij\u0003\u0004' +console.log(bl.toString('ascii', 3, 8)) // 'defgh' +console.log(bl.toString('ascii', 5, 10)) // 'fghij' + +// other standard Buffer readables +console.log(bl.readUInt16BE(10)) // 0x0304 +console.log(bl.readUInt16LE(10)) // 0x0403 +``` + +Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: + +```js +const bl = require('bl') + , fs = require('fs') + +fs.createReadStream('README.md') + .pipe(bl(function (err, data) { // note 'new' isn't strictly required + // `data` is a complete Buffer object containing the full data + console.log(data.toString()) + })) +``` + +Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. + +Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): +```js +const hyperquest = require('hyperquest') + , bl = require('bl') + , url = 'https://raw.github.com/rvagg/bl/master/README.md' + +hyperquest(url).pipe(bl(function (err, data) { + console.log(data.toString()) +})) +``` + +Or, use it as a readable stream to recompose a list of Buffers to an output source: + +```js +const BufferList = require('bl') + , fs = require('fs') + +var bl = new BufferList() +bl.append(new Buffer('abcd')) +bl.append(new Buffer('efg')) +bl.append(new Buffer('hi')) +bl.append(new Buffer('j')) + +bl.pipe(fs.createWriteStream('gibberish.txt')) +``` + +## API + + *
new BufferList([ callback ]) + * bl.length + * bl.append(buffer) + * bl.get(index) + * bl.slice([ start[, end ] ]) + * bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) + * bl.duplicate() + * bl.consume(bytes) + * bl.toString([encoding, [ start, [ end ]]]) + * bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() + * Streams + +-------------------------------------------------------- + +### new BufferList([ callback | buffer | buffer array ]) +The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. + +Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. + +`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: + +```js +var bl = require('bl') +var myinstance = bl() + +// equivilant to: + +var BufferList = require('bl') +var myinstance = new BufferList() +``` + +-------------------------------------------------------- + +### bl.length +Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. + +-------------------------------------------------------- + +### bl.append(buffer) +`append(buffer)` adds an additional buffer or BufferList to the internal list. + +-------------------------------------------------------- + +### bl.get(index) +`get()` will return the byte at the specified index. + +-------------------------------------------------------- + +### bl.slice([ start, [ end ] ]) +`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. + +If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. + +-------------------------------------------------------- + +### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) +`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. + +-------------------------------------------------------- + +### bl.duplicate() +`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: + +```js +var bl = new BufferList() + +bl.append('hello') +bl.append(' world') +bl.append('\n') + +bl.duplicate().pipe(process.stdout, { end: false }) + +console.log(bl.toString()) +``` + +-------------------------------------------------------- + +### bl.consume(bytes) +`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data. + +-------------------------------------------------------- + +### bl.toString([encoding, [ start, [ end ]]]) +`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. + +-------------------------------------------------------- + +### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() + +All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. + +See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. + +-------------------------------------------------------- + +### Streams +**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance. + +-------------------------------------------------------- + +## Contributors + +**bl** is brought to you by the following hackers: + + * [Rod Vagg](https://github.com/rvagg) + * [Matteo Collina](https://github.com/mcollina) + * [Jarett Cruger](https://github.com/jcrugzz) + +======= + + +## License & copyright + +Copyright (c) 2013-2014 bl contributors (listed above). + +bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/bl.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/bl.js new file mode 100644 index 0000000..7a2f997 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/bl.js @@ -0,0 +1,216 @@ +var DuplexStream = require('readable-stream/duplex') + , util = require('util') + +function BufferList (callback) { + if (!(this instanceof BufferList)) + return new BufferList(callback) + + this._bufs = [] + this.length = 0 + + if (typeof callback == 'function') { + this._callback = callback + + var piper = function (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) + + this.on('pipe', function (src) { + src.on('error', piper) + }) + this.on('unpipe', function (src) { + src.removeListener('error', piper) + }) + } + else if (Buffer.isBuffer(callback)) + this.append(callback) + else if (Array.isArray(callback)) { + callback.forEach(function (b) { + Buffer.isBuffer(b) && this.append(b) + }.bind(this)) + } + + DuplexStream.call(this) +} + +util.inherits(BufferList, DuplexStream) + +BufferList.prototype._offset = function (offset) { + var tot = 0, i = 0, _t + for (; i < this._bufs.length; i++) { + _t = tot + this._bufs[i].length + if (offset < _t) + return [ i, offset - tot ] + tot = _t + } +} + +BufferList.prototype.append = function (buf) { + var isBuffer = Buffer.isBuffer(buf) || + buf instanceof BufferList + + this._bufs.push(isBuffer ? buf : new Buffer(buf)) + this.length += buf.length + return this +} + +BufferList.prototype._write = function (buf, encoding, callback) { + this.append(buf) + if (callback) + callback() +} + +BufferList.prototype._read = function (size) { + if (!this.length) + return this.push(null) + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} + +BufferList.prototype.end = function (chunk) { + DuplexStream.prototype.end.call(this, chunk) + + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null + } +} + +BufferList.prototype.get = function (index) { + return this.slice(index, index + 1)[0] +} + +BufferList.prototype.slice = function (start, end) { + return this.copy(null, 0, start, end) +} + +BufferList.prototype.copy = function (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart != 'number' || srcStart < 0) + srcStart = 0 + if (typeof srcEnd != 'number' || srcEnd > this.length) + srcEnd = this.length + if (srcStart >= this.length) + return dst || new Buffer(0) + if (srcEnd <= 0) + return dst || new Buffer(0) + + var copy = !!dst + , off = this._offset(srcStart) + , len = srcEnd - srcStart + , bytes = len + , bufoff = (copy && dstStart) || 0 + , start = off[1] + , l + , i + + // copy/slice everything + if (srcStart === 0 && srcEnd == this.length) { + if (!copy) // slice, just return a full concat + return Buffer.concat(this._bufs) + + // copy, need to copy individual buffers + for (i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } + + return dst + } + + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } + + if (!copy) // a slice, we need something to copy in to + dst = new Buffer(len) + + for (i = off[0]; i < this._bufs.length; i++) { + l = this._bufs[i].length - start + + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + break + } + + bufoff += l + bytes -= l + + if (start) + start = 0 + } + + return dst +} + +BufferList.prototype.toString = function (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} + +BufferList.prototype.consume = function (bytes) { + while (this._bufs.length) { + if (bytes > this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break + } + } + return this +} + +BufferList.prototype.duplicate = function () { + var i = 0 + , copy = new BufferList() + + for (; i < this._bufs.length; i++) + copy.append(this._bufs[i]) + + return copy +} + +BufferList.prototype.destroy = function () { + this._bufs.length = 0; + this.length = 0; + this.push(null); +} + +;(function () { + var methods = { + 'readDoubleBE' : 8 + , 'readDoubleLE' : 8 + , 'readFloatBE' : 4 + , 'readFloatLE' : 4 + , 'readInt32BE' : 4 + , 'readInt32LE' : 4 + , 'readUInt32BE' : 4 + , 'readUInt32LE' : 4 + , 'readInt16BE' : 2 + , 'readInt16LE' : 2 + , 'readUInt16BE' : 2 + , 'readUInt16LE' : 2 + , 'readInt8' : 1 + , 'readUInt8' : 1 + } + + for (var m in methods) { + (function (m) { + BufferList.prototype[m] = function (offset) { + return this.slice(offset, offset + methods[m])[m](0) + } + }(m)) + } +}()) + +module.exports = BufferList diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/README.md new file mode 100644 index 0000000..3fb3e80 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/duplex.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; + + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; + + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} + +function emitReadable_(stream) { + stream.emit('readable'); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } + + function onend() { + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); + + state.flowing = true; + process.nextTick(function() { + flow(src); + }); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; +} + +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } + + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } + + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; + + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } + + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; +} + +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; + +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; + +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; + + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } + + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + process.nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + cb(er); + }); + else + cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..9074e8e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..b673333 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,37 @@ +{ + "name": "core-util-is", + "version": "1.0.1", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.1", + "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz", + "_from": "core-util-is@>=1.0.0 <1.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/util.js new file mode 100644 index 0000000..007fa10 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/util.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && objectToString(e) === '[object Error]'; +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..933382a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.1 <2.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/build/build.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/component.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..fb1eb37 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,38 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies 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 THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@0.0.1", + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "_from": "isarray@0.0.1" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..ee70702 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "readme": "**string_decoder.js** (`require('string_decoder')`) from Node.js core\n\nCopyright Joyent, Inc. and other Node contributors. See LICENCE file for details.\n\nVersion numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**\n\nThe *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_from": "string_decoder@>=0.10.0 <0.11.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/package.json new file mode 100644 index 0000000..d4c12ca --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/package.json @@ -0,0 +1,46 @@ +{ + "name": "readable-stream", + "version": "1.0.33", + "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "devDependencies": { + "tap": "~0.2.6" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "readme": "# readable-stream\n\n***Node-core streams for userland***\n\n[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)\n[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)\n\nThis package is a mirror of the Streams2 and Streams3 implementations in Node-core.\n\nIf you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *\"stream\"* module in Node-core.\n\n**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12.\n\n**readable-stream** uses proper patch-level versioning so if you pin to `\"~1.0.0\"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `\"~1.1.0\"`\n\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream#readme", + "_id": "readable-stream@1.0.33", + "_shasum": "3a360dd66c1b1d7fd4705389860eda1d0f61126c", + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz", + "_from": "readable-stream@>=1.0.26 <1.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/passthrough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..8b5337b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/readable.js @@ -0,0 +1,8 @@ +var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/transform.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/writable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/package.json new file mode 100644 index 0000000..d693008 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/package.json @@ -0,0 +1,45 @@ +{ + "name": "bl", + "version": "0.9.4", + "description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!", + "main": "bl.js", + "scripts": { + "test": "node test/test.js | faucet", + "test-local": "brtapsauce-local test/basic-test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/rvagg/bl.git" + }, + "homepage": "https://github.com/rvagg/bl", + "authors": [ + "Rod Vagg (https://github.com/rvagg)", + "Matteo Collina (https://github.com/mcollina)", + "Jarett Cruger (https://github.com/jcrugzz)" + ], + "keywords": [ + "buffer", + "buffers", + "stream", + "awesomesauce" + ], + "license": "MIT", + "dependencies": { + "readable-stream": "~1.0.26" + }, + "devDependencies": { + "tape": "~2.12.3", + "hash_file": "~0.1.1", + "faucet": "~0.0.1", + "brtapsauce": "~0.3.0" + }, + "readme": "# bl *(BufferList)*\n\n**A Node.js Buffer list collector, reader and streamer thingy.**\n\n[![NPM](https://nodei.co/npm/bl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/bl/)\n[![NPM](https://nodei.co/npm-dl/bl.png?months=6&height=3)](https://nodei.co/npm/bl/)\n\n**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them!\n\nThe original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently.\n\n```js\nconst BufferList = require('bl')\n\nvar bl = new BufferList()\nbl.append(new Buffer('abcd'))\nbl.append(new Buffer('efg'))\nbl.append('hi') // bl will also accept & convert Strings\nbl.append(new Buffer('j'))\nbl.append(new Buffer([ 0x3, 0x4 ]))\n\nconsole.log(bl.length) // 12\n\nconsole.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij'\nconsole.log(bl.slice(3, 10).toString('ascii')) // 'defghij'\nconsole.log(bl.slice(3, 6).toString('ascii')) // 'def'\nconsole.log(bl.slice(3, 8).toString('ascii')) // 'defgh'\nconsole.log(bl.slice(5, 10).toString('ascii')) // 'fghij'\n\n// or just use toString!\nconsole.log(bl.toString()) // 'abcdefghij\\u0003\\u0004'\nconsole.log(bl.toString('ascii', 3, 8)) // 'defgh'\nconsole.log(bl.toString('ascii', 5, 10)) // 'fghij'\n\n// other standard Buffer readables\nconsole.log(bl.readUInt16BE(10)) // 0x0304\nconsole.log(bl.readUInt16LE(10)) // 0x0403\n```\n\nGive it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**:\n\n```js\nconst bl = require('bl')\n , fs = require('fs')\n\nfs.createReadStream('README.md')\n .pipe(bl(function (err, data) { // note 'new' isn't strictly required\n // `data` is a complete Buffer object containing the full data\n console.log(data.toString())\n }))\n```\n\nNote that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream.\n\nOr to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!):\n```js\nconst hyperquest = require('hyperquest')\n , bl = require('bl')\n , url = 'https://raw.github.com/rvagg/bl/master/README.md'\n\nhyperquest(url).pipe(bl(function (err, data) {\n console.log(data.toString())\n}))\n```\n\nOr, use it as a readable stream to recompose a list of Buffers to an output source:\n\n```js\nconst BufferList = require('bl')\n , fs = require('fs')\n\nvar bl = new BufferList()\nbl.append(new Buffer('abcd'))\nbl.append(new Buffer('efg'))\nbl.append(new Buffer('hi'))\nbl.append(new Buffer('j'))\n\nbl.pipe(fs.createWriteStream('gibberish.txt'))\n```\n\n## API\n\n * new BufferList([ callback ])\n * bl.length\n * bl.append(buffer)\n * bl.get(index)\n * bl.slice([ start[, end ] ])\n * bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])\n * bl.duplicate()\n * bl.consume(bytes)\n * bl.toString([encoding, [ start, [ end ]]])\n * bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8()\n * Streams\n\n--------------------------------------------------------\n\n### new BufferList([ callback | buffer | buffer array ])\nThe constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream.\n\nNormally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object.\n\n`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:\n\n```js\nvar bl = require('bl')\nvar myinstance = bl()\n\n// equivilant to:\n\nvar BufferList = require('bl')\nvar myinstance = new BufferList()\n```\n\n--------------------------------------------------------\n\n### bl.length\nGet the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list.\n\n--------------------------------------------------------\n\n### bl.append(buffer)\n`append(buffer)` adds an additional buffer or BufferList to the internal list.\n\n--------------------------------------------------------\n\n### bl.get(index)\n`get()` will return the byte at the specified index.\n\n--------------------------------------------------------\n\n### bl.slice([ start, [ end ] ])\n`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively.\n\nIf the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer.\n\n--------------------------------------------------------\n\n### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])\n`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively.\n\n--------------------------------------------------------\n\n### bl.duplicate()\n`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example:\n\n```js\nvar bl = new BufferList()\n\nbl.append('hello')\nbl.append(' world')\nbl.append('\\n')\n\nbl.duplicate().pipe(process.stdout, { end: false })\n\nconsole.log(bl.toString())\n```\n\n--------------------------------------------------------\n\n### bl.consume(bytes)\n`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data.\n\n--------------------------------------------------------\n\n### bl.toString([encoding, [ start, [ end ]]])\n`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information.\n\n--------------------------------------------------------\n\n### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8()\n\nAll of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently.\n\nSee the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work.\n\n--------------------------------------------------------\n\n### Streams\n**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance.\n\n--------------------------------------------------------\n\n## Contributors\n\n**bl** is brought to you by the following hackers:\n\n * [Rod Vagg](https://github.com/rvagg)\n * [Matteo Collina](https://github.com/mcollina)\n * [Jarett Cruger](https://github.com/jcrugzz)\n\n=======\n\n\n## License & copyright\n\nCopyright (c) 2013-2014 bl contributors (listed above).\n\nbl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/rvagg/bl/issues" + }, + "_id": "bl@0.9.4", + "_shasum": "4702ddf72fbe0ecd82787c00c113aea1935ad0e7", + "_resolved": "https://registry.npmjs.org/bl/-/bl-0.9.4.tgz", + "_from": "bl@>=0.9.0 <0.10.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/basic-test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/basic-test.js new file mode 100644 index 0000000..75116a3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/basic-test.js @@ -0,0 +1,541 @@ +var tape = require('tape') + , crypto = require('crypto') + , fs = require('fs') + , hash = require('hash_file') + , BufferList = require('../') + + , encodings = + ('hex utf8 utf-8 ascii binary base64' + + (process.browser ? '' : ' ucs2 ucs-2 utf16le utf-16le')).split(' ') + +tape('single bytes from single buffer', function (t) { + var bl = new BufferList() + bl.append(new Buffer('abcd')) + + t.equal(bl.length, 4) + + t.equal(bl.get(0), 97) + t.equal(bl.get(1), 98) + t.equal(bl.get(2), 99) + t.equal(bl.get(3), 100) + + t.end() +}) + +tape('single bytes from multiple buffers', function (t) { + var bl = new BufferList() + bl.append(new Buffer('abcd')) + bl.append(new Buffer('efg')) + bl.append(new Buffer('hi')) + bl.append(new Buffer('j')) + + t.equal(bl.length, 10) + + t.equal(bl.get(0), 97) + t.equal(bl.get(1), 98) + t.equal(bl.get(2), 99) + t.equal(bl.get(3), 100) + t.equal(bl.get(4), 101) + t.equal(bl.get(5), 102) + t.equal(bl.get(6), 103) + t.equal(bl.get(7), 104) + t.equal(bl.get(8), 105) + t.equal(bl.get(9), 106) + t.end() +}) + +tape('multi bytes from single buffer', function (t) { + var bl = new BufferList() + bl.append(new Buffer('abcd')) + + t.equal(bl.length, 4) + + t.equal(bl.slice(0, 4).toString('ascii'), 'abcd') + t.equal(bl.slice(0, 3).toString('ascii'), 'abc') + t.equal(bl.slice(1, 4).toString('ascii'), 'bcd') + + t.end() +}) + +tape('multiple bytes from multiple buffers', function (t) { + var bl = new BufferList() + + bl.append(new Buffer('abcd')) + bl.append(new Buffer('efg')) + bl.append(new Buffer('hi')) + bl.append(new Buffer('j')) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') + t.equal(bl.slice(3, 6).toString('ascii'), 'def') + t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') + t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') + + t.end() +}) + +tape('multiple bytes from multiple buffer lists', function (t) { + var bl = new BufferList() + + bl.append(new BufferList([new Buffer('abcd'), new Buffer('efg')])) + bl.append(new BufferList([new Buffer('hi'), new Buffer('j')])) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') + t.equal(bl.slice(3, 6).toString('ascii'), 'def') + t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') + t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') + + t.end() +}) + +tape('consuming from multiple buffers', function (t) { + var bl = new BufferList() + + bl.append(new Buffer('abcd')) + bl.append(new Buffer('efg')) + bl.append(new Buffer('hi')) + bl.append(new Buffer('j')) + + t.equal(bl.length, 10) + + t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') + + bl.consume(3) + t.equal(bl.length, 7) + t.equal(bl.slice(0, 7).toString('ascii'), 'defghij') + + bl.consume(2) + t.equal(bl.length, 5) + t.equal(bl.slice(0, 5).toString('ascii'), 'fghij') + + bl.consume(1) + t.equal(bl.length, 4) + t.equal(bl.slice(0, 4).toString('ascii'), 'ghij') + + bl.consume(1) + t.equal(bl.length, 3) + t.equal(bl.slice(0, 3).toString('ascii'), 'hij') + + bl.consume(2) + t.equal(bl.length, 1) + t.equal(bl.slice(0, 1).toString('ascii'), 'j') + + t.end() +}) + +tape('test readUInt8 / readInt8', function (t) { + var buf1 = new Buffer(1) + , buf2 = new Buffer(3) + , buf3 = new Buffer(3) + , bl = new BufferList() + + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUInt8(2), 0x3) + t.equal(bl.readInt8(2), 0x3) + t.equal(bl.readUInt8(3), 0x4) + t.equal(bl.readInt8(3), 0x4) + t.equal(bl.readUInt8(4), 0x23) + t.equal(bl.readInt8(4), 0x23) + t.equal(bl.readUInt8(5), 0x42) + t.equal(bl.readInt8(5), 0x42) + t.end() +}) + +tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) { + var buf1 = new Buffer(1) + , buf2 = new Buffer(3) + , buf3 = new Buffer(3) + , bl = new BufferList() + + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUInt16BE(2), 0x0304) + t.equal(bl.readUInt16LE(2), 0x0403) + t.equal(bl.readInt16BE(2), 0x0304) + t.equal(bl.readInt16LE(2), 0x0403) + t.equal(bl.readUInt16BE(3), 0x0423) + t.equal(bl.readUInt16LE(3), 0x2304) + t.equal(bl.readInt16BE(3), 0x0423) + t.equal(bl.readInt16LE(3), 0x2304) + t.equal(bl.readUInt16BE(4), 0x2342) + t.equal(bl.readUInt16LE(4), 0x4223) + t.equal(bl.readInt16BE(4), 0x2342) + t.equal(bl.readInt16LE(4), 0x4223) + t.end() +}) + +tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) { + var buf1 = new Buffer(1) + , buf2 = new Buffer(3) + , buf3 = new Buffer(3) + , bl = new BufferList() + + buf2[1] = 0x3 + buf2[2] = 0x4 + buf3[0] = 0x23 + buf3[1] = 0x42 + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readUInt32BE(2), 0x03042342) + t.equal(bl.readUInt32LE(2), 0x42230403) + t.equal(bl.readInt32BE(2), 0x03042342) + t.equal(bl.readInt32LE(2), 0x42230403) + t.end() +}) + +tape('test readFloatLE / readFloatBE', function (t) { + var buf1 = new Buffer(1) + , buf2 = new Buffer(3) + , buf3 = new Buffer(3) + , bl = new BufferList() + + buf2[1] = 0x00 + buf2[2] = 0x00 + buf3[0] = 0x80 + buf3[1] = 0x3f + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readFloatLE(2), 0x01) + t.end() +}) + +tape('test readDoubleLE / readDoubleBE', function (t) { + var buf1 = new Buffer(1) + , buf2 = new Buffer(3) + , buf3 = new Buffer(10) + , bl = new BufferList() + + buf2[1] = 0x55 + buf2[2] = 0x55 + buf3[0] = 0x55 + buf3[1] = 0x55 + buf3[2] = 0x55 + buf3[3] = 0x55 + buf3[4] = 0xd5 + buf3[5] = 0x3f + + bl.append(buf1) + bl.append(buf2) + bl.append(buf3) + + t.equal(bl.readDoubleLE(2), 0.3333333333333333) + t.end() +}) + +tape('test toString', function (t) { + var bl = new BufferList() + + bl.append(new Buffer('abcd')) + bl.append(new Buffer('efg')) + bl.append(new Buffer('hi')) + bl.append(new Buffer('j')) + + t.equal(bl.toString('ascii', 0, 10), 'abcdefghij') + t.equal(bl.toString('ascii', 3, 10), 'defghij') + t.equal(bl.toString('ascii', 3, 6), 'def') + t.equal(bl.toString('ascii', 3, 8), 'defgh') + t.equal(bl.toString('ascii', 5, 10), 'fghij') + + t.end() +}) + +tape('test toString encoding', function (t) { + var bl = new BufferList() + , b = new Buffer('abcdefghij\xff\x00') + + bl.append(new Buffer('abcd')) + bl.append(new Buffer('efg')) + bl.append(new Buffer('hi')) + bl.append(new Buffer('j')) + bl.append(new Buffer('\xff\x00')) + + encodings.forEach(function (enc) { + t.equal(bl.toString(enc), b.toString(enc), enc) + }) + + t.end() +}) + +!process.browser && tape('test stream', function (t) { + var random = crypto.randomBytes(65534) + , rndhash = hash(random, 'md5') + , md5sum = crypto.createHash('md5') + , bl = new BufferList(function (err, buf) { + t.ok(Buffer.isBuffer(buf)) + t.ok(err === null) + t.equal(rndhash, hash(bl.slice(), 'md5')) + t.equal(rndhash, hash(buf, 'md5')) + + bl.pipe(fs.createWriteStream('/tmp/bl_test_rnd_out.dat')) + .on('close', function () { + var s = fs.createReadStream('/tmp/bl_test_rnd_out.dat') + s.on('data', md5sum.update.bind(md5sum)) + s.on('end', function() { + t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!') + t.end() + }) + }) + + }) + + fs.writeFileSync('/tmp/bl_test_rnd.dat', random) + fs.createReadStream('/tmp/bl_test_rnd.dat').pipe(bl) +}) + +tape('instantiation with Buffer', function (t) { + var buf = crypto.randomBytes(1024) + , buf2 = crypto.randomBytes(1024) + , b = BufferList(buf) + + t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer') + b = BufferList([ buf, buf2 ]) + t.equal(b.slice().toString('hex'), Buffer.concat([ buf, buf2 ]).toString('hex'), 'same buffer') + t.end() +}) + +tape('test String appendage', function (t) { + var bl = new BufferList() + , b = new Buffer('abcdefghij\xff\x00') + + bl.append('abcd') + bl.append('efg') + bl.append('hi') + bl.append('j') + bl.append('\xff\x00') + + encodings.forEach(function (enc) { + t.equal(bl.toString(enc), b.toString(enc)) + }) + + t.end() +}) + +tape('write nothing, should get empty buffer', function (t) { + t.plan(3) + BufferList(function (err, data) { + t.notOk(err, 'no error') + t.ok(Buffer.isBuffer(data), 'got a buffer') + t.equal(0, data.length, 'got a zero-length buffer') + t.end() + }).end() +}) + +tape('unicode string', function (t) { + t.plan(2) + var inp1 = '\u2600' + , inp2 = '\u2603' + , exp = inp1 + ' and ' + inp2 + , bl = BufferList() + bl.write(inp1) + bl.write(' and ') + bl.write(inp2) + t.equal(exp, bl.toString()) + t.equal(new Buffer(exp).toString('hex'), bl.toString('hex')) +}) + +tape('should emit finish', function (t) { + var source = BufferList() + , dest = BufferList() + + source.write('hello') + source.pipe(dest) + + dest.on('finish', function () { + t.equal(dest.toString('utf8'), 'hello') + t.end() + }) +}) + +tape('basic copy', function (t) { + var buf = crypto.randomBytes(1024) + , buf2 = new Buffer(1024) + , b = BufferList(buf) + + b.copy(buf2) + t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') + t.end() +}) + +tape('copy after many appends', function (t) { + var buf = crypto.randomBytes(512) + , buf2 = new Buffer(1024) + , b = BufferList(buf) + + b.append(buf) + b.copy(buf2) + t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') + t.end() +}) + +tape('copy at a precise position', function (t) { + var buf = crypto.randomBytes(1004) + , buf2 = new Buffer(1024) + , b = BufferList(buf) + + b.copy(buf2, 20) + t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer') + t.end() +}) + +tape('copy starting from a precise location', function (t) { + var buf = crypto.randomBytes(10) + , buf2 = new Buffer(5) + , b = BufferList(buf) + + b.copy(buf2, 0, 5) + t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer') + t.end() +}) + +tape('copy in an interval', function (t) { + var rnd = crypto.randomBytes(10) + , b = BufferList(rnd) // put the random bytes there + , actual = new Buffer(3) + , expected = new Buffer(3) + + rnd.copy(expected, 0, 5, 8) + b.copy(actual, 0, 5, 8) + + t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer') + t.end() +}) + +tape('copy an interval between two buffers', function (t) { + var buf = crypto.randomBytes(10) + , buf2 = new Buffer(10) + , b = BufferList(buf) + + b.append(buf) + b.copy(buf2, 0, 5, 15) + + t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer') + t.end() +}) + +tape('duplicate', function (t) { + t.plan(2) + + var bl = new BufferList('abcdefghij\xff\x00') + , dup = bl.duplicate() + + t.equal(bl.prototype, dup.prototype) + t.equal(bl.toString('hex'), dup.toString('hex')) +}) + +tape('destroy no pipe', function (t) { + t.plan(2) + + var bl = new BufferList('alsdkfja;lsdkfja;lsdk') + bl.destroy() + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) +}) + +!process.browser && tape('destroy with pipe before read end', function (t) { + t.plan(2) + + var bl = new BufferList() + fs.createReadStream(__dirname + '/sauce.js') + .pipe(bl) + + bl.destroy() + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) + +}) + +!process.browser && tape('destroy with pipe before read end with race', function (t) { + t.plan(2) + + var bl = new BufferList() + fs.createReadStream(__dirname + '/sauce.js') + .pipe(bl) + + setTimeout(function () { + bl.destroy() + setTimeout(function () { + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) + }, 500) + }, 500) +}) + +!process.browser && tape('destroy with pipe after read end', function (t) { + t.plan(2) + + var bl = new BufferList() + fs.createReadStream(__dirname + '/sauce.js') + .on('end', onEnd) + .pipe(bl) + + function onEnd () { + bl.destroy() + + t.equal(bl._bufs.length, 0) + t.equal(bl.length, 0) + } +}) + +!process.browser && tape('destroy with pipe while writing to a destination', function (t) { + t.plan(4) + + var bl = new BufferList() + , ds = new BufferList() + + fs.createReadStream(__dirname + '/sauce.js') + .on('end', onEnd) + .pipe(bl) + + function onEnd () { + bl.pipe(ds) + + setTimeout(function () { + bl.destroy() + + t.equals(bl._bufs.length, 0) + t.equals(bl.length, 0) + + ds.destroy() + + t.equals(bl._bufs.length, 0) + t.equals(bl.length, 0) + + }, 100) + } +}) + +!process.browser && tape('handle error', function (t) { + t.plan(2) + fs.createReadStream('/does/not/exist').pipe(BufferList(function (err, data) { + t.ok(err instanceof Error, 'has error') + t.notOk(data, 'no data') + })) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/sauce.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/sauce.js new file mode 100644 index 0000000..a6d2862 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/sauce.js @@ -0,0 +1,38 @@ +#!/usr/bin/env node + +const user = process.env.SAUCE_USER + , key = process.env.SAUCE_KEY + , path = require('path') + , brtapsauce = require('brtapsauce') + , testFile = path.join(__dirname, 'basic-test.js') + + , capabilities = [ + { browserName: 'chrome' , platform: 'Windows XP', version: '' } + , { browserName: 'firefox' , platform: 'Windows 8' , version: '' } + , { browserName: 'firefox' , platform: 'Windows XP', version: '4' } + , { browserName: 'internet explorer' , platform: 'Windows 8' , version: '10' } + , { browserName: 'internet explorer' , platform: 'Windows 7' , version: '9' } + , { browserName: 'internet explorer' , platform: 'Windows 7' , version: '8' } + , { browserName: 'internet explorer' , platform: 'Windows XP', version: '7' } + , { browserName: 'internet explorer' , platform: 'Windows XP', version: '6' } + , { browserName: 'safari' , platform: 'Windows 7' , version: '5' } + , { browserName: 'safari' , platform: 'OS X 10.8' , version: '6' } + , { browserName: 'opera' , platform: 'Windows 7' , version: '' } + , { browserName: 'opera' , platform: 'Windows 7' , version: '11' } + , { browserName: 'ipad' , platform: 'OS X 10.8' , version: '6' } + , { browserName: 'android' , platform: 'Linux' , version: '4.0', 'device-type': 'tablet' } + ] + +if (!user) + throw new Error('Must set a SAUCE_USER env var') +if (!key) + throw new Error('Must set a SAUCE_KEY env var') + +brtapsauce({ + name : 'Traversty' + , user : user + , key : key + , brsrc : testFile + , capabilities : capabilities + , options : { timeout: 60 * 6 } +}) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/test.js new file mode 100644 index 0000000..aa9b487 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/bl/test/test.js @@ -0,0 +1,9 @@ +require('./basic-test') + +if (!process.env.SAUCE_KEY || !process.env.SAUCE_USER) + return console.log('SAUCE_KEY and/or SAUCE_USER not set, not running sauce tests') + +if (!/v0\.10/.test(process.version)) + return console.log('Not Node v0.10.x, not running sauce tests') + +require('./sauce.js') \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/README.md new file mode 100644 index 0000000..e5077a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/README.md @@ -0,0 +1,45 @@ +## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing. + +This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set. + +## Usage + +```javascript +var headers = {} + , c = caseless(headers) + ; +c.set('a-Header', 'asdf') +c.get('a-header') === 'asdf' +``` + +## has(key) + +Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with. + +```javascript +c.has('a-header') === 'a-Header' +``` + +## set(key, value[, clobber=true]) + +Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header. + +```javascript +c.set('a-Header', 'fdas') +c.set('a-HEADER', 'more', false) +c.get('a-header') === 'fdsa,more' +``` + +## swap(key) + +Swaps the casing of a header with the new one that is passed in. + +```javascript +var headers = {} + , c = caseless(headers) + ; +c.set('a-Header', 'fdas') +c.swap('a-HEADER') +c.has('a-header') === 'a-HEADER' +headers === {'a-HEADER': 'fdas'} +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/index.js new file mode 100644 index 0000000..ba711f6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/index.js @@ -0,0 +1,65 @@ +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) + } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) + + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i=0.10.0 <0.11.0", + "_npmVersion": "1.4.14", + "_npmUser": { + "name": "nylen", + "email": "jnylen@gmail.com" + }, + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "nylen", + "email": "jnylen@gmail.com" + } + ], + "dist": { + "shasum": "ed6b2719adcd1fd18f58dc081c0f1a5b43963909", + "tarball": "http://registry.npmjs.org/caseless/-/caseless-0.10.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/caseless/-/caseless-0.10.0.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/test.js new file mode 100644 index 0000000..084bbaf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/caseless/test.js @@ -0,0 +1,40 @@ +var tape = require('tape') + , caseless = require('./') + ; + +tape('set get has', function (t) { + var headers = {} + , c = caseless(headers) + ; + t.plan(17) + c.set('a-Header', 'asdf') + t.equal(c.get('a-header'), 'asdf') + t.equal(c.has('a-header'), 'a-Header') + t.ok(!c.has('nothing')) + // old bug where we used the wrong regex + t.ok(!c.has('a-hea')) + c.set('a-header', 'fdsa') + t.equal(c.get('a-header'), 'fdsa') + t.equal(c.get('a-Header'), 'fdsa') + c.set('a-HEADER', 'more', false) + t.equal(c.get('a-header'), 'fdsa,more') + + t.deepEqual(headers, {'a-Header': 'fdsa,more'}) + c.swap('a-HEADER') + t.deepEqual(headers, {'a-HEADER': 'fdsa,more'}) + + c.set('deleteme', 'foobar') + t.ok(c.has('deleteme')) + t.ok(c.del('deleteme')) + t.notOk(c.has('deleteme')) + t.notOk(c.has('idonotexist')) + t.ok(c.del('idonotexist')) + + c.set('tva', 'test1') + c.set('tva-header', 'test2') + t.equal(c.has('tva'), 'tva') + t.notOk(c.has('header')) + + t.equal(c.get('tva'), 'test1') + +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/License b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/Readme.md new file mode 100644 index 0000000..3068adc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/Readme.md @@ -0,0 +1,139 @@ +# combined-stream + +A stream that emits multiple other streams one after another. + +**NB** This module uses streams1 and will always use streams1 for +compatibility. If you're looking for something to use for your project, please +use a streams2 module, e.g., +[multistream](https://www.npmjs.com/package/multistream). Moreover, this module +is maintained for bugfixes to current downstream consumers, so PRs which add +features generally aren't accepted. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/lib/combined_stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 0000000..6b5c21b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,188 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/.npmignore new file mode 100644 index 0000000..9daeafb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/.npmignore @@ -0,0 +1 @@ +test diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/License b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Makefile new file mode 100644 index 0000000..b4ff85a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Makefile @@ -0,0 +1,7 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +.PHONY: test + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Readme.md new file mode 100644 index 0000000..aca36f9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/Readme.md @@ -0,0 +1,141 @@ +# delayed-stream + +Buffers events from a stream until you are ready to handle them. + +## Installation + +``` bash +npm install delayed-stream +``` + +## Usage + +The following example shows how to write a http echo server that delays its +response by 1000 ms. + +``` javascript +var DelayedStream = require('delayed-stream'); +var http = require('http'); + +http.createServer(function(req, res) { + var delayed = DelayedStream.create(req); + + setTimeout(function() { + res.writeHead(200); + delayed.pipe(res); + }, 1000); +}); +``` + +If you are not using `Stream#pipe`, you can also manually release the buffered +events by calling `delayedStream.resume()`: + +``` javascript +var delayed = DelayedStream.create(req); + +setTimeout(function() { + // Emit all buffered events and resume underlaying source + delayed.resume(); +}, 1000); +``` + +## Implementation + +In order to use this meta stream properly, here are a few things you should +know about the implementation. + +### Event Buffering / Proxying + +All events of the `source` stream are hijacked by overwriting the `source.emit` +method. Until node implements a catch-all event listener, this is the only way. + +However, delayed-stream still continues to emit all events it captures on the +`source`, regardless of whether you have released the delayed stream yet or +not. + +Upon creation, delayed-stream captures all `source` events and stores them in +an internal event buffer. Once `delayedStream.release()` is called, all +buffered events are emitted on the `delayedStream`, and the event buffer is +cleared. After that, delayed-stream merely acts as a proxy for the underlaying +source. + +### Error handling + +Error events on `source` are buffered / proxied just like any other events. +However, `delayedStream.create` attaches a no-op `'error'` listener to the +`source`. This way you only have to handle errors on the `delayedStream` +object, rather than in two places. + +### Buffer limits + +delayed-stream provides a `maxDataSize` property that can be used to limit +the amount of data being buffered. In order to protect you from bad `source` +streams that don't react to `source.pause()`, this feature is enabled by +default. + +## API + +### DelayedStream.create(source, [options]) + +Returns a new `delayedStream`. Available options are: + +* `pauseStream` +* `maxDataSize` + +The description for those properties can be found below. + +### delayedStream.source + +The `source` stream managed by this object. This is useful if you are +passing your `delayedStream` around, and you still want to access properties +on the `source` object. + +### delayedStream.pauseStream = true + +Whether to pause the underlaying `source` when calling +`DelayedStream.create()`. Modifying this property afterwards has no effect. + +### delayedStream.maxDataSize = 1024 * 1024 + +The amount of data to buffer before emitting an `error`. + +If the underlaying source is emitting `Buffer` objects, the `maxDataSize` +refers to bytes. + +If the underlaying source is emitting JavaScript strings, the size refers to +characters. + +If you know what you are doing, you can set this property to `Infinity` to +disable this feature. You can also modify this property during runtime. + +### delayedStream.dataSize = 0 + +The amount of data buffered so far. + +### delayedStream.readable + +An ECMA5 getter that returns the value of `source.readable`. + +### delayedStream.resume() + +If the `delayedStream` has not been released so far, `delayedStream.release()` +is called. + +In either case, `source.resume()` is called. + +### delayedStream.pause() + +Calls `source.pause()`. + +### delayedStream.pipe(dest) + +Calls `delayedStream.resume()` and then proxies the arguments to `source.pipe`. + +### delayedStream.release() + +Emits and clears all events that have been buffered up so far. This does not +resume the underlaying source, use `delayedStream.resume()` instead. + +## License + +delayed-stream is licensed under the MIT license. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js new file mode 100644 index 0000000..b38fc85 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js @@ -0,0 +1,107 @@ +var Stream = require('stream').Stream; +var util = require('util'); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); + +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/package.json new file mode 100644 index 0000000..ab9bbe4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/package.json @@ -0,0 +1,63 @@ +{ + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "contributors": [ + { + "name": "Mike Atkins", + "email": "apeherder@gmail.com" + } + ], + "name": "delayed-stream", + "description": "Buffers events from a stream until you are ready to handle them.", + "license": "MIT", + "version": "1.0.0", + "homepage": "https://github.com/felixge/node-delayed-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-delayed-stream.git" + }, + "main": "./lib/delayed_stream", + "engines": { + "node": ">=0.4.0" + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "fake": "0.2.0", + "far": "0.0.1" + }, + "gitHead": "07a9dc99fb8f1a488160026b9ad77493f766fb84", + "bugs": { + "url": "https://github.com/felixge/node-delayed-stream/issues" + }, + "_id": "delayed-stream@1.0.0", + "_shasum": "df3ae199acadfb7d440aaae0b29e2272b24ec619", + "_from": "delayed-stream@>=1.0.0 <2.0.0", + "_npmVersion": "2.8.3", + "_nodeVersion": "1.6.4", + "_npmUser": { + "name": "apechimp", + "email": "apeherder@gmail.com" + }, + "dist": { + "shasum": "df3ae199acadfb7d440aaae0b29e2272b24ec619", + "tarball": "http://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz" + }, + "maintainers": [ + { + "name": "felixge", + "email": "felix@debuggable.com" + }, + { + "name": "apechimp", + "email": "apeherder@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/package.json new file mode 100644 index 0000000..f0ad401 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/combined-stream/package.json @@ -0,0 +1,66 @@ +{ + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "name": "combined-stream", + "description": "A stream that emits multiple other streams one after another.", + "version": "1.0.3", + "homepage": "https://github.com/felixge/node-combined-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "main": "./lib/combined_stream", + "scripts": { + "test": "node test/run.js" + }, + "engines": { + "node": ">= 0.8" + }, + "dependencies": { + "delayed-stream": "^1.0.0" + }, + "devDependencies": { + "far": "~0.0.7" + }, + "license": "MIT", + "gitHead": "f1a12682aed63acb3cd66857104202a7e7ca5565", + "bugs": { + "url": "https://github.com/felixge/node-combined-stream/issues" + }, + "_id": "combined-stream@1.0.3", + "_shasum": "c224cc35d3cb98e25dead532472a18e8f75df5ab", + "_from": "combined-stream@>=1.0.1 <1.1.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "apechimp", + "email": "apeherder@gmail.com" + }, + "dist": { + "shasum": "c224cc35d3cb98e25dead532472a18e8f75df5ab", + "tarball": "http://registry.npmjs.org/combined-stream/-/combined-stream-1.0.3.tgz" + }, + "maintainers": [ + { + "name": "felixge", + "email": "felix@debuggable.com" + }, + { + "name": "celer", + "email": "dtyree77@gmail.com" + }, + { + "name": "alexindigo", + "email": "iam@alexindigo.com" + }, + { + "name": "apechimp", + "email": "apeherder@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.3.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/README.md new file mode 100644 index 0000000..9d5b663 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/README.md @@ -0,0 +1,4 @@ +forever-agent +============= + +HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/index.js new file mode 100644 index 0000000..416c7ab --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/index.js @@ -0,0 +1,138 @@ +module.exports = ForeverAgent +ForeverAgent.SSL = ForeverAgentSSL + +var util = require('util') + , Agent = require('http').Agent + , net = require('net') + , tls = require('tls') + , AgentSSL = require('https').Agent + +function getConnectionName(host, port) { + var name = '' + if (typeof host === 'string') { + name = host + ':' + port + } else { + // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. + name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') + } + return name +} + +function ForeverAgent(options) { + var self = this + self.options = options || {} + self.requests = {} + self.sockets = {} + self.freeSockets = {} + self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets + self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets + self.on('free', function(socket, host, port) { + var name = getConnectionName(host, port) + + if (self.requests[name] && self.requests[name].length) { + self.requests[name].shift().onSocket(socket) + } else if (self.sockets[name].length < self.minSockets) { + if (!self.freeSockets[name]) self.freeSockets[name] = [] + self.freeSockets[name].push(socket) + + // if an error happens while we don't use the socket anyway, meh, throw the socket away + var onIdleError = function() { + socket.destroy() + } + socket._onIdleError = onIdleError + socket.on('error', onIdleError) + } else { + // If there are no pending requests just destroy the + // socket and it will get removed from the pool. This + // gets us out of timeout issues and allows us to + // default to Connection:keep-alive. + socket.destroy() + } + }) + +} +util.inherits(ForeverAgent, Agent) + +ForeverAgent.defaultMinSockets = 5 + + +ForeverAgent.prototype.createConnection = net.createConnection +ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest +ForeverAgent.prototype.addRequest = function(req, host, port) { + var name = getConnectionName(host, port) + + if (typeof host !== 'string') { + var options = host + port = options.port + host = options.host + } + + if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { + var idleSocket = this.freeSockets[name].pop() + idleSocket.removeListener('error', idleSocket._onIdleError) + delete idleSocket._onIdleError + req._reusedSocket = true + req.onSocket(idleSocket) + } else { + this.addRequestNoreuse(req, host, port) + } +} + +ForeverAgent.prototype.removeSocket = function(s, name, host, port) { + if (this.sockets[name]) { + var index = this.sockets[name].indexOf(s) + if (index !== -1) { + this.sockets[name].splice(index, 1) + } + } else if (this.sockets[name] && this.sockets[name].length === 0) { + // don't leak + delete this.sockets[name] + delete this.requests[name] + } + + if (this.freeSockets[name]) { + var index = this.freeSockets[name].indexOf(s) + if (index !== -1) { + this.freeSockets[name].splice(index, 1) + if (this.freeSockets[name].length === 0) { + delete this.freeSockets[name] + } + } + } + + if (this.requests[name] && this.requests[name].length) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(name, host, port).emit('free') + } +} + +function ForeverAgentSSL (options) { + ForeverAgent.call(this, options) +} +util.inherits(ForeverAgentSSL, ForeverAgent) + +ForeverAgentSSL.prototype.createConnection = createConnectionSSL +ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest + +function createConnectionSSL (port, host, options) { + if (typeof port === 'object') { + options = port; + } else if (typeof host === 'object') { + options = host; + } else if (typeof options === 'object') { + options = options; + } else { + options = {}; + } + + if (typeof port === 'number') { + options.port = port; + } + + if (typeof host === 'string') { + options.host = host; + } + + return tls.connect(options); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/package.json new file mode 100644 index 0000000..ef074a5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/forever-agent/package.json @@ -0,0 +1,56 @@ +{ + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "name": "forever-agent", + "description": "HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module.", + "version": "0.6.1", + "license": "Apache-2.0", + "repository": { + "url": "git+https://github.com/mikeal/forever-agent.git" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "gitHead": "1b3b6163f2b3c2c4122bbfa288c1325c0df9871d", + "bugs": { + "url": "https://github.com/mikeal/forever-agent/issues" + }, + "homepage": "https://github.com/mikeal/forever-agent", + "_id": "forever-agent@0.6.1", + "scripts": {}, + "_shasum": "fbc71f0c41adeb37f96c577ad1ed42d8fdacca91", + "_from": "forever-agent@>=0.6.0 <0.7.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + }, + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "nylen", + "email": "jnylen@gmail.com" + }, + { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + } + ], + "dist": { + "shasum": "fbc71f0c41adeb37f96c577ad1ed42d8fdacca91", + "tarball": "http://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/License b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/License new file mode 100644 index 0000000..c7ff12a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/License @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and 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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/Readme.md new file mode 100644 index 0000000..c8a1a55 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/Readme.md @@ -0,0 +1,175 @@ +# Form-Data [![Build Status](https://travis-ci.org/felixge/node-form-data.png?branch=master)](https://travis-ci.org/felixge/node-form-data) [![Dependency Status](https://gemnasium.com/felixge/node-form-data.png)](https://gemnasium.com/felixge/node-form-data) + +A module to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. + +The API of this module is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. + +[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface +[streams2-thing]: http://nodejs.org/api/stream.html#stream_compatibility_with_older_node_versions + +## Install + +``` +npm install form-data +``` + +## Usage + +In this example we are constructing a form with 3 fields that contain a string, +a buffer and a file stream. + +``` javascript +var FormData = require('form-data'); +var fs = require('fs'); + +var form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +``` + +Also you can use http-response stream: + +``` javascript +var FormData = require('form-data'); +var http = require('http'); + +var form = new FormData(); + +http.request('http://nodejs.org/images/logo.png', function(response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); +}); +``` + +Or @mikeal's request stream: + +``` javascript +var FormData = require('form-data'); +var request = require('request'); + +var form = new FormData(); + +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_logo', request('http://nodejs.org/images/logo.png')); +``` + +In order to submit this form to a web application, call ```submit(url, [callback])``` method: + +``` javascript +form.submit('http://example.org/', function(err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); // for node-0.10.x +}); + +``` + +For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. + +### Alternative submission methods + +You can use node's http client interface: + +``` javascript +var http = require('http'); + +var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() +}); + +form.pipe(request); + +request.on('response', function(res) { + console.log(res.statusCode); +}); +``` + +Or if you would prefer the `'Content-Length'` header to be set for you: + +``` javascript +form.submit('example.org/upload', function(err, res) { + console.log(res.statusCode); +}); +``` + +To use custom headers and pre-known length in parts: + +``` javascript +var CRLF = '\r\n'; +var form = new FormData(); + +var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 +}; + +form.append('my_buffer', buffer, options); + +form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); +}); +``` + +Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: + +``` javascript +someModule.stream(function(err, stdout, stderr) { + if (err) throw err; + + var form = new FormData(); + + form.append('file', stdout, { + filename: 'unicycle.jpg', + contentType: 'image/jpg', + knownLength: 19806 + }); + + form.submit('http://example.com/', function(err, res) { + if (err) throw err; + console.log('Done'); + }); +}); +``` + +For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: + +``` javascript +form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: + +``` javascript +form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: {'x-test-header': 'test-header-value'} +}, function(err, res) { + console.log(res.statusCode); +}); +``` + +## Notes + +- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. +- If it feels like FormData hangs after submit and you're on ```node-0.10```, please check [Compatibility with Older Node Versions][streams2-thing] + +## TODO + +- Add new streams (0.10) support and try really hard not to break it for 0.8.x. + +## License + +Form-Data is licensed under the MIT license. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/lib/form_data.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/lib/form_data.js new file mode 100644 index 0000000..5b33f55 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/lib/form_data.js @@ -0,0 +1,351 @@ +var CombinedStream = require('combined-stream'); +var util = require('util'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var parseUrl = require('url').parse; +var fs = require('fs'); +var mime = require('mime-types'); +var async = require('async'); + +module.exports = FormData; +function FormData() { + this._overheadLength = 0; + this._valueLength = 0; + this._lengthRetrievers = []; + + CombinedStream.call(this); +} +util.inherits(FormData, CombinedStream); + +FormData.LINE_BREAK = '\r\n'; + +FormData.prototype.append = function(field, value, options) { + options = options || {}; + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') value = ''+value; + + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(field, value, options); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + return; + } + + // no need to bother with the length + if (!options.knownLength) + this._lengthRetrievers.push(function(next) { + + if (value.hasOwnProperty('fd')) { + + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + + // when end specified + // no need to calculate range + // inclusive, starts with 0 + next(null, value.end+1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + + var fileSize; + + if (err) { + next(err); + return; + } + + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + next(null, fileSize); + }); + } + + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + next(null, +value.headers['content-length']); + + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + next(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + next('Unknown stream'); + } + }); +}; + +FormData.prototype._multiPartHeader = function(field, value, options) { + var boundary = this.getBoundary(); + var header = ''; + + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (options.header != null) { + header = options.header; + } else { + header += '--' + boundary + FormData.LINE_BREAK + + 'Content-Disposition: form-data; name="' + field + '"'; + + // fs- and request- streams have path property + // or use custom filename and/or contentType + // TODO: Use request's response mime-type + if (options.filename || value.path) { + header += + '; filename="' + path.basename(options.filename || value.path) + '"' + FormData.LINE_BREAK + + 'Content-Type: ' + (options.contentType || mime.lookup(options.filename || value.path)); + + // http response has not + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + header += + '; filename="' + path.basename(value.client._httpMessage.path) + '"' + FormData.LINE_BREAK + + 'Content-Type: ' + value.headers['content-type']; + } + + header += FormData.LINE_BREAK + FormData.LINE_BREAK; + } + + return header; +}; + +FormData.prototype._multiPartFooter = function(field, value, options) { + return function(next) { + var footer = FormData.LINE_BREAK; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--'; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (var header in userHeaders) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + + return formHeaders; +} + +FormData.prototype.getCustomHeaders = function(contentType) { + contentType = contentType ? contentType : 'multipart/form-data'; + + var formHeaders = { + 'content-type': contentType + '; boundary=' + this.getBoundary(), + 'content-length': this.getLengthSync() + }; + + return formHeaders; +} + +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; +}; + +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + + this._boundary = boundary; +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function(debug) { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + // https://github.com/felixge/node-form-data/issues/40 + if (this._lengthRetrievers.length) { + // Some async length retrivers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + + return knownLength; +}; + +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._lengthRetrievers.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + async.parallel(this._lengthRetrievers, function(err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function(length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function(params, cb) { + + var request + , options + , defaults = { + method : 'post' + }; + + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + params = parseUrl(params); + + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname + }, defaults); + } + else // use custom params + { + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } + + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (params.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } + + // get content length and fire away + this.getLength(function(err, length) { + + // TODO: Add chunked encoding when no length (if err) + + // add content length + request.setHeader('Content-Length', length); + + this.pipe(request); + if (cb) { + request.on('error', cb); + request.on('response', cb.bind(this, null)); + } + }.bind(this)); + + return request; +}; + +FormData.prototype._error = function(err) { + if (this.error) return; + + this.error = err; + this.pause(); + this.emit('error', err); +}; + +/* + * Santa's little helpers + */ + +// populates missing values +function populate(dst, src) { + for (var prop in src) { + if (!dst[prop]) dst[prop] = src[prop]; + } + return dst; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/License b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/Readme.md new file mode 100644 index 0000000..8043cb4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/Readme.md @@ -0,0 +1,132 @@ +# combined-stream [![Build Status](https://travis-ci.org/felixge/node-combined-stream.svg?branch=master)](https://travis-ci.org/felixge/node-combined-stream) + +A stream that emits multiple other streams one after another. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 0000000..6b5c21b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,188 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/.npmignore new file mode 100644 index 0000000..2fedb26 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/.npmignore @@ -0,0 +1,2 @@ +*.un~ +/node_modules/* diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/License b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/License new file mode 100644 index 0000000..4804b7a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Makefile new file mode 100644 index 0000000..b4ff85a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Makefile @@ -0,0 +1,7 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +.PHONY: test + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Readme.md new file mode 100644 index 0000000..5cb5b35 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/Readme.md @@ -0,0 +1,154 @@ +# delayed-stream + +Buffers events from a stream until you are ready to handle them. + +## Installation + +``` bash +npm install delayed-stream +``` + +## Usage + +The following example shows how to write a http echo server that delays its +response by 1000 ms. + +``` javascript +var DelayedStream = require('delayed-stream'); +var http = require('http'); + +http.createServer(function(req, res) { + var delayed = DelayedStream.create(req); + + setTimeout(function() { + res.writeHead(200); + delayed.pipe(res); + }, 1000); +}); +``` + +If you are not using `Stream#pipe`, you can also manually release the buffered +events by calling `delayedStream.resume()`: + +``` javascript +var delayed = DelayedStream.create(req); + +setTimeout(function() { + // Emit all buffered events and resume underlaying source + delayed.resume(); +}, 1000); +``` + +## Implementation + +In order to use this meta stream properly, here are a few things you should +know about the implementation. + +### Event Buffering / Proxying + +All events of the `source` stream are hijacked by overwriting the `source.emit` +method. Until node implements a catch-all event listener, this is the only way. + +However, delayed-stream still continues to emit all events it captures on the +`source`, regardless of whether you have released the delayed stream yet or +not. + +Upon creation, delayed-stream captures all `source` events and stores them in +an internal event buffer. Once `delayedStream.release()` is called, all +buffered events are emitted on the `delayedStream`, and the event buffer is +cleared. After that, delayed-stream merely acts as a proxy for the underlaying +source. + +### Error handling + +Error events on `source` are buffered / proxied just like any other events. +However, `delayedStream.create` attaches a no-op `'error'` listener to the +`source`. This way you only have to handle errors on the `delayedStream` +object, rather than in two places. + +### Buffer limits + +delayed-stream provides a `maxDataSize` property that can be used to limit +the amount of data being buffered. In order to protect you from bad `source` +streams that don't react to `source.pause()`, this feature is enabled by +default. + +## API + +### DelayedStream.create(source, [options]) + +Returns a new `delayedStream`. Available options are: + +* `pauseStream` +* `maxDataSize` + +The description for those properties can be found below. + +### delayedStream.source + +The `source` stream managed by this object. This is useful if you are +passing your `delayedStream` around, and you still want to access properties +on the `source` object. + +### delayedStream.pauseStream = true + +Whether to pause the underlaying `source` when calling +`DelayedStream.create()`. Modifying this property afterwards has no effect. + +### delayedStream.maxDataSize = 1024 * 1024 + +The amount of data to buffer before emitting an `error`. + +If the underlaying source is emitting `Buffer` objects, the `maxDataSize` +refers to bytes. + +If the underlaying source is emitting JavaScript strings, the size refers to +characters. + +If you know what you are doing, you can set this property to `Infinity` to +disable this feature. You can also modify this property during runtime. + +### delayedStream.maxDataSize = 1024 * 1024 + +The amount of data to buffer before emitting an `error`. + +If the underlaying source is emitting `Buffer` objects, the `maxDataSize` +refers to bytes. + +If the underlaying source is emitting JavaScript strings, the size refers to +characters. + +If you know what you are doing, you can set this property to `Infinity` to +disable this feature. + +### delayedStream.dataSize = 0 + +The amount of data buffered so far. + +### delayedStream.readable + +An ECMA5 getter that returns the value of `source.readable`. + +### delayedStream.resume() + +If the `delayedStream` has not been released so far, `delayedStream.release()` +is called. + +In either case, `source.resume()` is called. + +### delayedStream.pause() + +Calls `source.pause()`. + +### delayedStream.pipe(dest) + +Calls `delayedStream.resume()` and then proxies the arguments to `source.pipe`. + +### delayedStream.release() + +Emits and clears all events that have been buffered up so far. This does not +resume the underlaying source, use `delayedStream.resume()` instead. + +## License + +delayed-stream is licensed under the MIT license. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js new file mode 100644 index 0000000..7c10d48 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js @@ -0,0 +1,99 @@ +var Stream = require('stream').Stream; +var util = require('util'); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; +}; + +DelayedStream.prototype.__defineGetter__('readable', function() { + return this.source.readable; +}); + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/package.json new file mode 100644 index 0000000..8249003 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/package.json @@ -0,0 +1,33 @@ +{ + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "name": "delayed-stream", + "description": "Buffers events from a stream until you are ready to handle them.", + "version": "0.0.5", + "homepage": "https://github.com/felixge/node-delayed-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-delayed-stream.git" + }, + "main": "./lib/delayed_stream", + "engines": { + "node": ">=0.4.0" + }, + "dependencies": {}, + "devDependencies": { + "fake": "0.2.0", + "far": "0.0.1" + }, + "readme": "# delayed-stream\n\nBuffers events from a stream until you are ready to handle them.\n\n## Installation\n\n``` bash\nnpm install delayed-stream\n```\n\n## Usage\n\nThe following example shows how to write a http echo server that delays its\nresponse by 1000 ms.\n\n``` javascript\nvar DelayedStream = require('delayed-stream');\nvar http = require('http');\n\nhttp.createServer(function(req, res) {\n var delayed = DelayedStream.create(req);\n\n setTimeout(function() {\n res.writeHead(200);\n delayed.pipe(res);\n }, 1000);\n});\n```\n\nIf you are not using `Stream#pipe`, you can also manually release the buffered\nevents by calling `delayedStream.resume()`:\n\n``` javascript\nvar delayed = DelayedStream.create(req);\n\nsetTimeout(function() {\n // Emit all buffered events and resume underlaying source\n delayed.resume();\n}, 1000);\n```\n\n## Implementation\n\nIn order to use this meta stream properly, here are a few things you should\nknow about the implementation.\n\n### Event Buffering / Proxying\n\nAll events of the `source` stream are hijacked by overwriting the `source.emit`\nmethod. Until node implements a catch-all event listener, this is the only way.\n\nHowever, delayed-stream still continues to emit all events it captures on the\n`source`, regardless of whether you have released the delayed stream yet or\nnot.\n\nUpon creation, delayed-stream captures all `source` events and stores them in\nan internal event buffer. Once `delayedStream.release()` is called, all\nbuffered events are emitted on the `delayedStream`, and the event buffer is\ncleared. After that, delayed-stream merely acts as a proxy for the underlaying\nsource.\n\n### Error handling\n\nError events on `source` are buffered / proxied just like any other events.\nHowever, `delayedStream.create` attaches a no-op `'error'` listener to the\n`source`. This way you only have to handle errors on the `delayedStream`\nobject, rather than in two places.\n\n### Buffer limits\n\ndelayed-stream provides a `maxDataSize` property that can be used to limit\nthe amount of data being buffered. In order to protect you from bad `source`\nstreams that don't react to `source.pause()`, this feature is enabled by\ndefault.\n\n## API\n\n### DelayedStream.create(source, [options])\n\nReturns a new `delayedStream`. Available options are:\n\n* `pauseStream`\n* `maxDataSize`\n\nThe description for those properties can be found below.\n\n### delayedStream.source\n\nThe `source` stream managed by this object. This is useful if you are\npassing your `delayedStream` around, and you still want to access properties\non the `source` object.\n\n### delayedStream.pauseStream = true\n\nWhether to pause the underlaying `source` when calling\n`DelayedStream.create()`. Modifying this property afterwards has no effect.\n\n### delayedStream.maxDataSize = 1024 * 1024\n\nThe amount of data to buffer before emitting an `error`.\n\nIf the underlaying source is emitting `Buffer` objects, the `maxDataSize`\nrefers to bytes.\n\nIf the underlaying source is emitting JavaScript strings, the size refers to\ncharacters.\n\nIf you know what you are doing, you can set this property to `Infinity` to\ndisable this feature. You can also modify this property during runtime.\n\n### delayedStream.maxDataSize = 1024 * 1024\n\nThe amount of data to buffer before emitting an `error`.\n\nIf the underlaying source is emitting `Buffer` objects, the `maxDataSize`\nrefers to bytes.\n\nIf the underlaying source is emitting JavaScript strings, the size refers to\ncharacters.\n\nIf you know what you are doing, you can set this property to `Infinity` to\ndisable this feature.\n\n### delayedStream.dataSize = 0\n\nThe amount of data buffered so far.\n\n### delayedStream.readable\n\nAn ECMA5 getter that returns the value of `source.readable`.\n\n### delayedStream.resume()\n\nIf the `delayedStream` has not been released so far, `delayedStream.release()`\nis called.\n\nIn either case, `source.resume()` is called.\n\n### delayedStream.pause()\n\nCalls `source.pause()`.\n\n### delayedStream.pipe(dest)\n\nCalls `delayedStream.resume()` and then proxies the arguments to `source.pipe`.\n\n### delayedStream.release()\n\nEmits and clears all events that have been buffered up so far. This does not\nresume the underlaying source, use `delayedStream.resume()` instead.\n\n## License\n\ndelayed-stream is licensed under the MIT license.\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/felixge/node-delayed-stream/issues" + }, + "_id": "delayed-stream@0.0.5", + "_shasum": "d4b1f43a93e8296dfe02694f4680bc37a313c73f", + "_resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-0.0.5.tgz", + "_from": "delayed-stream@0.0.5" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/common.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/common.js new file mode 100644 index 0000000..4d71b8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/common.js @@ -0,0 +1,6 @@ +var common = module.exports; + +common.DelayedStream = require('..'); +common.assert = require('assert'); +common.fake = require('fake'); +common.PORT = 49252; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-http-upload.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-http-upload.js new file mode 100644 index 0000000..9ecad5b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-http-upload.js @@ -0,0 +1,38 @@ +var common = require('../common'); +var assert = common.assert; +var DelayedStream = common.DelayedStream; +var http = require('http'); + +var UPLOAD = new Buffer(10 * 1024 * 1024); + +var server = http.createServer(function(req, res) { + var delayed = DelayedStream.create(req, {maxDataSize: UPLOAD.length}); + + setTimeout(function() { + res.writeHead(200); + delayed.pipe(res); + }, 10); +}); +server.listen(common.PORT, function() { + var request = http.request({ + method: 'POST', + port: common.PORT, + }); + + request.write(UPLOAD); + request.end(); + + request.on('response', function(res) { + var received = 0; + res + .on('data', function(chunk) { + received += chunk.length; + }) + .on('end', function() { + assert.equal(received, UPLOAD.length); + server.close(); + }); + }); +}); + + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-auto-pause.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-auto-pause.js new file mode 100644 index 0000000..6f417f3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-auto-pause.js @@ -0,0 +1,21 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testAutoPause() { + var source = new Stream(); + + fake.expect(source, 'pause', 1); + var delayedStream = DelayedStream.create(source); + fake.verify(); +})(); + +(function testDisableAutoPause() { + var source = new Stream(); + fake.expect(source, 'pause', 0); + + var delayedStream = DelayedStream.create(source, {pauseStream: false}); + fake.verify(); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-pause.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-pause.js new file mode 100644 index 0000000..b50c397 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream-pause.js @@ -0,0 +1,14 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testDelayEventsUntilResume() { + var source = new Stream(); + var delayedStream = DelayedStream.create(source, {pauseStream: false}); + + fake.expect(source, 'pause'); + delayedStream.pause(); + fake.verify(); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream.js new file mode 100644 index 0000000..fc4047e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-delayed-stream.js @@ -0,0 +1,48 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testDelayEventsUntilResume() { + var source = new Stream(); + var delayedStream = DelayedStream.create(source, {pauseStream: false}); + + // delayedStream must not emit until we resume + fake.expect(delayedStream, 'emit', 0); + + // but our original source must emit + var params = []; + source.on('foo', function(param) { + params.push(param); + }); + + source.emit('foo', 1); + source.emit('foo', 2); + + // Make sure delayedStream did not emit, and source did + assert.deepEqual(params, [1, 2]); + fake.verify(); + + // After resume, delayedStream must playback all events + fake + .stub(delayedStream, 'emit') + .times(Infinity) + .withArg(1, 'newListener'); + fake.expect(delayedStream, 'emit', ['foo', 1]); + fake.expect(delayedStream, 'emit', ['foo', 2]); + fake.expect(source, 'resume'); + + delayedStream.resume(); + fake.verify(); + + // Calling resume again will delegate to source + fake.expect(source, 'resume'); + delayedStream.resume(); + fake.verify(); + + // Emitting more events directly leads to them being emitted + fake.expect(delayedStream, 'emit', ['foo', 3]); + source.emit('foo', 3); + fake.verify(); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-handle-source-errors.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-handle-source-errors.js new file mode 100644 index 0000000..a9d35e7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-handle-source-errors.js @@ -0,0 +1,15 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testHandleSourceErrors() { + var source = new Stream(); + var delayedStream = DelayedStream.create(source, {pauseStream: false}); + + // We deal with this by attaching a no-op listener to 'error' on the source + // when creating a new DelayedStream. This way error events on the source + // won't throw. + source.emit('error', new Error('something went wrong')); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-max-data-size.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-max-data-size.js new file mode 100644 index 0000000..7638a2b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-max-data-size.js @@ -0,0 +1,18 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testMaxDataSize() { + var source = new Stream(); + var delayedStream = DelayedStream.create(source, {maxDataSize: 1024, pauseStream: false}); + + source.emit('data', new Buffer(1024)); + + fake + .expect(delayedStream, 'emit') + .withArg(1, 'error'); + source.emit('data', new Buffer(1)); + fake.verify(); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-pipe-resumes.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-pipe-resumes.js new file mode 100644 index 0000000..7d312ab --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-pipe-resumes.js @@ -0,0 +1,13 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testPipeReleases() { + var source = new Stream(); + var delayedStream = DelayedStream.create(source, {pauseStream: false}); + + fake.expect(delayedStream, 'resume'); + delayedStream.pipe(new Stream()); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-proxy-readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-proxy-readable.js new file mode 100644 index 0000000..d436163 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-proxy-readable.js @@ -0,0 +1,13 @@ +var common = require('../common'); +var assert = common.assert; +var fake = common.fake.create(); +var DelayedStream = common.DelayedStream; +var Stream = require('stream').Stream; + +(function testProxyReadableProperty() { + var source = new Stream(); + var delayedStream = DelayedStream.create(source, {pauseStream: false}); + + source.readable = fake.value('source.readable'); + assert.strictEqual(delayedStream.readable, source.readable); +})(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/run.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/run.js new file mode 100755 index 0000000..0bb8e82 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/run.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node +var far = require('far').create(); + +far.add(__dirname); +far.include(/test-.*\.js$/); + +far.execute(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/package.json new file mode 100644 index 0000000..57c38da --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/node_modules/combined-stream/package.json @@ -0,0 +1,37 @@ +{ + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "name": "combined-stream", + "description": "A stream that emits multiple other streams one after another.", + "version": "0.0.7", + "homepage": "https://github.com/felixge/node-combined-stream", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "main": "./lib/combined_stream", + "scripts": { + "test": "node test/run.js" + }, + "engines": { + "node": ">= 0.8" + }, + "dependencies": { + "delayed-stream": "0.0.5" + }, + "devDependencies": { + "far": "~0.0.7" + }, + "readme": "# combined-stream [![Build Status](https://travis-ci.org/felixge/node-combined-stream.svg?branch=master)](https://travis-ci.org/felixge/node-combined-stream)\n\nA stream that emits multiple other streams one after another.\n\n## Installation\n\n``` bash\nnpm install combined-stream\n```\n\n## Usage\n\nHere is a simple example that shows how you can use combined-stream to combine\ntwo files into one:\n\n``` javascript\nvar CombinedStream = require('combined-stream');\nvar fs = require('fs');\n\nvar combinedStream = CombinedStream.create();\ncombinedStream.append(fs.createReadStream('file1.txt'));\ncombinedStream.append(fs.createReadStream('file2.txt'));\n\ncombinedStream.pipe(fs.createWriteStream('combined.txt'));\n```\n\nWhile the example above works great, it will pause all source streams until\nthey are needed. If you don't want that to happen, you can set `pauseStreams`\nto `false`:\n\n``` javascript\nvar CombinedStream = require('combined-stream');\nvar fs = require('fs');\n\nvar combinedStream = CombinedStream.create({pauseStreams: false});\ncombinedStream.append(fs.createReadStream('file1.txt'));\ncombinedStream.append(fs.createReadStream('file2.txt'));\n\ncombinedStream.pipe(fs.createWriteStream('combined.txt'));\n```\n\nHowever, what if you don't have all the source streams yet, or you don't want\nto allocate the resources (file descriptors, memory, etc.) for them right away?\nWell, in that case you can simply provide a callback that supplies the stream\nby calling a `next()` function:\n\n``` javascript\nvar CombinedStream = require('combined-stream');\nvar fs = require('fs');\n\nvar combinedStream = CombinedStream.create();\ncombinedStream.append(function(next) {\n next(fs.createReadStream('file1.txt'));\n});\ncombinedStream.append(function(next) {\n next(fs.createReadStream('file2.txt'));\n});\n\ncombinedStream.pipe(fs.createWriteStream('combined.txt'));\n```\n\n## API\n\n### CombinedStream.create([options])\n\nReturns a new combined stream object. Available options are:\n\n* `maxDataSize`\n* `pauseStreams`\n\nThe effect of those options is described below.\n\n### combinedStream.pauseStreams = `true`\n\nWhether to apply back pressure to the underlaying streams. If set to `false`,\nthe underlaying streams will never be paused. If set to `true`, the\nunderlaying streams will be paused right after being appended, as well as when\n`delayedStream.pipe()` wants to throttle.\n\n### combinedStream.maxDataSize = `2 * 1024 * 1024`\n\nThe maximum amount of bytes (or characters) to buffer for all source streams.\nIf this value is exceeded, `combinedStream` emits an `'error'` event.\n\n### combinedStream.dataSize = `0`\n\nThe amount of bytes (or characters) currently buffered by `combinedStream`.\n\n### combinedStream.append(stream)\n\nAppends the given `stream` to the combinedStream object. If `pauseStreams` is\nset to `true, this stream will also be paused right away.\n\n`streams` can also be a function that takes one parameter called `next`. `next`\nis a function that must be invoked in order to provide the `next` stream, see\nexample above.\n\nRegardless of how the `stream` is appended, combined-stream always attaches an\n`'error'` listener to it, so you don't have to do that manually.\n\nSpecial case: `stream` can also be a String or Buffer.\n\n### combinedStream.write(data)\n\nYou should not call this, `combinedStream` takes care of piping the appended\nstreams into itself for you.\n\n### combinedStream.resume()\n\nCauses `combinedStream` to start drain the streams it manages. The function is\nidempotent, and also emits a `'resume'` event each time which usually goes to\nthe stream that is currently being drained.\n\n### combinedStream.pause();\n\nIf `combinedStream.pauseStreams` is set to `false`, this does nothing.\nOtherwise a `'pause'` event is emitted, this goes to the stream that is\ncurrently being drained, so you can use it to apply back pressure.\n\n### combinedStream.end();\n\nSets `combinedStream.writable` to false, emits an `'end'` event, and removes\nall streams from the queue.\n\n### combinedStream.destroy();\n\nSame as `combinedStream.end()`, except it emits a `'close'` event instead of\n`'end'`.\n\n## License\n\ncombined-stream is licensed under the MIT license.\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/felixge/node-combined-stream/issues" + }, + "_id": "combined-stream@0.0.7", + "_shasum": "0137e657baa5a7541c57ac37ac5fc07d73b4dc1f", + "_resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-0.0.7.tgz", + "_from": "combined-stream@>=0.0.4 <0.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/package.json new file mode 100644 index 0000000..46ec26d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/form-data/package.json @@ -0,0 +1,48 @@ +{ + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "name": "form-data", + "description": "A module to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.", + "version": "0.2.0", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-form-data.git" + }, + "main": "./lib/form_data", + "scripts": { + "test": "node test/run.js" + }, + "engines": { + "node": ">= 0.8" + }, + "dependencies": { + "async": "~0.9.0", + "combined-stream": "~0.0.4", + "mime-types": "~2.0.3" + }, + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/felixge/node-form-data/master/License" + } + ], + "devDependencies": { + "fake": "~0.2.2", + "far": "~0.0.7", + "formidable": "~1.0.14", + "request": "~2.36.0" + }, + "readme": "# Form-Data [![Build Status](https://travis-ci.org/felixge/node-form-data.png?branch=master)](https://travis-ci.org/felixge/node-form-data) [![Dependency Status](https://gemnasium.com/felixge/node-form-data.png)](https://gemnasium.com/felixge/node-form-data)\n\nA module to create readable ```\"multipart/form-data\"``` streams. Can be used to submit forms and file uploads to other web applications.\n\nThe API of this module is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd].\n\n[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface\n[streams2-thing]: http://nodejs.org/api/stream.html#stream_compatibility_with_older_node_versions\n\n## Install\n\n```\nnpm install form-data\n```\n\n## Usage\n\nIn this example we are constructing a form with 3 fields that contain a string,\na buffer and a file stream.\n\n``` javascript\nvar FormData = require('form-data');\nvar fs = require('fs');\n\nvar form = new FormData();\nform.append('my_field', 'my value');\nform.append('my_buffer', new Buffer(10));\nform.append('my_file', fs.createReadStream('/foo/bar.jpg'));\n```\n\nAlso you can use http-response stream:\n\n``` javascript\nvar FormData = require('form-data');\nvar http = require('http');\n\nvar form = new FormData();\n\nhttp.request('http://nodejs.org/images/logo.png', function(response) {\n form.append('my_field', 'my value');\n form.append('my_buffer', new Buffer(10));\n form.append('my_logo', response);\n});\n```\n\nOr @mikeal's request stream:\n\n``` javascript\nvar FormData = require('form-data');\nvar request = require('request');\n\nvar form = new FormData();\n\nform.append('my_field', 'my value');\nform.append('my_buffer', new Buffer(10));\nform.append('my_logo', request('http://nodejs.org/images/logo.png'));\n```\n\nIn order to submit this form to a web application, call ```submit(url, [callback])``` method:\n\n``` javascript\nform.submit('http://example.org/', function(err, res) {\n // res – response object (http.IncomingMessage) //\n res.resume(); // for node-0.10.x\n});\n\n```\n\nFor more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods.\n\n### Alternative submission methods\n\nYou can use node's http client interface:\n\n``` javascript\nvar http = require('http');\n\nvar request = http.request({\n method: 'post',\n host: 'example.org',\n path: '/upload',\n headers: form.getHeaders()\n});\n\nform.pipe(request);\n\nrequest.on('response', function(res) {\n console.log(res.statusCode);\n});\n```\n\nOr if you would prefer the `'Content-Length'` header to be set for you:\n\n``` javascript\nform.submit('example.org/upload', function(err, res) {\n console.log(res.statusCode);\n});\n```\n\nTo use custom headers and pre-known length in parts:\n\n``` javascript\nvar CRLF = '\\r\\n';\nvar form = new FormData();\n\nvar options = {\n header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF,\n knownLength: 1\n};\n\nform.append('my_buffer', buffer, options);\n\nform.submit('http://example.com/', function(err, res) {\n if (err) throw err;\n console.log('Done');\n});\n```\n\nForm-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide \"file\"-related information manually:\n\n``` javascript\nsomeModule.stream(function(err, stdout, stderr) {\n if (err) throw err;\n\n var form = new FormData();\n\n form.append('file', stdout, {\n filename: 'unicycle.jpg',\n contentType: 'image/jpg',\n knownLength: 19806\n });\n\n form.submit('http://example.com/', function(err, res) {\n if (err) throw err;\n console.log('Done');\n });\n});\n```\n\nFor edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter:\n\n``` javascript\nform.submit({\n host: 'example.com',\n path: '/probably.php?extra=params',\n auth: 'username:password'\n}, function(err, res) {\n console.log(res.statusCode);\n});\n```\n\nIn case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`:\n\n``` javascript\nform.submit({\n host: 'example.com',\n path: '/surelynot.php',\n headers: {'x-test-header': 'test-header-value'}\n}, function(err, res) {\n console.log(res.statusCode);\n});\n```\n\n## Notes\n\n- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround.\n- If it feels like FormData hangs after submit and you're on ```node-0.10```, please check [Compatibility with Older Node Versions][streams2-thing]\n\n## TODO\n\n- Add new streams (0.10) support and try really hard not to break it for 0.8.x.\n\n## License\n\nForm-Data is licensed under the MIT license.\n", + "readmeFilename": "Readme.md", + "bugs": { + "url": "https://github.com/felixge/node-form-data/issues" + }, + "homepage": "https://github.com/felixge/node-form-data#readme", + "_id": "form-data@0.2.0", + "_shasum": "26f8bc26da6440e299cbdcfb69035c4f77a6e466", + "_resolved": "https://registry.npmjs.org/form-data/-/form-data-0.2.0.tgz", + "_from": "form-data@>=0.2.0 <0.3.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/LICENSE new file mode 100644 index 0000000..d527871 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Ahmad Nassri (https://www.ahmadnassri.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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/README.md new file mode 100644 index 0000000..4e580ab --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/README.md @@ -0,0 +1,362 @@ +# HAR Validator [![version][npm-version]][npm-url] [![License][npm-license]][license-url] + +Extremely fast HTTP Archive ([HAR](http://www.softwareishard.com/blog/har-12-spec/)) validator using JSON Schema. + +[![Build Status][travis-image]][travis-url] +[![Downloads][npm-downloads]][npm-url] +[![Code Climate][codeclimate-quality]][codeclimate-url] +[![Coverage Status][codeclimate-coverage]][codeclimate-url] +[![Dependencies][david-image]][david-url] + +## Install + +```shell +# to use in cli +npm install --global har-validator + +# to use as a module +npm install --save har-validator +``` + +## Usage + +``` + + Usage: har-validator [options] + + Options: + + -h, --help output usage information + -V, --version output the version number + -s, --schema [name] validate schema name (log, request, response, etc ...) + +``` + +###### Example + +```shell +har-validator har.json + +har-validator --schema request request.json +``` + +## API + +### Validate(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a full [HAR](http://www.softwareishard.com/blog/har-12-spec/) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var HAR = require('./har.json'); +var validate = require('har-validator'); + +validate(HAR, function (e, valid) { + if (e) console.log(e.errors) + + if (valid) console.log('horray!'); +}); +``` + +### Validate.log(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [log](http://www.softwareishard.com/blog/har-12-spec/#log) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.log(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.cache(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [cache](http://www.softwareishard.com/blog/har-12-spec/#cache) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.cache(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.cacheEntry(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a ["beforeRequest" or "afterRequest"](http://www.softwareishard.com/blog/har-12-spec/#cache) objects + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.cacheEntry(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.content(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [content](http://www.softwareishard.com/blog/har-12-spec/#content) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.content(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.cookie(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [cookie](http://www.softwareishard.com/blog/har-12-spec/#cookies) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.cookie(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.creator(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [creator](http://www.softwareishard.com/blog/har-12-spec/#creator) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.creator(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.entry(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + an [entry](http://www.softwareishard.com/blog/har-12-spec/#entries) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.entry(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.log(data [, callback]) + +alias of [`Validate(data [, callback])`](#validate-data-callback-) + +### Validate.page(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [page](http://www.softwareishard.com/blog/har-12-spec/#pages) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.page(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.pageTimings(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [pageTimings](http://www.softwareishard.com/blog/har-12-spec/#pageTimings) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.pageTimings(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.postData(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [postData](http://www.softwareishard.com/blog/har-12-spec/#postData) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.postData(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.record(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [record](http://www.softwareishard.com/blog/har-12-spec/#headers) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.record(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.request(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [request](http://www.softwareishard.com/blog/har-12-spec/#request) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.request(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.response(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [response](http://www.softwareishard.com/blog/har-12-spec/#response) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.cacheEntry(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +### Validate.timings(data [, callback]) + +Returns `true` or `false`. + +- **data**: `Object` *(Required)* + a [timings](http://www.softwareishard.com/blog/har-12-spec/#timings) object + +- **callback**: `Function` + gets two arguments (err, valid) + +```js +var validate = require('har-validator'); + +validate.timings(data, function (e, valid) { + if (e) console.log(e.errors) +}); +``` + +## Support + +Donations are welcome to help support the continuous development of this project. + +[![Gratipay][gratipay-image]][gratipay-url] +[![PayPal][paypal-image]][paypal-url] +[![Flattr][flattr-image]][flattr-url] +[![Bitcoin][bitcoin-image]][bitcoin-url] + +## License + +[MIT](LICENSE) © [Ahmad Nassri](https://www.ahmadnassri.com) + +[license-url]: https://github.com/ahmadnassri/har-validator/blob/master/LICENSE + +[travis-url]: https://travis-ci.org/ahmadnassri/har-validator +[travis-image]: https://img.shields.io/travis/ahmadnassri/har-validator.svg?style=flat-square + +[npm-url]: https://www.npmjs.com/package/har-validator +[npm-license]: https://img.shields.io/npm/l/har-validator.svg?style=flat-square +[npm-version]: https://img.shields.io/npm/v/har-validator.svg?style=flat-square +[npm-downloads]: https://img.shields.io/npm/dm/har-validator.svg?style=flat-square + +[codeclimate-url]: https://codeclimate.com/github/ahmadnassri/har-validator +[codeclimate-quality]: https://img.shields.io/codeclimate/github/ahmadnassri/har-validator.svg?style=flat-square +[codeclimate-coverage]: https://img.shields.io/codeclimate/coverage/github/ahmadnassri/har-validator.svg?style=flat-square + +[david-url]: https://david-dm.org/ahmadnassri/har-validator +[david-image]: https://img.shields.io/david/ahmadnassri/har-validator.svg?style=flat-square + +[gratipay-url]: https://www.gratipay.com/ahmadnassri/ +[gratipay-image]: https://img.shields.io/gratipay/ahmadnassri.svg?style=flat-square + +[paypal-url]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=UJ2B2BTK9VLRS&on0=project&os0=har-validator +[paypal-image]: http://img.shields.io/badge/paypal-donate-green.svg?style=flat-square + +[flattr-url]: https://flattr.com/submit/auto?user_id=ahmadnassri&url=https://github.com/ahmadnassri/har-validator&title=har-validator&language=&tags=github&category=software +[flattr-image]: http://img.shields.io/badge/flattr-donate-green.svg?style=flat-square + +[bitcoin-image]: http://img.shields.io/badge/bitcoin-1Nb46sZRVG3or7pNaDjthcGJpWhvoPpCxy-green.svg?style=flat-square +[bitcoin-url]: https://www.coinbase.com/checkouts/ae383ae6bb931a2fa5ad11cec115191e?name=har-validator diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/bin/har-validator b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/bin/har-validator new file mode 100755 index 0000000..ab1db25 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/bin/har-validator @@ -0,0 +1,45 @@ +#!/usr/bin/env node + +'use strict' + +var Promise = require('bluebird') + +var chalk = require('chalk') +var cmd = require('commander') +var fs = Promise.promisifyAll(require('fs')) +var path = require('path') +var pkg = require('../package.json') +var validate = Promise.promisifyAll(require('..')) + +cmd + .version(pkg.version) + .usage('[options] ') + .option('-s, --schema [name]', 'validate schema name (log, request, response, etc ...)') + .parse(process.argv) + +if (!cmd.args.length) { + cmd.help() +} + +if (!cmd.schema) { + cmd.schema = 'har' +} + +cmd.args.map(function (fileName) { + var file = chalk.yellow.italic(path.basename(fileName)) + + fs.readFileAsync(fileName) + .then(JSON.parse) + .then(validate[cmd.schema + 'Async']) + .then(function () { + console.log('%s [%s] is valid', chalk.green('✓'), file) + }) + .catch(SyntaxError, function (e) { + console.error('%s [%s] failed to read JSON: %s', chalk.red('✖'), file, chalk.red(e.message)) + }) + .catch(function (e) { + e.errors.map(function (err) { + console.error('%s [%s] failed validation: (%s: %s) %s', chalk.red('✖'), file, chalk.cyan.italic(err.field), chalk.magenta.italic(err.value), chalk.red(err.message)) + }) + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..a3966cf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/README.md new file mode 100644 index 0000000..dad5dcf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/README.md @@ -0,0 +1,676 @@ + + 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) + + +# 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) +- 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 + +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 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 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. + +# 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/changelog.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..aa145dc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/changelog.md @@ -0,0 +1,1653 @@ +## 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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..a529187 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5102 @@ +/* @preserve + * 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. + * + */ +/** + * bluebird build version 2.9.27 + * 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; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + 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"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!true) { +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) { + 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._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(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(); +}; + +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,"events":39}],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) { + this._setBoundTo(thisArg); + 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(); + 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._setBoundTo(thisArg); + 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); + + 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; +}; +}; + +},{}],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) { + 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._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 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 (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && 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 wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, 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._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) { + 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 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(); + this._callback = 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._boundTo; + 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._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 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 noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +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", + "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\ + 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 + ); +}; +} + +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; + } + 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; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + 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 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; + this._callback = 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; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + 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; + if (typeof message !== "string") { + message = "operation timed out"; + } + var 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"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } 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 = fn.apply(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 { + return tryCatchTarget.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; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + 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) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + 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)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +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, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + 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); +})(); +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) +}); ;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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..bc182ff --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * 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. + * + */ +/** + * bluebird build version 2.9.27 + * 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){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.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(){},s=function(){throw void 0},a=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 void 0===t?this.then(o):i&&n(t)?this._then(a(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 void 0===t?this.then(s):i&&n(t)?this._then(a(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=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?(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)}:i;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(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 C.apply(this,arguments)}catch(t){return F.e=t,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);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;i10||t[0]>0}();try{throw new Error}catch(O){S.lastLineError=O}e.exports=S},{"./es5.js":14}],39:[function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(t){return"function"==typeof t}function i(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!i(t)||0>t||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 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/any.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/assert.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/assert.js new file mode 100644 index 0000000..a98955c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/async.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/async.js new file mode 100644 index 0000000..3b5f828 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/async.js @@ -0,0 +1,204 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule.js"); +var Queue = require("./queue.js"); +var util = require("./util.js"); + +function Async() { + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; +} + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.enableTrampoline = function() { + if (!this._trampolineEnabled) { + this._trampolineEnabled = true; + this._schedule = function(fn) { + setTimeout(fn, 0); + }; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._normalQueue.length() > 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + 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); + }, 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"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!false) { +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) { + 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._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(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(); +}; + +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; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bind.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bind.js new file mode 100644 index 0000000..d6f6da2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bind.js @@ -0,0 +1,73 @@ +"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) { + this._setBoundTo(thisArg); + 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(); + 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._setBoundTo(thisArg); + 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); + + 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; +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bluebird.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/bluebird.js new file mode 100644 index 0000000..ed6226e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/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.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/call_get.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/call_get.js new file mode 100644 index 0000000..62c166d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/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.js"); +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/cancel.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/cancel.js new file mode 100644 index 0000000..9eb40b6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/cancel.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = function(Promise) { +var errors = require("./errors.js"); +var async = require("./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; +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/captured_trace.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/captured_trace.js new file mode 100644 index 0000000..6fda9e8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/captured_trace.js @@ -0,0 +1,492 @@ +"use strict"; +module.exports = function() { +var async = require("./async.js"); +var util = require("./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) { + 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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/catch_filter.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/catch_filter.js new file mode 100644 index 0000000..040f057 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/catch_filter.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util.js"); +var errors = require("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = require("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = 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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/context.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/context.js new file mode 100644 index 0000000..ccd7702 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/context.js @@ -0,0 +1,38 @@ +"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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/debuggability.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/debuggability.js new file mode 100644 index 0000000..5ac1767 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/debuggability.js @@ -0,0 +1,147 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = require("./async.js"); +var Warning = require("./errors.js").Warning; +var util = require("./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; +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/direct_resolve.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/direct_resolve.js new file mode 100644 index 0000000..47a9ce9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/direct_resolve.js @@ -0,0 +1,62 @@ +"use strict"; +var util = require("./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 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 (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/each.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/each.js new file mode 100644 index 0000000..a37e22c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/each.js @@ -0,0 +1,12 @@ +"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); +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/errors.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/errors.js new file mode 100644 index 0000000..c334bb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/errors.js @@ -0,0 +1,111 @@ +"use strict"; +var es5 = require("./es5.js"); +var Objectfreeze = es5.freeze; +var util = require("./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 +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/es5.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/filter.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/finally.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/finally.js new file mode 100644 index 0000000..ed84a2a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/finally.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = require("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, 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._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) { + 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); +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/generators.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/generators.js new file mode 100644 index 0000000..4c0568d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/generators.js @@ -0,0 +1,136 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = require("./errors.js"); +var TypeError = errors.TypeError; +var util = require("./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; +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/join.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/join.js new file mode 100644 index 0000000..cf33eb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/join.js @@ -0,0 +1,107 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util.js"); +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 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 (!false) { + 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; +}; + +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/map.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/map.js new file mode 100644 index 0000000..66a5b17 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/map.js @@ -0,0 +1,131 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./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(); + this._callback = 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._boundTo; + 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(); +}; + + +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/method.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/method.js new file mode 100644 index 0000000..3d3eeb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/method.js @@ -0,0 +1,44 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./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); + } +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/nodeify.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/nodeify.js new file mode 100644 index 0000000..f305b93 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util.js"); +var async = require("./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; +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/progress.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/progress.js new file mode 100644 index 0000000..2e3e95e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/progress.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = require("./util.js"); +var async = require("./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); + } + } +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise.js new file mode 100644 index 0000000..f80d247 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise.js @@ -0,0 +1,700 @@ +"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 = require("./util.js"); +var async = require("./async.js"); +var errors = require("./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 = require("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = require("./captured_trace.js")(); +var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + require("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = require("./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; +require("./progress.js")(Promise, PromiseArray); +require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +require("./direct_resolve.js")(Promise); +require("./synchronous_inspection.js")(Promise); +require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./cancel.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +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); +require('./settle.js')(Promise, PromiseArray); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./promisify.js')(Promise, INTERNAL); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./timers.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._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; + +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_array.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_array.js new file mode 100644 index 0000000..6dac866 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_array.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = require("./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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_resolver.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_resolver.js new file mode 100644 index 0000000..b180a32 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promise_resolver.js @@ -0,0 +1,123 @@ +"use strict"; +var util = require("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = require("./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; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promisify.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promisify.js new file mode 100644 index 0000000..0355344 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/promisify.js @@ -0,0 +1,291 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util.js"); +var nodebackForPromise = require("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var 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) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +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 (!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) { + 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", + "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\ + 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 + ); +}; +} + +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; + } + 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; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + 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); +}; +}; + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/props.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/props.js new file mode 100644 index 0000000..d6f9e64 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/props.js @@ -0,0 +1,79 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var isObject = util.isObject; +var es5 = require("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + 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); +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/queue.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/race.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/race.js new file mode 100644 index 0000000..30e7bb0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/race.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = require("./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); +}; + +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/reduce.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/reduce.js new file mode 100644 index 0000000..3192220 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/reduce.js @@ -0,0 +1,146 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./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; + this._callback = 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(); +}; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/some.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/some.js new file mode 100644 index 0000000..f3968cf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/some.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util.js"); +var RangeError = require("./errors.js").RangeError; +var AggregateError = require("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + 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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/synchronous_inspection.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/synchronous_inspection.js new file mode 100644 index 0000000..7aac149 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/synchronous_inspection.js @@ -0,0 +1,94 @@ +"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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/thenables.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/thenables.js new file mode 100644 index 0000000..c858f86 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/thenables.js @@ -0,0 +1,89 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./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; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + 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; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/timers.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/timers.js new file mode 100644 index 0000000..ecf1b57 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/timers.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var 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); +}; + +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/using.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/using.js new file mode 100644 index 0000000..4038711 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/using.js @@ -0,0 +1,202 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = require("./errors.js").TypeError; + var inherits = require("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + 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"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } 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 = fn.apply(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(); + }; + +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/util.js new file mode 100644 index 0000000..ab67f87 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/js/main/util.js @@ -0,0 +1,284 @@ +"use strict"; +var es5 = require("./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 { + return tryCatchTarget.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; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + 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) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + 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)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +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, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + 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); +})(); +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/package.json new file mode 100644 index 0000000..2bb86a9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/bluebird/package.json @@ -0,0 +1,98 @@ +{ + "name": "bluebird", + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "version": "2.9.27", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "scripts": { + "lint": "node scripts/jshint.js", + "test": "node tools/test.js", + "istanbul": "istanbul", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify" + }, + "homepage": "https://github.com/petkaantonov/bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "license": "MIT", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "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", + "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", + "kefir": "^2.4.1" + }, + "main": "./js/main/bluebird.js", + "browser": "./js/browser/bluebird.js", + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "LICENSE", + "zalgo.js" + ], + "gitHead": "634af0e27ff4faab62c6c5bfd105527abcf8b06e", + "_id": "bluebird@2.9.27", + "_shasum": "8eab7da1e866998f9f71c209b9875f9949a7adca", + "_from": "bluebird@>=2.9.26 <3.0.0", + "_npmVersion": "2.7.1", + "_nodeVersion": "1.6.2", + "_npmUser": { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + }, + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "dist": { + "shasum": "8eab7da1e866998f9f71c209b9875f9949a7adca", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.9.27.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.27.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/History.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/History.md new file mode 100644 index 0000000..7b8b2c4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/History.md @@ -0,0 +1,256 @@ + +2.8.1 / 2015-04-22 +================== + + * Back out `support multiline description` Close #396 #397 + + + +2.8.0 / 2015-04-07 +================== + + * Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee + * Fix bug in Git-style sub-commands #372 @zhiyelee + * Allow commands to be hidden from help #383 @tonylukasavage + * When git-style sub-commands are in use, yet none are called, display help #382 @claylo + * Add ability to specify arguments syntax for top-level command #258 @rrthomas + * Support multiline descriptions #208 @zxqfox + +2.7.1 / 2015-03-11 +================== + + * Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. + +2.7.0 / 2015-03-09 +================== + + * Fix git-style bug when installed globally. Close #335 #349 @zhiyelee + * Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage + * Add support for camelCase on `opts()`. Close #353 @nkzawa + * Add node.js 0.12 and io.js to travis.yml + * Allow RegEx options. #337 @palanik + * Fixes exit code when sub-command failing. Close #260 #332 @pirelenito + * git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee + +2.6.0 / 2014-12-30 +================== + + * added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee + * Add application description to the help msg. Close #112 @dalssoft + +2.5.1 / 2014-12-15 +================== + + * fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee + +2.5.0 / 2014-10-24 +================== + + * add support for variadic arguments. Closes #277 @whitlockjc + +2.4.0 / 2014-10-17 +================== + + * fixed a bug on executing the coercion function of subcommands option. Closes #270 + * added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage + * added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage + * fixed a bug on subcommand name. Closes #248 @jonathandelgado + * fixed function normalize doesn’t honor option terminator. Closes #216 @abbr + +2.3.0 / 2014-07-16 +================== + + * add command alias'. Closes PR #210 + * fix: Typos. Closes #99 + * fix: Unused fs module. Closes #217 + +2.2.0 / 2014-03-29 +================== + + * add passing of previous option value + * fix: support subcommands on windows. Closes #142 + * Now the defaultValue passed as the second argument of the coercion function. + +2.1.0 / 2013-11-21 +================== + + * add: allow cflag style option params, unit test, fixes #174 + +2.0.0 / 2013-07-18 +================== + + * remove input methods (.prompt, .confirm, etc) + +1.3.2 / 2013-07-18 +================== + + * add support for sub-commands to co-exist with the original command + +1.3.1 / 2013-07-18 +================== + + * add quick .runningCommand hack so you can opt-out of other logic when running a sub command + +1.3.0 / 2013-07-09 +================== + + * add EACCES error handling + * fix sub-command --help + +1.2.0 / 2013-06-13 +================== + + * allow "-" hyphen as an option argument + * support for RegExp coercion + +1.1.1 / 2012-11-20 +================== + + * add more sub-command padding + * fix .usage() when args are present. Closes #106 + +1.1.0 / 2012-11-16 +================== + + * add git-style executable subcommand support. Closes #94 + +1.0.5 / 2012-10-09 +================== + + * fix `--name` clobbering. Closes #92 + * fix examples/help. Closes #89 + +1.0.4 / 2012-09-03 +================== + + * add `outputHelp()` method. + +1.0.3 / 2012-08-30 +================== + + * remove invalid .version() defaulting + +1.0.2 / 2012-08-24 +================== + + * add `--foo=bar` support [arv] + * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus] + +1.0.1 / 2012-08-03 +================== + + * fix issue #56 + * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) + +1.0.0 / 2012-07-05 +================== + + * add support for optional option descriptions + * add defaulting of `.version()` to package.json's version + +0.6.1 / 2012-06-01 +================== + + * Added: append (yes or no) on confirmation + * Added: allow node.js v0.7.x + +0.6.0 / 2012-04-10 +================== + + * Added `.prompt(obj, callback)` support. Closes #49 + * Added default support to .choose(). Closes #41 + * Fixed the choice example + +0.5.1 / 2011-12-20 +================== + + * Fixed `password()` for recent nodes. Closes #36 + +0.5.0 / 2011-12-04 +================== + + * Added sub-command option support [itay] + +0.4.3 / 2011-12-04 +================== + + * Fixed custom help ordering. Closes #32 + +0.4.2 / 2011-11-24 +================== + + * Added travis support + * Fixed: line-buffered input automatically trimmed. Closes #31 + +0.4.1 / 2011-11-18 +================== + + * Removed listening for "close" on --help + +0.4.0 / 2011-11-15 +================== + + * Added support for `--`. Closes #24 + +0.3.3 / 2011-11-14 +================== + + * Fixed: wait for close event when writing help info [Jerry Hamlet] + +0.3.2 / 2011-11-01 +================== + + * Fixed long flag definitions with values [felixge] + +0.3.1 / 2011-10-31 +================== + + * Changed `--version` short flag to `-V` from `-v` + * Changed `.version()` so it's configurable [felixge] + +0.3.0 / 2011-10-31 +================== + + * Added support for long flags only. Closes #18 + +0.2.1 / 2011-10-24 +================== + + * "node": ">= 0.4.x < 0.7.0". Closes #20 + +0.2.0 / 2011-09-26 +================== + + * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] + +0.1.0 / 2011-08-24 +================== + + * Added support for custom `--help` output + +0.0.5 / 2011-08-18 +================== + + * Changed: when the user enters nothing prompt for password again + * Fixed issue with passwords beginning with numbers [NuckChorris] + +0.0.4 / 2011-08-15 +================== + + * Fixed `Commander#args` + +0.0.3 / 2011-08-15 +================== + + * Added default option value support + +0.0.2 / 2011-08-15 +================== + + * Added mask support to `Command#password(str[, mask], fn)` + * Added `Command#password(str, fn)` + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/LICENSE new file mode 100644 index 0000000..10f997a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/Readme.md new file mode 100644 index 0000000..af58e22 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/Readme.md @@ -0,0 +1,342 @@ +# Commander.js + + +[![Build Status](https://api.travis-ci.org/tj/commander.js.svg)](http://travis-ci.org/tj/commander.js) +[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://www.npmjs.org/package/commander) +[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/tj/commander). + [API documentation](http://tj.github.com/commander.js/) + + +## Installation + + $ npm install commander + +## Option parsing + + Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.0.1') + .option('-p, --peppers', 'Add peppers') + .option('-P, --pineapple', 'Add pineapple') + .option('-b, --bbq-sauce', 'Add bbq sauce') + .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') + .parse(process.argv); + +console.log('you ordered a pizza with:'); +if (program.peppers) console.log(' - peppers'); +if (program.pineapple) console.log(' - pineapple'); +if (program.bbqSauce) console.log(' - bbq'); +console.log(' - %s cheese', program.cheese); +``` + + Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. + + +## Coercion + +```js +function range(val) { + return val.split('..').map(Number); +} + +function list(val) { + return val.split(','); +} + +function collect(val, memo) { + memo.push(val); + return memo; +} + +function increaseVerbosity(v, total) { + return total + 1; +} + +program + .version('0.0.1') + .usage('[options] ') + .option('-i, --integer ', 'An integer argument', parseInt) + .option('-f, --float ', 'A float argument', parseFloat) + .option('-r, --range ..', 'A range', range) + .option('-l, --list ', 'A list', list) + .option('-o, --optional [value]', 'An optional value') + .option('-c, --collect [value]', 'A repeatable value', collect, []) + .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) + .parse(process.argv); + +console.log(' int: %j', program.integer); +console.log(' float: %j', program.float); +console.log(' optional: %j', program.optional); +program.range = program.range || []; +console.log(' range: %j..%j', program.range[0], program.range[1]); +console.log(' list: %j', program.list); +console.log(' collect: %j', program.collect); +console.log(' verbosity: %j', program.verbose); +console.log(' args: %j', program.args); +``` + +## Regular Expression +```js +program + .version('0.0.1') + .option('-s --size ', 'Pizza size', /^(large|medium|small)$/i, 'medium') + .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i) + .parse(process.argv); + +console.log(' size: %j', program.size); +console.log(' drink: %j', program.drink); +``` + +## Variadic arguments + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to + append `...` to the argument name. Here is an example: + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.0.1') + .command('rmdir [otherDirs...]') + .action(function (dir, otherDirs) { + console.log('rmdir %s', dir); + if (otherDirs) { + otherDirs.forEach(function (oDir) { + console.log('rmdir %s', oDir); + }); + } + }); + +program.parse(process.argv); +``` + + An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed + to your action as demonstrated above. + +## Specify the argument syntax + +```js +#!/usr/bin/env node + +var program = require('../'); + +program + .version('0.0.1') + .arguments(' [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; + }); + +program.parse(process.argv); + +if (typeof cmdValue === 'undefined') { + console.error('no command given!'); + process.exit(1); +} +console.log('command:', cmdValue); +console.log('environment:', envValue || "no environment given"); +``` + +## Git-style sub-commands + +```js +// file: ./examples/pm +var program = require('..'); + +program + .version('0.0.1') + .command('install [name]', 'install one or more packages') + .command('search [query]', 'search with optional query') + .command('list', 'list packages installed') + .parse(process.argv); +``` + +When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. +The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`. + +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. + +### `--harmony` + +You can enable `--harmony` option in two ways: +* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern. +* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process. + +## Automated --help + + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: + +``` + $ ./examples/pizza --help + + Usage: pizza [options] + + An application for pizzas ordering + + Options: + + -h, --help output usage information + -V, --version output the version number + -p, --peppers Add peppers + -P, --pineapple Add pineapple + -b, --bbq Add bbq sauce + -c, --cheese Add the specified type of cheese [marble] + -C, --no-cheese You do not want any cheese + +``` + +## Custom help + + You can display arbitrary `-h, --help` information + by listening for "--help". Commander will automatically + exit once you are done so that the remainder of your program + does not execute causing undesired behaviours, for example + in the following executable "stuff" will not output when + `--help` is used. + +```js +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); + +program + .version('0.0.1') + .option('-f, --foo', 'enable some foo') + .option('-b, --bar', 'enable some bar') + .option('-B, --baz', 'enable some baz'); + +// must be before .parse() since +// node's emit() is immediate + +program.on('--help', function(){ + console.log(' Examples:'); + console.log(''); + console.log(' $ custom-help --help'); + console.log(' $ custom-help -h'); + console.log(''); +}); + +program.parse(process.argv); + +console.log('stuff'); +``` + +Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run: + +``` + +Usage: custom-help [options] + +Options: + + -h, --help output usage information + -V, --version output the version number + -f, --foo enable some foo + -b, --bar enable some bar + -B, --baz enable some baz + +Examples: + + $ custom-help --help + $ custom-help -h + +``` + +## .outputHelp() + +Output help information without exiting. + +If you want to display help by default (e.g. if no command was provided), you can use something like: + +```js +var program = require('commander'); + +program + .version('0.0.1') + .command('getstream [url]', 'get stream URL') + .parse(process.argv); + + if (!process.argv.slice(2).length) { + program.outputHelp(); + } +``` + +## .help() + + Output help information and exit immediately. + +## Examples + +```js +var program = require('commander'); + +program + .version('0.0.1') + .option('-C, --chdir ', 'change the working directory') + .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + .option('-T, --no-tests', 'ignore test hook') + +program + .command('setup [env]') + .description('run setup commands for all envs') + .option("-s, --setup_mode [mode]", "Which setup mode to use") + .action(function(env, options){ + var mode = options.setup_mode || "normal"; + env = env || 'all'; + console.log('setup for %s env(s) with %s mode', env, mode); + }); + +program + .command('exec ') + .alias('ex') + .description('execute the given remote cmd') + .option("-e, --exec_mode ", "Which exec mode to use") + .action(function(cmd, options){ + console.log('exec "%s" using %s mode', cmd, options.exec_mode); + }).on('--help', function() { + console.log(' Examples:'); + console.log(); + console.log(' $ deploy exec sequential'); + console.log(' $ deploy exec async'); + console.log(); + }); + +program + .command('*') + .action(function(env){ + console.log('deploying "%s"', env); + }); + +program.parse(process.argv); +``` + +More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## License + +MIT + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/index.js new file mode 100644 index 0000000..8776965 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/index.js @@ -0,0 +1,1103 @@ + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var spawn = require('child_process').spawn; +var readlink = require('graceful-readlink').readlinkSync; +var path = require('path'); +var dirname = path.dirname; +var basename = path.basename; +var fs = require('fs'); + +/** + * Expose the root command. + */ + +exports = module.exports = new Command(); + +/** + * Expose `Command`. + */ + +exports.Command = Command; + +/** + * Expose `Option`. + */ + +exports.Option = Option; + +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ + +function Option(flags, description) { + this.flags = flags; + this.required = ~flags.indexOf('<'); + this.optional = ~flags.indexOf('['); + this.bool = !~flags.indexOf('-no-'); + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} + +/** + * Return option name. + * + * @return {String} + * @api private + */ + +Option.prototype.name = function() { + return this.long + .replace('--', '') + .replace('no-', ''); +}; + +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ + +Option.prototype.is = function(arg) { + return arg == this.short || arg == this.long; +}; + +/** + * Initialize a new `Command`. + * + * @param {String} name + * @api public + */ + +function Command(name) { + this.commands = []; + this.options = []; + this._execs = []; + this._allowUnknownOption = false; + this._args = []; + this._name = name; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +Command.prototype.__proto__ = EventEmitter.prototype; + +/** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * Examples: + * + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {String} name + * @param {String} [desc] for git-style sub-commands + * @return {Command} the new command + * @api public + */ + +Command.prototype.command = function(name, desc, opts) { + opts = opts || {}; + var args = name.split(/ +/); + var cmd = new Command(args.shift()); + + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs[cmd._name] = true; + } + + cmd._noHelp = !!opts.noHelp; + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; +}; + +/** + * Define argument syntax for the top-level command. + * + * @api public + */ + +Command.prototype.arguments = function (desc) { + return this.parseExpectedArgs(desc.split(/ +/)); +} + +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ + +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; + +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; + + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } + + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + self._args.push(argDetails); + } + }); + return this; +}; + +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ + +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; + + var parsed = self.parseOptions(unknown); + + // Output help if necessary + outputHelpIfNecessary(self, parsed.unknown); + + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } + + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); + + self._args.forEach(function(arg, i) { + if (arg.required && null == args[i]) { + self.missingArgument(arg.name); + } else if (arg.variadic) { + if (i !== self._args.length - 1) { + self.variadicArgNotLast(arg.name); + } + + args[i] = args.splice(i); + } + }); + + // Always append ourselves to the end of the arguments, + // to make sure we match the number of arguments the user + // expects + if (self._args.length) { + args[self._args.length] = self; + } else { + args.push(self); + } + + fn.apply(self, args); + }; + var parent = this.parent || this; + var name = parent === this ? '*' : this._name; + parent.on(name, listener); + if (this._alias) parent.on(this._alias, listener); + return this; +}; + +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|Mixed} fn or default + * @param {Mixed} defaultValue + * @return {Command} for chaining + * @api public + */ + +Command.prototype.option = function(flags, description, fn, defaultValue) { + var self = this + , option = new Option(flags, description) + , oname = option.name() + , name = camelcase(oname); + + // default as 3rd arg + if (typeof fn != 'function') { + if (fn instanceof RegExp) { + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; + } + } + else { + defaultValue = fn; + fn = null; + } + } + + // preassign default value only for --no-*, [optional], or + if (false == option.bool || option.optional || option.required) { + // when --no-* we make sure default is true + if (false == option.bool) defaultValue = true; + // preassign only if we have a default + if (undefined !== defaultValue) self[name] = defaultValue; + } + + // register the option + this.options.push(option); + + // when it's passed assign the value + // and conditionally invoke the callback + this.on(oname, function(val) { + // coercion + if (null !== val && fn) val = fn(val, undefined === self[name] + ? defaultValue + : self[name]); + + // unassigned or bool + if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { + // if no value, bool true, and we have a default, then use it! + if (null == val) { + self[name] = option.bool + ? defaultValue || true + : false; + } else { + self[name] = val; + } + } else if (null !== val) { + // reassign + self[name] = val; + } + }); + + return this; +}; + +/** + * Allow unknown options on the command line. + * + * @param {Boolean} arg if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ +Command.prototype.allowUnknownOption = function(arg) { + this._allowUnknownOption = arguments.length === 0 || arg; + return this; +}; + +/** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ + +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); + + // store raw args + this.rawArgs = argv; + + // guess name + this._name = this._name || basename(argv[1], '.js'); + + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3) { + // this user needs help + argv.push('--help'); + } + + // process argv + var parsed = this.parseOptions(this.normalize(argv.slice(2))); + var args = this.args = parsed.args; + + var result = this.parseArgs(this.args, parsed.unknown); + + // executable sub-commands + var name = result.args[0]; + if (this._execs[name] && typeof this._execs[name] != "function") { + return this.executeSubCommand(argv, args, parsed.unknown); + } + + return result; +}; + +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @api private + */ + +Command.prototype.executeSubCommand = function(argv, args, unknown) { + args = args.concat(unknown); + + if (!args.length) this.help(); + if ('help' == args[0] && 1 == args.length) this.help(); + + // --help + if ('help' == args[0]) { + args[0] = args[1]; + args[1] = '--help'; + } + + // executable + var f = argv[1]; + // name of the subcommand, link `pm-install` + var bin = basename(f, '.js') + '-' + args[0]; + + + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir + , link = readlink(f); + + // when symbolink is relative path + if (link !== f && link.charAt(0) !== '/') { + link = path.join(dirname(f), link) + } + baseDir = dirname(link); + + // prefer local `./` to bin in the $PATH + var localBin = path.join(baseDir, bin); + + // whether bin file is a js script with explicit `.js` extension + var isExplicitJS = false; + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin)) { + bin = localBin; + } + + args = args.slice(1); + + var proc; + if (process.platform !== 'win32') { + if (isExplicitJS) { + args.unshift(localBin); + // add executable arguments to spawn + args = (process.execArgv || []).concat(args); + + proc = spawn('node', args, { stdio: 'inherit', customFds: [0, 1, 2] }); + } else { + proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); + } + } else { + args.unshift(localBin); + proc = spawn(process.execPath, args, { stdio: 'inherit'}); + } + + proc.on('close', process.exit.bind(process)); + proc.on('error', function(err) { + if (err.code == "ENOENT") { + console.error('\n %s(1) does not exist, try --help\n', bin); + } else if (err.code == "EACCES") { + console.error('\n %s(1) not executable. try chmod or run with root\n', bin); + } + process.exit(1); + }); + + this.runningCommand = proc; +}; + +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ + +Command.prototype.normalize = function(args) { + var ret = [] + , arg + , lastOpt + , index; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i-1]); + } + + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } + } + + return ret; +}; + +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ + +Command.prototype.parseArgs = function(args, unknown) { + var name; + + if (args.length) { + name = args[0]; + if (this.listeners(name).length) { + this.emit(args.shift(), args, unknown); + } else { + this.emit('*', args); + } + } else { + outputHelpIfNecessary(this, unknown); + + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0) { + this.unknownOption(unknown[0]); + } + } + + return this; +}; + +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ + +Command.prototype.optionFor = function(arg) { + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } + } +}; + +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {Array} + * @api public + */ + +Command.prototype.parseOptions = function(argv) { + var args = [] + , len = argv.length + , literal + , option + , arg; + + var unknownOptions = []; + + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + + // literal args after -- + if ('--' == arg) { + literal = true; + continue; + } + + if (literal) { + args.push(arg); + continue; + } + + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (null == arg) return this.optionMissingArgument(option); + this.emit(option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i+1]; + if (null == arg || ('-' == arg[0] && '-' != arg)) { + arg = null; + } else { + ++i; + } + this.emit(option.name(), arg); + // bool + } else { + this.emit(option.name()); + } + continue; + } + + // looks like an option + if (arg.length > 1 && '-' == arg[0]) { + unknownOptions.push(arg); + + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if (argv[i+1] && '-' != argv[i+1][0]) { + unknownOptions.push(argv[++i]); + } + continue; + } + + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; + +/** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ +Command.prototype.opts = function() { + var result = {} + , len = this.options.length; + + for (var i = 0 ; i < len; i++) { + var key = camelcase(this.options[i].name()); + result[key] = key === 'version' ? this._version : this[key]; + } + return result; +}; + +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ + +Command.prototype.missingArgument = function(name) { + console.error(); + console.error(" error: missing required argument `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {String} option + * @param {String} flag + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag) { + console.error(); + if (flag) { + console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); + } else { + console.error(" error: option `%s' argument missing", option.flags); + } + console.error(); + process.exit(1); +}; + +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ + +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + console.error(); + console.error(" error: unknown option `%s'", flag); + console.error(); + process.exit(1); +}; + +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ + +Command.prototype.variadicArgNotLast = function(name) { + console.error(); + console.error(" error: variadic arguments must be last `%s'", name); + console.error(); + process.exit(1); +}; + +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {String} str + * @param {String} flags + * @return {Command} for chaining + * @api public + */ + +Command.prototype.version = function(str, flags) { + if (0 == arguments.length) return this._version; + this._version = str; + flags = flags || '-V, --version'; + this.option(flags, 'output the version number'); + this.on('version', function() { + process.stdout.write(str + '\n'); + process.exit(0); + }); + return this; +}; + +/** + * Set the description to `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.description = function(str) { + if (0 == arguments.length) return this._description; + this._description = str; + return this; +}; + +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ + +Command.prototype.alias = function(alias) { + if (0 == arguments.length) return this._alias; + this._alias = alias; + return this; +}; + +/** + * Set / get the command usage `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ + +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); + + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); + + if (0 == arguments.length) return this._usage || usage; + this._usage = str; + + return this; +}; + +/** + * Get the name of the command + * + * @param {String} name + * @return {String|Command} + * @api public + */ + +Command.prototype.name = function() { + return this._name; +}; + +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ + +Command.prototype.largestOptionLength = function() { + return this.options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; + +/** + * Return help for options. + * + * @return {String} + * @api private + */ + +Command.prototype.optionHelp = function() { + var width = this.largestOptionLength(); + + // Prepend the help information + return [pad('-h, --help', width) + ' ' + 'output usage information'] + .concat(this.options.map(function(option) { + return pad(option.flags, width) + ' ' + option.description; + })) + .join('\n'); +}; + +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; + + var commands = this.commands.filter(function(cmd) { + return !cmd._noHelp; + }).map(function(cmd) { + var args = cmd._args.map(function(arg) { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._alias + ? '|' + cmd._alias + : '') + + (cmd.options.length + ? ' [options]' + : '') + + ' ' + args + , cmd.description() + ]; + }); + + var width = commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); + + return [ + '' + , ' Commands:' + , '' + , commands.map(function(cmd) { + return pad(cmd[0], width) + ' ' + cmd[1]; + }).join('\n').replace(/^/gm, ' ') + , '' + ].join('\n'); +}; + +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ + +Command.prototype.helpInformation = function() { + var desc = []; + if (this._description) { + desc = [ + ' ' + this._description + , '' + ]; + } + + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var usage = [ + '' + ,' Usage: ' + cmdName + ' ' + this.usage() + , '' + ]; + + var cmds = []; + var commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; + + var options = [ + ' Options:' + , '' + , '' + this.optionHelp().replace(/^/gm, ' ') + , '' + , '' + ]; + + return usage + .concat(cmds) + .concat(desc) + .concat(options) + .join('\n'); +}; + +/** + * Output help information for this command + * + * @api public + */ + +Command.prototype.outputHelp = function() { + process.stdout.write(this.helpInformation()); + this.emit('--help'); +}; + +/** + * Output help information and exit. + * + * @api public + */ + +Command.prototype.help = function() { + this.outputHelp(); + process.exit(); +}; + +/** + * Camel-case the given `flag` + * + * @param {String} flag + * @return {String} + * @api private + */ + +function camelcase(flag) { + return flag.split('-').reduce(function(str, word) { + return str + word[0].toUpperCase() + word.slice(1); + }); +} + +/** + * Pad `str` to `width`. + * + * @param {String} str + * @param {Number} width + * @return {String} + * @api private + */ + +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); +} + +/** + * Output help information if necessary + * + * @param {Command} command to output help for + * @param {Array} array of options to search for -h or --help + * @api private + */ + +function outputHelpIfNecessary(cmd, options) { + options = options || []; + for (var i = 0; i < options.length; i++) { + if (options[i] == '--help' || options[i] == '-h') { + cmd.outputHelp(); + process.exit(0); + } + } +} + +/** + * Takes an argument an returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {String} + * @api private + */ + +function humanReadableArgName(arg) { + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']' +} + +// for versions before node v0.8 when there weren't `fs.existsSync` +function exists(file) { + try { + if (fs.statSync(file).isFile()) { + return true; + } + } catch (e) { + return false; + } +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.npmignore new file mode 100644 index 0000000..3ac7d16 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.npmignore @@ -0,0 +1,3 @@ +.idea/ +.DS_Store +node_modules/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.travis.yml new file mode 100644 index 0000000..baf9be7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "io.js" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/LICENSE new file mode 100644 index 0000000..d1f842f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Zhiye Li + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/README.md new file mode 100644 index 0000000..fc63b50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/README.md @@ -0,0 +1,17 @@ +# graceful-readlink +[![NPM Version](http://img.shields.io/npm/v/graceful-readlink.svg?style=flat)](https://www.npmjs.org/package/graceful-readlink) +[![NPM Downloads](https://img.shields.io/npm/dm/graceful-readlink.svg?style=flat)](https://www.npmjs.org/package/graceful-readlink) + + +## Usage + +```js +var readlinkSync = require('graceful-readlink').readlinkSync; +console.log(readlinkSync(f)); +// output +// the file pointed to when `f` is a symbolic link +// the `f` itself when `f` is not a symbolic link +``` +## Licence + +MIT License diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/index.js new file mode 100644 index 0000000..7e9fc70 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/index.js @@ -0,0 +1,12 @@ +var fs = require('fs') + , lstat = fs.lstatSync; + +exports.readlinkSync = function (p) { + if (lstat(p).isSymbolicLink()) { + return fs.readlinkSync(p); + } else { + return p; + } +}; + + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/package.json new file mode 100644 index 0000000..5b8486a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/node_modules/graceful-readlink/package.json @@ -0,0 +1,48 @@ +{ + "name": "graceful-readlink", + "version": "1.0.1", + "description": "graceful fs.readlink", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/zhiyelee/graceful-readlink.git" + }, + "homepage": "https://github.com/zhiyelee/graceful-readlink", + "bugs": { + "url": "https://github.com/zhiyelee/graceful-readlink/issues" + }, + "keywords": [ + "fs.readlink", + "readlink" + ], + "author": { + "name": "zhiyelee" + }, + "license": "MIT", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "gitHead": "f6655275bebef706fb63fd01b5f062a7052419a5", + "_id": "graceful-readlink@1.0.1", + "_shasum": "4cafad76bc62f02fa039b2f94e9a3dd3a391a725", + "_from": "graceful-readlink@>=1.0.0", + "_npmVersion": "2.1.17", + "_nodeVersion": "0.11.14", + "_npmUser": { + "name": "zhiyelee", + "email": "zhiyelee@gmail.com" + }, + "maintainers": [ + { + "name": "zhiyelee", + "email": "zhiyelee@gmail.com" + } + ], + "dist": { + "shasum": "4cafad76bc62f02fa039b2f94e9a3dd3a391a725", + "tarball": "http://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/graceful-readlink/-/graceful-readlink-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/package.json new file mode 100644 index 0000000..6b45951 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/commander/package.json @@ -0,0 +1,75 @@ +{ + "name": "commander", + "version": "2.8.1", + "description": "the complete solution for node.js command-line programs", + "keywords": [ + "command", + "option", + "parser" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/tj/commander.js.git" + }, + "devDependencies": { + "should": ">= 0.0.1", + "sinon": ">= 1.14.1" + }, + "scripts": { + "test": "make test" + }, + "main": "index", + "engines": { + "node": ">= 0.6.x" + }, + "files": [ + "index.js" + ], + "dependencies": { + "graceful-readlink": ">= 1.0.0" + }, + "gitHead": "c6c84726050b19c0373de27cd359f3baddff579f", + "bugs": { + "url": "https://github.com/tj/commander.js/issues" + }, + "homepage": "https://github.com/tj/commander.js", + "_id": "commander@2.8.1", + "_shasum": "06be367febfda0c330aa1e2a072d3dc9762425d4", + "_from": "commander@>=2.8.1 <3.0.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "zhiyelee", + "email": "zhiyelee@gmail.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "somekittens", + "email": "rkoutnik@gmail.com" + }, + { + "name": "zhiyelee", + "email": "zhiyelee@gmail.com" + }, + { + "name": "thethomaseffect", + "email": "thethomaseffect@gmail.com" + } + ], + "dist": { + "shasum": "06be367febfda0c330aa1e2a072d3dc9762425d4", + "tarball": "http://registry.npmjs.org/commander/-/commander-2.8.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/commander/-/commander-2.8.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.npmignore new file mode 100644 index 0000000..dbb0721 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.npmignore @@ -0,0 +1,2 @@ +node_modules +cosmicrealms.com diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.travis.yml new file mode 100644 index 0000000..6e5919d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/LICENSE new file mode 100644 index 0000000..757562e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/README.md new file mode 100644 index 0000000..47350d8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/README.md @@ -0,0 +1,173 @@ +# is-my-json-valid + +A [JSONSchema](http://json-schema.org/) validator that uses code generation +to be extremely fast + +``` +npm install is-my-json-valid +``` + +It passes the entire JSONSchema v4 test suite except for `remoteRefs` and `maxLength`/`minLength` when using unicode surrogate pairs. + +[![build status](http://img.shields.io/travis/mafintosh/is-my-json-valid.svg?style=flat)](http://travis-ci.org/mafintosh/is-my-json-valid) + +## Usage + +Simply pass a schema to compile it + +``` js +var validator = require('is-my-json-valid') + +var validate = validator({ + required: true, + type: 'object', + properties: { + hello: { + required: true, + type: 'string' + } + } +}) + +console.log('should be valid', validate({hello: 'world'})) +console.log('should not be valid', validate({})) + +// get the last list of errors by checking validate.errors +// the following will print [{field: 'data.hello', message: 'is required'}] +console.log(validate.errors) +``` + +You can also pass the schema as a string + +``` js +var validate = validate('{"type": ... }') +``` + +Optionally you can use the require submodule to load a schema from `__dirname` + +``` js +var validator = require('is-my-json-valid/require') +var validate = validator('my-schema.json') +``` + +## Custom formats + +is-my-json-valid supports the formats specified in JSON schema v4 (such as date-time). +If you want to add your own custom formats pass them as the formats options to the validator + +``` js +var validate = validator({ + type: 'string', + required: true, + format: 'only-a' +}, { + formats: { + 'only-a': /^a+$/ + } +}) + +console.log(validate('aa')) // true +console.log(validate('ab')) // false +``` + +## External schemas + +You can pass in external schemas that you reference using the `$ref` attribute as the `schemas` option + +``` js +var ext = { + required: true, + type: 'string' +} + +var schema = { + $ref: '#ext' // references another schema called ext +} + +// pass the external schemas as an option +var validate = validate(schema, {schemas: {ext: ext}}) + +validate('hello') // returns true +validate(42) // return false +``` + +## Filtering away additional properties + +is-my-json-valid supports filtering away properties not in the schema + +``` js +var filter = validator.filter({ + required: true, + type: 'object', + properties: { + hello: {type: 'string', required: true} + }, + additionalProperties: false +}) + +var doc = {hello: 'world', notInSchema: true} +console.log(filter(doc)) // {hello: 'world'} +``` + +## Verbose mode outputs the value on errors + +is-my-json-valid outputs the value causing an error when verbose is set to true + +``` js +var validate = validator({ + required: true, + type: 'object', + properties: { + hello: { + required: true, + type: 'string' + } + } +}, { + verbose: true +}) + +validate({hello: 100}); +console.log(validate.errors) // {field: 'data.hello', message: 'is the wrong type', value: 100} +``` + +## Greedy mode tries to validate as much as possible + +By default is-my-json-valid bails on first validation error but when greedy is +set to true it tries to validate as much as possible: + +``` js +var validate = validator({ + type: 'object', + properties: { + x: { + type: 'number' + } + }, + required: ['x', 'y'] +}, { + greedy: true +}); + +validate({x: 'string'}); +console.log(validate.errors) // [{field: 'data.y', message: 'is required'}, + // {field: 'data.x', message: 'is the wrong type'}] +``` + +## Performance + +is-my-json-valid uses code generation to turn your JSON schema into basic javascript code that is easily optimizeable by v8. + +At the time of writing, is-my-json-valid is the __fastest validator__ when running + +* [json-schema-benchmark](https://github.com/Muscula/json-schema-benchmark) +* [cosmicreals.com benchmark](http://cosmicrealms.com/blog/2014/08/29/benchmark-of-node-dot-js-json-validation-modules-part-3/) +* [jsck benchmark](https://github.com/pandastrike/jsck/issues/72#issuecomment-70992684) +* [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) +* [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) + +If you know any other relevant benchmarks open a PR and I'll add them. + +## License + +MIT diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/example.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/example.js new file mode 100644 index 0000000..f70f4df --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/example.js @@ -0,0 +1,18 @@ +var validator = require('./') + +var validate = validator({ + type: 'object', + properties: { + hello: { + required: true, + type: 'string' + } + } +}) + +console.log('should be valid', validate({hello: 'world'})) +console.log('should not be valid', validate({})) + +// get the last error message by checking validate.error +// the following will print "data.hello is required" +console.log('the errors were:', validate.errors) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/formats.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/formats.js new file mode 100644 index 0000000..3038dae --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/formats.js @@ -0,0 +1,14 @@ +exports['date-time'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}[tT ]\d{2}:\d{2}:\d{2}(\.\d+)?([zZ]|[+-]\d{2}:\d{2})$/ +exports['date'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/ +exports['time'] = /^\d{2}:\d{2}:\d{2}$/ +exports['email'] = /^\S+@\S+$/ +exports['ip-address'] = exports['ipv4'] = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/ +exports['ipv6'] = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/ +exports['uri'] = /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/ +exports['color'] = /(#?([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))/ +exports['hostname'] = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/ +exports['alpha'] = /^[a-zA-Z]+$/ +exports['alphanumeric'] = /^[a-zA-Z0-9]+$/ +exports['style'] = /\s*(.+?):\s*([^;]+);?/g +exports['phone'] = /^\+(?:[0-9] ?){6,14}[0-9]$/ +exports['utc-millisec'] = /^[0-9]+(\.?[0-9]+)?$/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/index.js new file mode 100644 index 0000000..6fef4ed --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/index.js @@ -0,0 +1,569 @@ +var genobj = require('generate-object-property') +var genfun = require('generate-function') +var jsonpointer = require('jsonpointer') +var xtend = require('xtend') +var formats = require('./formats') + +var get = function(obj, additionalSchemas, ptr) { + if (/^https?:\/\//.test(ptr)) return null + + var visit = function(sub) { + if (sub && sub.id === ptr) return sub + if (typeof sub !== 'object' || !sub) return null + return Object.keys(sub).reduce(function(res, k) { + return res || visit(sub[k]) + }, null) + } + + var res = visit(obj) + if (res) return res + + ptr = ptr.replace(/^#/, '') + ptr = ptr.replace(/\/$/, '') + + try { + return jsonpointer.get(obj, decodeURI(ptr)) + } catch (err) { + var end = ptr.indexOf('#') + var other + // external reference + if (end !== 0) { + // fragment doesn't exist. + if (end === -1) { + other = additionalSchemas[ptr] + } else { + var ext = ptr.slice(0, end) + other = additionalSchemas[ext] + var fragment = ptr.slice(end).replace(/^#/, '') + try { + return jsonpointer.get(other, fragment) + } catch (err) {} + } + } else { + other = additionalSchemas[ptr] + } + return other || null + } +} + +var formatName = function(field) { + field = JSON.stringify(field) + var pattern = /\[([^\[\]"]+)\]/ + while (pattern.test(field)) field = field.replace(pattern, '."+$1+"') + return field +} + +var types = {} + +types.any = function() { + return 'true' +} + +types.null = function(name) { + return name+' === null' +} + +types.boolean = function(name) { + return 'typeof '+name+' === "boolean"' +} + +types.array = function(name) { + return 'Array.isArray('+name+')' +} + +types.object = function(name) { + return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')' +} + +types.number = function(name) { + return 'typeof '+name+' === "number"' +} + +types.integer = function(name) { + return 'typeof '+name+' === "number" && (Math.floor('+name+') === '+name+' || '+name+' > 9007199254740992 || '+name+' < -9007199254740992)' +} + +types.string = function(name) { + return 'typeof '+name+' === "string"' +} + +var unique = function(array) { + var list = [] + for (var i = 0; i < array.length; i++) { + list.push(typeof array[i] === 'object' ? JSON.stringify(array[i]) : array[i]) + } + for (var i = 1; i < list.length; i++) { + if (list.indexOf(list[i]) !== i) return false + } + return true +} + +var toType = function(node) { + return node.type +} + +var compile = function(schema, cache, root, reporter, opts) { + var fmts = opts ? xtend(formats, opts.formats) : formats + var scope = {unique:unique, formats:fmts} + var verbose = opts ? !!opts.verbose : false; + var greedy = opts && opts.greedy !== undefined ? + opts.greedy : false; + + var syms = {} + var gensym = function(name) { + return name+(syms[name] = (syms[name] || 0)+1) + } + + var reversePatterns = {} + var patterns = function(p) { + if (reversePatterns[p]) return reversePatterns[p] + var n = gensym('pattern') + scope[n] = new RegExp(p) + reversePatterns[p] = n + return n + } + + var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'] + var genloop = function() { + var v = vars.shift() + vars.push(v+v[0]) + return v + } + + var visit = function(name, node, reporter, filter) { + var properties = node.properties + var type = node.type + var tuple = false + + if (Array.isArray(node.items)) { // tuple type + properties = {} + node.items.forEach(function(item, i) { + properties[i] = item + }) + type = 'array' + tuple = true + } + + var indent = 0 + var error = function(msg, prop, value) { + validate('errors++') + if (reporter === true) { + validate('if (validate.errors === null) validate.errors = []') + if (verbose) { + validate('validate.errors.push({field:%s,message:%s,value:%s})', formatName(prop || name), JSON.stringify(msg), value || name) + } else { + validate('validate.errors.push({field:%s,message:%s})', formatName(prop || name), JSON.stringify(msg)) + } + } + } + + if (node.required === true) { + indent++ + validate('if (%s === undefined) {', name) + error('is required') + validate('} else {') + } else { + indent++ + validate('if (%s !== undefined) {', name) + } + + var valid = [].concat(type) + .map(function(t) { + return types[t || 'any'](name) + }) + .join(' || ') || 'true' + + if (valid !== 'true') { + indent++ + validate('if (!(%s)) {', valid) + error('is the wrong type') + validate('} else {') + } + + if (tuple) { + if (node.additionalItems === false) { + validate('if (%s.length > %d) {', name, node.items.length) + error('has additional items') + validate('}') + } else if (node.additionalItems) { + var i = genloop() + validate('for (var %s = %d; %s < %s.length; %s++) {', i, node.items.length, i, name, i) + visit(name+'['+i+']', node.additionalItems, reporter, filter) + validate('}') + } + } + + if (node.format && fmts[node.format]) { + if (type !== 'string' && formats[node.format]) validate('if (%s) {', types.string(name)) + var n = gensym('format') + scope[n] = fmts[node.format] + + if (typeof scope[n] === 'function') validate('if (!%s(%s)) {', n, name) + else validate('if (!%s.test(%s)) {', n, name) + error('must be '+node.format+' format') + validate('}') + if (type !== 'string' && formats[node.format]) validate('}') + } + + if (Array.isArray(node.required)) { + var isUndefined = function(req) { + return genobj(name, req) + ' === undefined' + } + + var checkRequired = function (req) { + var prop = genobj(name, req); + validate('if (%s === undefined) {', prop) + error('is required', prop) + validate('missing++') + validate('}') + } + validate('if ((%s)) {', type !== 'object' ? types.object(name) : 'true') + validate('var missing = 0') + node.required.map(checkRequired) + validate('}'); + if (!greedy) { + validate('if (missing === 0) {') + indent++ + } + } + + if (node.uniqueItems) { + if (type !== 'array') validate('if (%s) {', types.array(name)) + validate('if (!(unique(%s))) {', name) + error('must be unique') + validate('}') + if (type !== 'array') validate('}') + } + + if (node.enum) { + var complex = node.enum.some(function(e) { + return typeof e === 'object' + }) + + var compare = complex ? + function(e) { + return 'JSON.stringify('+name+')'+' !== JSON.stringify('+JSON.stringify(e)+')' + } : + function(e) { + return name+' !== '+JSON.stringify(e) + } + + validate('if (%s) {', node.enum.map(compare).join(' && ') || 'false') + error('must be an enum value') + validate('}') + } + + if (node.dependencies) { + if (type !== 'object') validate('if (%s) {', types.object(name)) + + Object.keys(node.dependencies).forEach(function(key) { + var deps = node.dependencies[key] + if (typeof deps === 'string') deps = [deps] + + var exists = function(k) { + return genobj(name, k) + ' !== undefined' + } + + if (Array.isArray(deps)) { + validate('if (%s !== undefined && !(%s)) {', genobj(name, key), deps.map(exists).join(' && ') || 'true') + error('dependencies not set') + validate('}') + } + if (typeof deps === 'object') { + validate('if (%s !== undefined) {', genobj(name, key)) + visit(name, deps, reporter, filter) + validate('}') + } + }) + + if (type !== 'object') validate('}') + } + + if (node.additionalProperties || node.additionalProperties === false) { + if (type !== 'object') validate('if (%s) {', types.object(name)) + + var i = genloop() + var keys = gensym('keys') + + var toCompare = function(p) { + return keys+'['+i+'] !== '+JSON.stringify(p) + } + + var toTest = function(p) { + return '!'+patterns(p)+'.test('+keys+'['+i+'])' + } + + var additionalProp = Object.keys(properties || {}).map(toCompare) + .concat(Object.keys(node.patternProperties || {}).map(toTest)) + .join(' && ') || 'true' + + validate('var %s = Object.keys(%s)', keys, name) + ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i) + ('if (%s) {', additionalProp) + + if (node.additionalProperties === false) { + if (filter) validate('delete %s', name+'['+keys+'['+i+']]') + error('has additional properties', null, JSON.stringify(name+'.') + ' + ' + keys + '['+i+']') + } else { + visit(name+'['+keys+'['+i+']]', node.additionalProperties, reporter, filter) + } + + validate + ('}') + ('}') + + if (type !== 'object') validate('}') + } + + if (node.$ref) { + var sub = get(root, opts && opts.schemas || {}, node.$ref) + if (sub) { + var fn = cache[node.$ref] + if (!fn) { + cache[node.$ref] = function proxy(data) { + return fn(data) + } + fn = compile(sub, cache, root, false, opts) + } + var n = gensym('ref') + scope[n] = fn + validate('if (!(%s(%s))) {', n, name) + error('referenced schema does not match') + validate('}') + } + } + + if (node.not) { + var prev = gensym('prev') + validate('var %s = errors', prev) + visit(name, node.not, false, filter) + validate('if (%s === errors) {', prev) + error('negative schema matches') + validate('} else {') + ('errors = %s', prev) + ('}') + } + + if (node.items && !tuple) { + if (type !== 'array') validate('if (%s) {', types.array(name)) + + var i = genloop() + validate('for (var %s = 0; %s < %s.length; %s++) {', i, i, name, i) + visit(name+'['+i+']', node.items, reporter, filter) + validate('}') + + if (type !== 'array') validate('}') + } + + if (node.patternProperties) { + if (type !== 'object') validate('if (%s) {', types.object(name)) + var keys = gensym('keys') + var i = genloop() + validate + ('var %s = Object.keys(%s)', keys, name) + ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i) + + Object.keys(node.patternProperties).forEach(function(key) { + var p = patterns(key) + validate('if (%s.test(%s)) {', p, keys+'['+i+']') + visit(name+'['+keys+'['+i+']]', node.patternProperties[key], reporter, filter) + validate('}') + }) + + validate('}') + if (type !== 'object') validate('}') + } + + if (node.pattern) { + var p = patterns(node.pattern) + if (type !== 'string') validate('if (%s) {', types.string(name)) + validate('if (!(%s.test(%s))) {', p, name) + error('pattern mismatch') + validate('}') + if (type !== 'string') validate('}') + } + + if (node.allOf) { + node.allOf.forEach(function(sch) { + visit(name, sch, reporter, filter) + }) + } + + if (node.anyOf && node.anyOf.length) { + var prev = gensym('prev') + + node.anyOf.forEach(function(sch, i) { + if (i === 0) { + validate('var %s = errors', prev) + } else { + validate('if (errors !== %s) {', prev) + ('errors = %s', prev) + } + visit(name, sch, false, false) + }) + node.anyOf.forEach(function(sch, i) { + if (i) validate('}') + }) + validate('if (%s !== errors) {', prev) + error('no schemas match') + validate('}') + } + + if (node.oneOf && node.oneOf.length) { + var prev = gensym('prev') + var passes = gensym('passes') + + validate + ('var %s = errors', prev) + ('var %s = 0', passes) + + node.oneOf.forEach(function(sch, i) { + visit(name, sch, false, false) + validate('if (%s === errors) {', prev) + ('%s++', passes) + ('} else {') + ('errors = %s', prev) + ('}') + }) + + validate('if (%s !== 1) {', passes) + error('no (or more than one) schemas match') + validate('}') + } + + if (node.multipleOf !== undefined) { + if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name)) + + var factor = ((node.multipleOf | 0) !== node.multipleOf) ? Math.pow(10, node.multipleOf.toString().split('.').pop().length) : 1 + if (factor > 1) validate('if ((%d*%s) % %d) {', factor, name, factor*node.multipleOf) + else validate('if (%s % %d) {', name, node.multipleOf) + + error('has a remainder') + validate('}') + + if (type !== 'number' && type !== 'integer') validate('}') + } + + if (node.maxProperties !== undefined) { + if (type !== 'object') validate('if (%s) {', types.object(name)) + + validate('if (Object.keys(%s).length > %d) {', name, node.maxProperties) + error('has more properties than allowed') + validate('}') + + if (type !== 'object') validate('}') + } + + if (node.minProperties !== undefined) { + if (type !== 'object') validate('if (%s) {', types.object(name)) + + validate('if (Object.keys(%s).length < %d) {', name, node.minProperties) + error('has less properties than allowed') + validate('}') + + if (type !== 'object') validate('}') + } + + if (node.maxItems !== undefined) { + if (type !== 'array') validate('if (%s) {', types.array(name)) + + validate('if (%s.length > %d) {', name, node.maxItems) + error('has more items than allowed') + validate('}') + + if (type !== 'array') validate('}') + } + + if (node.minItems !== undefined) { + if (type !== 'array') validate('if (%s) {', types.array(name)) + + validate('if (%s.length < %d) {', name, node.minItems) + error('has less items than allowed') + validate('}') + + if (type !== 'array') validate('}') + } + + if (node.maxLength !== undefined) { + if (type !== 'string') validate('if (%s) {', types.string(name)) + + validate('if (%s.length > %d) {', name, node.maxLength) + error('has longer length than allowed') + validate('}') + + if (type !== 'string') validate('}') + } + + if (node.minLength !== undefined) { + if (type !== 'string') validate('if (%s) {', types.string(name)) + + validate('if (%s.length < %d) {', name, node.minLength) + error('has less length than allowed') + validate('}') + + if (type !== 'string') validate('}') + } + + if (node.minimum !== undefined) { + validate('if (%s %s %d) {', name, node.exclusiveMinimum ? '<=' : '<', node.minimum) + error('is less than minimum') + validate('}') + } + + if (node.maximum !== undefined) { + validate('if (%s %s %d) {', name, node.exclusiveMaximum ? '>=' : '>', node.maximum) + error('is more than maximum') + validate('}') + } + + if (properties) { + Object.keys(properties).forEach(function(p) { + visit(genobj(name, p), properties[p], reporter, filter) + }) + } + + while (indent--) validate('}') + } + + var validate = genfun + ('function validate(data) {') + ('validate.errors = null') + ('var errors = 0') + + visit('data', schema, reporter, opts && opts.filter) + + validate + ('return errors === 0') + ('}') + + validate = validate.toFunction(scope) + validate.errors = null + + validate.__defineGetter__('error', function() { + if (!validate.errors) return '' + return validate.errors + .map(function(err) { + return err.field+' '+err.message + }) + .join('\n') + }) + + validate.toJSON = function() { + return schema + } + + return validate +} + +module.exports = function(schema, opts) { + if (typeof schema === 'string') schema = JSON.parse(schema) + return compile(schema, {}, schema, true, opts) +} + +module.exports.filter = function(schema, opts) { + var validate = module.exports(schema, xtend(opts, {filter: true})) + return function(sch) { + validate(sch) + return sch + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.travis.yml new file mode 100644 index 0000000..6e5919d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/README.md new file mode 100644 index 0000000..693bff8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/README.md @@ -0,0 +1,72 @@ +# generate-function + +Module that helps you write generated functions in Node + +``` +npm install generate-function +``` + +[![build status](http://img.shields.io/travis/mafintosh/generate-function.svg?style=flat)](http://travis-ci.org/mafintosh/generate-function) + +## Disclamer + +Writing code that generates code is hard. +You should only use this if you really, really, really need this for performance reasons (like schema validators / parsers etc). + +## Usage + +``` js +var genfun = require('generate-function') + +var addNumber = function(val) { + var fn = genfun() + ('function add(n) {') + ('return n + %d', val) // supports format strings to insert values + ('}') + + return fn.toFunction() // will compile the function +} + +var add2 = addNumber(2) + +console.log('1+2=', add2(1)) +console.log(add2.toString()) // prints the generated function +``` + +If you need to close over variables in your generated function pass them to `toFunction(scope)` + +``` js +var multiply = function(a, b) { + return a * b +} + +var addAndMultiplyNumber = function(val) { + var fn = genfun() + ('function(n) {') + ('if (typeof n !== "number") {') // ending a line with { will indent the source + ('throw new Error("argument should be a number")') + ('}') + ('var result = multiply(%d, n+%d)', val, val) + ('return result') + ('}') + + // use fn.toString() if you want to see the generated source + + return fn.toFunction({ + multiply: multiply + }) +} + +var addAndMultiply2 = addAndMultiplyNumber(2) + +console.log('(3 + 2) * 2 =', addAndMultiply2(3)) +``` + +## Related + +See [generate-object-property](https://github.com/mafintosh/generate-object-property) if you need to safely generate code that +can be used to reference an object property + +## License + +MIT \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/example.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/example.js new file mode 100644 index 0000000..8d1fee1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/example.js @@ -0,0 +1,27 @@ +var genfun = require('./') + +var multiply = function(a, b) { + return a * b +} + +var addAndMultiplyNumber = function(val) { + var fn = genfun() + ('function(n) {') + ('if (typeof n !== "number") {') // ending a line with { will indent the source + ('throw new Error("argument should be a number")') + ('}') + ('var result = multiply(%d, n+%d)', val, val) + ('return result') + ('}') + + // use fn.toString() if you want to see the generated source + + return fn.toFunction({ + multiply: multiply + }) +} + +var addAndMultiply2 = addAndMultiplyNumber(2) + +console.log(addAndMultiply2.toString()) +console.log('(3 + 2) * 2 =', addAndMultiply2(3)) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/index.js new file mode 100644 index 0000000..37e064b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/index.js @@ -0,0 +1,61 @@ +var util = require('util') + +var INDENT_START = /[\{\[]/ +var INDENT_END = /[\}\]]/ + +module.exports = function() { + var lines = [] + var indent = 0 + + var push = function(str) { + var spaces = '' + while (spaces.length < indent*2) spaces += ' ' + lines.push(spaces+str) + } + + var line = function(fmt) { + if (!fmt) return line + + if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) { + indent-- + push(util.format.apply(util, arguments)) + indent++ + return line + } + if (INDENT_START.test(fmt[fmt.length-1])) { + push(util.format.apply(util, arguments)) + indent++ + return line + } + if (INDENT_END.test(fmt.trim()[0])) { + indent-- + push(util.format.apply(util, arguments)) + return line + } + + push(util.format.apply(util, arguments)) + return line + } + + line.toString = function() { + return lines.join('\n') + } + + line.toFunction = function(scope) { + var src = 'return ('+line.toString()+')' + + var keys = Object.keys(scope || {}).map(function(key) { + return key + }) + + var vals = keys.map(function(key) { + return scope[key] + }) + + return Function.apply(null, keys.concat(src)).apply(null, vals) + } + + if (arguments.length) line.apply(null, arguments) + + return line +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/package.json new file mode 100644 index 0000000..db1ac2a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/package.json @@ -0,0 +1,53 @@ +{ + "name": "generate-function", + "version": "2.0.0", + "description": "Module that helps you write generated functions in Node", + "main": "index.js", + "scripts": { + "test": "tape test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/generate-function.git" + }, + "keywords": [ + "generate", + "code", + "generation", + "function", + "performance" + ], + "author": { + "name": "Mathias Buus" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/generate-function/issues" + }, + "homepage": "https://github.com/mafintosh/generate-function", + "devDependencies": { + "tape": "^2.13.4" + }, + "gitHead": "3d5fc8de5859be95f58e3af9bfb5f663edd95149", + "_id": "generate-function@2.0.0", + "_shasum": "6858fe7c0969b7d4e9093337647ac79f60dfbe74", + "_from": "generate-function@>=2.0.0 <3.0.0", + "_npmVersion": "1.4.23", + "_npmUser": { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + }, + "maintainers": [ + { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + } + ], + "dist": { + "shasum": "6858fe7c0969b7d4e9093337647ac79f60dfbe74", + "tarball": "http://registry.npmjs.org/generate-function/-/generate-function-2.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/test.js new file mode 100644 index 0000000..2768893 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/test.js @@ -0,0 +1,33 @@ +var tape = require('tape') +var genfun = require('./') + +tape('generate add function', function(t) { + var fn = genfun() + ('function add(n) {') + ('return n + %d', 42) + ('}') + + t.same(fn.toString(), 'function add(n) {\n return n + 42\n}', 'code is indented') + t.same(fn.toFunction()(10), 52, 'function works') + t.end() +}) + +tape('generate function + closed variables', function(t) { + var fn = genfun() + ('function add(n) {') + ('return n + %d + number', 42) + ('}') + + var notGood = fn.toFunction() + var good = fn.toFunction({number:10}) + + try { + notGood(10) + t.ok(false, 'function should not work') + } catch (err) { + t.same(err.message, 'number is not defined', 'throws reference error') + } + + t.same(good(11), 63, 'function with closed var works') + t.end() +}) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.travis.yml new file mode 100644 index 0000000..6e5919d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/LICENSE new file mode 100644 index 0000000..757562e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/README.md new file mode 100644 index 0000000..0ee0461 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/README.md @@ -0,0 +1,19 @@ +# generate-object-property + +Generate safe JS code that can used to reference a object property + + npm install generate-object-property + +[![build status](http://img.shields.io/travis/mafintosh/generate-object-property.svg?style=flat)](http://travis-ci.org/mafintosh/generate-object-property) + +## Usage + +``` js +var gen = require('generate-object-property'); +console.log(gen('a','b')); // prints a.b +console.log(gen('a', 'foo-bar')); // prints a["foo-bar"] +``` + +## License + +MIT \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/index.js new file mode 100644 index 0000000..5dc9f77 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/index.js @@ -0,0 +1,12 @@ +var isProperty = require('is-property') + +var gen = function(obj, prop) { + return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']' +} + +gen.valid = isProperty +gen.property = function (prop) { + return isProperty(prop) ? prop : JSON.stringify(prop) +} + +module.exports = gen diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/.npmignore new file mode 100644 index 0000000..8ecfa25 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/.npmignore @@ -0,0 +1,17 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules/* +*.DS_Store +test/* \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/LICENSE new file mode 100644 index 0000000..8ce206a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2013 Mikola Lysenko + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/README.md new file mode 100644 index 0000000..ef1d00b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/README.md @@ -0,0 +1,28 @@ +is-property +=========== +Tests if a property of a JavaScript object can be accessed using the dot (.) notation or if it must be enclosed in brackets, (ie use x[" ... "]) + +Example +------- + +```javascript +var isProperty = require("is-property") + +console.log(isProperty("foo")) //Prints true +console.log(isProperty("0")) //Prints false +``` + +Install +------- + + npm install is-property + +### `require("is-property")(str)` +Checks if str is a property + +* `str` is a string which we will test if it is a property or not + +**Returns** true or false depending if str is a property + +## Credits +(c) 2013 Mikola Lysenko. MIT License \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/is-property.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/is-property.js new file mode 100644 index 0000000..db58b47 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/is-property.js @@ -0,0 +1,5 @@ +"use strict" +function isProperty(str) { + return /^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(str) +} +module.exports = isProperty \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/package.json new file mode 100644 index 0000000..9f23619 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/package.json @@ -0,0 +1,59 @@ +{ + "name": "is-property", + "version": "1.0.2", + "description": "Tests if a JSON property can be accessed using . syntax", + "main": "is-property.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.0.4" + }, + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/mikolalysenko/is-property.git" + }, + "keywords": [ + "is", + "property", + "json", + "dot", + "bracket", + ".", + "[]" + ], + "author": { + "name": "Mikola Lysenko" + }, + "license": "MIT", + "gitHead": "0a85ea5b6b1264ea1cdecc6e5cf186adbb3ffc50", + "bugs": { + "url": "https://github.com/mikolalysenko/is-property/issues" + }, + "homepage": "https://github.com/mikolalysenko/is-property", + "_id": "is-property@1.0.2", + "_shasum": "57fe1c4e48474edd65b09911f26b1cd4095dda84", + "_from": "is-property@>=1.0.0 <2.0.0", + "_npmVersion": "2.1.4", + "_nodeVersion": "0.10.26", + "_npmUser": { + "name": "mikolalysenko", + "email": "mikolalysenko@gmail.com" + }, + "maintainers": [ + { + "name": "mikolalysenko", + "email": "mikolalysenko@gmail.com" + } + ], + "dist": { + "shasum": "57fe1c4e48474edd65b09911f26b1cd4095dda84", + "tarball": "http://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz" + }, + "_resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/package.json new file mode 100644 index 0000000..8bc73da --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/package.json @@ -0,0 +1,51 @@ +{ + "name": "generate-object-property", + "version": "1.2.0", + "description": "Generate safe JS code that can used to reference a object property", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/generate-object-property.git" + }, + "devDependencies": { + "tape": "^2.13.0" + }, + "scripts": { + "test": "tape test.js" + }, + "dependencies": { + "is-property": "^1.0.0" + }, + "bugs": { + "url": "https://github.com/mafintosh/generate-object-property/issues" + }, + "homepage": "https://github.com/mafintosh/generate-object-property", + "main": "index.js", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "license": "MIT", + "gitHead": "0dd7d411018de54b2eae63b424c15b3e50bd678c", + "_id": "generate-object-property@1.2.0", + "_shasum": "9c0e1c40308ce804f4783618b937fa88f99d50d0", + "_from": "generate-object-property@>=1.1.0 <2.0.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + }, + "maintainers": [ + { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + } + ], + "dist": { + "shasum": "9c0e1c40308ce804f4783618b937fa88f99d50d0", + "tarball": "http://registry.npmjs.org/generate-object-property/-/generate-object-property-1.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/generate-object-property/-/generate-object-property-1.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/test.js new file mode 100644 index 0000000..6c299c6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/test.js @@ -0,0 +1,12 @@ +var tape = require('tape') +var gen = require('./') + +tape('valid', function(t) { + t.same(gen('a', 'b'), 'a.b') + t.end() +}) + +tape('invalid', function(t) { + t.same(gen('a', '-b'), 'a["-b"]') + t.end() +}) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/.travis.yml new file mode 100644 index 0000000..a057a7c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/.travis.yml @@ -0,0 +1,6 @@ +language: "node_js" +node_js: + - 0.4 + - 0.5 + - 0.6 + - 0.8 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/README.md new file mode 100644 index 0000000..bcfdb1a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/README.md @@ -0,0 +1,31 @@ +# JSON Pointer for nodejs + +This is an implementation of [JSON Pointer](http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-08). + +## Usage + + var jsonpointer = require("jsonpointer"); + var obj = { foo: 1, bar: { baz: 2}, qux: [3, 4, 5]}; + var one = jsonpointer.get(obj, "/foo"); + var two = jsonpointer.get(obj, "/bar/baz"); + var three = jsonpointer.get(obj, "/qux/0"); + var four = jsonpointer.get(obj, "/qux/1"); + var five = jsonpointer.get(obj, "/qux/2"); + + jsonpointer.set(obj, "/foo", 6); // obj.foo = 6; + +## Testing + + $ node test.js + All tests pass. + $ + +[![Build Status](https://travis-ci.org/janl/node-jsonpointer.png?branch=master)](undefined) + +## Author + +(c) 2011 Jan Lehnardt + +## License + +MIT License. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js new file mode 100644 index 0000000..3f53026 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js @@ -0,0 +1,79 @@ +var console = require("console"); + +var untilde = function(str) { + return str.replace(/~./g, function(m) { + switch (m) { + case "~0": + return "~"; + case "~1": + return "/"; + } + throw("Invalid tilde escape: " + m); + }); +} + +var traverse = function(obj, pointer, value) { + // assert(isArray(pointer)) + var part = untilde(pointer.shift()); + if(typeof obj[part] === "undefined") { + throw("Value for pointer '" + pointer + "' not found."); + return; + } + if(pointer.length !== 0) { // keep traversin! + return traverse(obj[part], pointer, value); + } + // we're done + if(typeof value === "undefined") { + // just reading + return obj[part]; + } + // set new value, return old value + var old_value = obj[part]; + if(value === null) { + delete obj[part]; + } else { + obj[part] = value; + } + return old_value; +} + +var validate_input = function(obj, pointer) { + if(typeof obj !== "object") { + throw("Invalid input object."); + } + + if(pointer === "") { + return []; + } + + if(!pointer) { + throw("Invalid JSON pointer."); + } + + pointer = pointer.split("/"); + var first = pointer.shift(); + if (first !== "") { + throw("Invalid JSON pointer."); + } + + return pointer; +} + +var get = function(obj, pointer) { + pointer = validate_input(obj, pointer); + if (pointer.length === 0) { + return obj; + } + return traverse(obj, pointer); +} + +var set = function(obj, pointer, value) { + pointer = validate_input(obj, pointer); + if (pointer.length === 0) { + throw("Invalid JSON pointer for set.") + } + return traverse(obj, pointer, value); +} + +exports.get = get +exports.set = set diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/package.json new file mode 100644 index 0000000..bde9b77 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/package.json @@ -0,0 +1,61 @@ +{ + "name": "jsonpointer", + "description": "Simple JSON Addressing.", + "tags": [ + "util", + "simple", + "util", + "utility" + ], + "version": "1.1.0", + "author": { + "name": "Jan Lehnardt", + "email": "jan@apache.org" + }, + "contributors": [ + { + "name": "Joe Hildebrand", + "email": "joe-github@cursive.net" + }, + { + "name": "Filip Noetzel" + } + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/janl/node-jsonpointer.git" + }, + "bugs": { + "url": "http://github.com/janl/node-jsonpointer/issues" + }, + "engines": [ + "node >= 0.4.9" + ], + "main": "./jsonpointer", + "scripts": { + "test": "node test.js" + }, + "readme": "# JSON Pointer for nodejs\n\nThis is an implementation of [JSON Pointer](http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-08).\n\n## Usage\n\n var jsonpointer = require(\"jsonpointer\");\n var obj = { foo: 1, bar: { baz: 2}, qux: [3, 4, 5]};\n var one = jsonpointer.get(obj, \"/foo\");\n var two = jsonpointer.get(obj, \"/bar/baz\");\n var three = jsonpointer.get(obj, \"/qux/0\");\n var four = jsonpointer.get(obj, \"/qux/1\");\n var five = jsonpointer.get(obj, \"/qux/2\");\n\n jsonpointer.set(obj, \"/foo\", 6); // obj.foo = 6;\n\n## Testing\n\n $ node test.js\n All tests pass.\n $\n\n[![Build Status](https://travis-ci.org/janl/node-jsonpointer.png?branch=master)](undefined)\n\n## Author\n\n(c) 2011 Jan Lehnardt \n\n## License\n\nMIT License.", + "readmeFilename": "README.md", + "_id": "jsonpointer@1.1.0", + "dist": { + "shasum": "c3c72efaed3b97154163dc01dd349e1cfe0f80fc", + "tarball": "http://registry.npmjs.org/jsonpointer/-/jsonpointer-1.1.0.tgz" + }, + "_npmVersion": "1.1.69", + "_npmUser": { + "name": "jan", + "email": "jan@apache.org" + }, + "maintainers": [ + { + "name": "jan", + "email": "jan@apache.org" + } + ], + "directories": {}, + "_shasum": "c3c72efaed3b97154163dc01dd349e1cfe0f80fc", + "_resolved": "https://registry.npmjs.org/jsonpointer/-/jsonpointer-1.1.0.tgz", + "_from": "jsonpointer@>=1.1.0 <2.0.0", + "homepage": "https://github.com/janl/node-jsonpointer" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/test.js new file mode 100644 index 0000000..cdb8ec5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/test.js @@ -0,0 +1,100 @@ +var assert = require("assert"); +var console = require("console"); +var jsonpointer = require("./jsonpointer"); + +var obj = { + a: 1, + b: { + c: 2 + }, + d: { + e: [{a:3}, {b:4}, {c:5}] + } +}; + +assert.equal(jsonpointer.get(obj, "/a"), 1); +assert.equal(jsonpointer.get(obj, "/b/c"), 2); +assert.equal(jsonpointer.get(obj, "/d/e/0/a"), 3); +assert.equal(jsonpointer.get(obj, "/d/e/1/b"), 4); +assert.equal(jsonpointer.get(obj, "/d/e/2/c"), 5); + +// set returns old value +assert.equal(jsonpointer.set(obj, "/a", 2), 1); +assert.equal(jsonpointer.set(obj, "/b/c", 3), 2); +assert.equal(jsonpointer.set(obj, "/d/e/0/a", 4), 3); +assert.equal(jsonpointer.set(obj, "/d/e/1/b", 5), 4); +assert.equal(jsonpointer.set(obj, "/d/e/2/c", 6), 5); + +assert.equal(jsonpointer.get(obj, "/a"), 2); +assert.equal(jsonpointer.get(obj, "/b/c"), 3); +assert.equal(jsonpointer.get(obj, "/d/e/0/a"), 4); +assert.equal(jsonpointer.get(obj, "/d/e/1/b"), 5); +assert.equal(jsonpointer.get(obj, "/d/e/2/c"), 6); + +assert.equal(jsonpointer.get(obj, ""), obj); +assert.throws(function() { + assert.equal(jsonpointer.get(obj, "a"), 3); +}); + +var complexKeys = { + "a/b": { + c: 1 + }, + d: { + "e/f": 2 + }, + "~1": 3, + "01": 4 +} + +assert.equal(jsonpointer.get(complexKeys, "/a~1b/c"), 1); +assert.equal(jsonpointer.get(complexKeys, "/d/e~1f"), 2); +assert.equal(jsonpointer.get(complexKeys, "/~01"), 3); +assert.equal(jsonpointer.get(complexKeys, "/01"), 4); +assert.throws(function() { + assert.equal(jsonpointer.get(complexKeys, "/a/b/c"), 1); +}); +assert.throws(function() { + assert.equal(jsonpointer.get(complexKeys, "/~1"), 3); +}); + +// draft-ietf-appsawg-json-pointer-08 has special array rules +var ary = [ "zero", "one", "two" ]; + +assert.throws(function() { + assert.equal(jsonpointer.get(ary, "/01"), "one"); +}); +//assert.equal(jsonpointer.set(ary, "/-", "three"), null); +//assert.equal(ary[3], "three"); + +// Examples from the draft: +var example = { + "foo": ["bar", "baz"], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 +}; + +assert.equal(jsonpointer.get(example, ""), example); +var ans = jsonpointer.get(example, "/foo"); +assert.equal(ans.length, 2); +assert.equal(ans[0], "bar"); +assert.equal(ans[1], "baz"); +assert.equal(jsonpointer.get(example, "/foo/0"), "bar"); +assert.equal(jsonpointer.get(example, "/"), 0); +assert.equal(jsonpointer.get(example, "/a~1b"), 1); +assert.equal(jsonpointer.get(example, "/c%d"), 2); +assert.equal(jsonpointer.get(example, "/e^f"), 3); +assert.equal(jsonpointer.get(example, "/g|h"), 4); +assert.equal(jsonpointer.get(example, "/i\\j"), 5); +assert.equal(jsonpointer.get(example, "/k\"l"), 6); +assert.equal(jsonpointer.get(example, "/ "), 7); +assert.equal(jsonpointer.get(example, "/m~0n"), 8); + +console.log("All tests pass."); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.jshintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.jshintrc new file mode 100644 index 0000000..77887b5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/LICENCE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/LICENCE new file mode 100644 index 0000000..1a14b43 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2012-2014 Raynos. + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/Makefile new file mode 100644 index 0000000..d583fcf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/Makefile @@ -0,0 +1,4 @@ +browser: + node ./support/compile + +.PHONY: browser \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/README.md new file mode 100644 index 0000000..093cb29 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/README.md @@ -0,0 +1,32 @@ +# xtend + +[![browser support][3]][4] + +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) + +Extend like a boss + +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. + +## Examples + +```js +var extend = require("xtend") + +// extend returns a new object. Does not mutate arguments +var combination = extend({ + a: "a", + b: 'c' +}, { + b: "b" +}) +// { a: "a", b: "b" } +``` + +## Stability status: Locked + +## MIT Licenced + + + [3]: http://ci.testling.com/Raynos/xtend.png + [4]: http://ci.testling.com/Raynos/xtend diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/immutable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/immutable.js new file mode 100644 index 0000000..5b76015 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/immutable.js @@ -0,0 +1,17 @@ +module.exports = extend + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (source.hasOwnProperty(key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/mutable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/mutable.js new file mode 100644 index 0000000..a34475e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/mutable.js @@ -0,0 +1,15 @@ +module.exports = extend + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (source.hasOwnProperty(key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/package.json new file mode 100644 index 0000000..c087642 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/package.json @@ -0,0 +1,72 @@ +{ + "name": "xtend", + "version": "4.0.0", + "description": "extend like a boss", + "keywords": [ + "extend", + "merge", + "options", + "opts", + "object", + "array" + ], + "author": { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Raynos/xtend.git" + }, + "main": "immutable", + "scripts": { + "test": "node test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.0" + }, + "homepage": "https://github.com/Raynos/xtend", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Matt Esch" + } + ], + "bugs": { + "url": "https://github.com/Raynos/xtend/issues", + "email": "raynos2@gmail.com" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/raynos/xtend/raw/master/LICENSE" + } + ], + "testling": { + "files": "test.js", + "browsers": [ + "ie/7..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "engines": { + "node": ">=0.4" + }, + "readme": "# xtend\n\n[![browser support][3]][4]\n\n[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges)\n\nExtend like a boss\n\nxtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence.\n\n## Examples\n\n```js\nvar extend = require(\"xtend\")\n\n// extend returns a new object. Does not mutate arguments\nvar combination = extend({\n a: \"a\",\n b: 'c'\n}, {\n b: \"b\"\n})\n// { a: \"a\", b: \"b\" }\n```\n\n## Stability status: Locked\n\n## MIT Licenced\n\n\n [3]: http://ci.testling.com/Raynos/xtend.png\n [4]: http://ci.testling.com/Raynos/xtend\n", + "readmeFilename": "README.md", + "_id": "xtend@4.0.0", + "_shasum": "8bc36ff87aedbe7ce9eaf0bca36b2354a743840f", + "_resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.0.tgz", + "_from": "xtend@>=4.0.0 <5.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/test.js new file mode 100644 index 0000000..3369d79 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/test.js @@ -0,0 +1,63 @@ +var test = require("tape") +var extend = require("./") +var mutableExtend = require("./mutable") + +test("merge", function(assert) { + var a = { a: "foo" } + var b = { b: "bar" } + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("replace", function(assert) { + var a = { a: "foo" } + var b = { a: "bar" } + + assert.deepEqual(extend(a, b), { a: "bar" }) + assert.end() +}) + +test("undefined", function(assert) { + var a = { a: undefined } + var b = { b: "foo" } + + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) + assert.end() +}) + +test("handle 0", function(assert) { + var a = { a: "default" } + var b = { a: 0 } + + assert.deepEqual(extend(a, b), { a: 0 }) + assert.deepEqual(extend(b, a), { a: "default" }) + assert.end() +}) + +test("is immutable", function (assert) { + var record = {} + + extend(record, { foo: "bar" }) + assert.equal(record.foo, undefined) + assert.end() +}) + +test("null as argument", function (assert) { + var a = { foo: "bar" } + var b = null + var c = void 0 + + assert.deepEqual(extend(b, a, c), { foo: "bar" }) + assert.end() +}) + +test("mutable", function (assert) { + var a = { foo: "bar" } + + mutableExtend(a, { bar: "baz" }) + + assert.equal(a.bar, "baz") + assert.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/package.json new file mode 100644 index 0000000..4f090f3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/package.json @@ -0,0 +1,67 @@ +{ + "name": "is-my-json-valid", + "version": "2.12.0", + "description": "A JSONSchema validator that uses code generation to be extremely fast", + "main": "index.js", + "dependencies": { + "generate-function": "^2.0.0", + "generate-object-property": "^1.1.0", + "jsonpointer": "^1.1.0", + "xtend": "^4.0.0" + }, + "devDependencies": { + "tape": "^2.13.4" + }, + "scripts": { + "test": "tape test/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/is-my-json-valid.git" + }, + "keywords": [ + "json", + "schema", + "orderly", + "jsonschema" + ], + "author": { + "name": "Mathias Buus" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/is-my-json-valid/issues" + }, + "homepage": "https://github.com/mafintosh/is-my-json-valid", + "gitHead": "fc2d995ecb1bdb0f367ddf114dfd069265043c6c", + "_id": "is-my-json-valid@2.12.0", + "_shasum": "8fa6c408b26be95b45a23e8f8c4b464a53874d2b", + "_from": "is-my-json-valid@>=2.12.0 <3.0.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + }, + "maintainers": [ + { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + }, + { + "name": "watson", + "email": "w@tson.dk" + }, + { + "name": "freeall", + "email": "freeall@gmail.com" + } + ], + "dist": { + "shasum": "8fa6c408b26be95b45a23e8f8c4b464a53874d2b", + "tarball": "http://registry.npmjs.org/is-my-json-valid/-/is-my-json-valid-2.12.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/is-my-json-valid/-/is-my-json-valid-2.12.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/require.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/require.js new file mode 100644 index 0000000..0bfb8a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/require.js @@ -0,0 +1,12 @@ +var fs = require('fs') +var path = require('path') +var compile = require('./') + +delete require.cache[require.resolve(__filename)] + +module.exports = function(file, opts) { + file = path.join(path.dirname(module.parent.filename), file) + if (!fs.existsSync(file) && fs.existsSync(file+'.schema')) file += '.schema' + if (!fs.existsSync(file) && fs.existsSync(file+'.json')) file += '.json' + return compile(fs.readFileSync(file, 'utf-8'), opts) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/fixtures/cosmic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/fixtures/cosmic.js new file mode 100644 index 0000000..4e0a34b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/fixtures/cosmic.js @@ -0,0 +1,84 @@ +exports.valid = { + fullName : "John Doe", + age : 47, + state : "Massachusetts", + city : "Boston", + zip : 16417, + married : false, + dozen : 12, + dozenOrBakersDozen : 13, + favoriteEvenNumber : 14, + topThreeFavoriteColors : [ "red", "blue", "green" ], + favoriteSingleDigitWholeNumbers : [ 7 ], + favoriteFiveLetterWord : "coder", + emailAddresses : + [ + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@letters-in-local.org", + "01234567890@numbers-in-local.net", + "&'*+-./=?^_{}~@other-valid-characters-in-local.net", + "mixed-1234-in-{+^}-local@sld.net", + "a@single-character-in-local.org", + "\"quoted\"@sld.com", + "\"\\e\\s\\c\\a\\p\\e\\d\"@sld.com", + "\"quoted-at-sign@sld.org\"@sld.com", + "\"escaped\\\"quote\"@sld.com", + "\"back\\slash\"@sld.com", + "one-character-third-level@a.example.com", + "single-character-in-sld@x.org", + "local@dash-in-sld.com", + "letters-in-sld@123.com", + "one-letter-sld@x.org", + "uncommon-tld@sld.museum", + "uncommon-tld@sld.travel", + "uncommon-tld@sld.mobi", + "country-code-tld@sld.uk", + "country-code-tld@sld.rw", + "local@sld.newTLD", + "the-total-length@of-an-entire-address.cannot-be-longer-than-two-hundred-and-fifty-four-characters.and-this-address-is-254-characters-exactly.so-it-should-be-valid.and-im-going-to-add-some-more-words-here.to-increase-the-lenght-blah-blah-blah-blah-bla.org", + "the-character-limit@for-each-part.of-the-domain.is-sixty-three-characters.this-is-exactly-sixty-three-characters-so-it-is-valid-blah-blah.com", + "local@sub.domains.com" + ], + ipAddresses : [ "127.0.0.1", "24.48.64.2", "192.168.1.1", "209.68.44.3", "2.2.2.2" ] +} + +exports.invalid = { + fullName : null, + age : -1, + state : 47, + city : false, + zip : [null], + married : "yes", + dozen : 50, + dozenOrBakersDozen : "over 9000", + favoriteEvenNumber : 15, + topThreeFavoriteColors : [ "red", 5 ], + favoriteSingleDigitWholeNumbers : [ 78, 2, 999 ], + favoriteFiveLetterWord : "codernaut", + emailAddresses : [], + ipAddresses : [ "999.0.099.1", "294.48.64.2346", false, "2221409.64214128.42414.235233", "124124.12412412" ] +} + +exports.schema = { // from cosmic thingy + name : "test", + type : "object", + additionalProperties : false, + required : ["fullName", "age", "zip", "married", "dozen", "dozenOrBakersDozen", "favoriteEvenNumber", "topThreeFavoriteColors", "favoriteSingleDigitWholeNumbers", "favoriteFiveLetterWord", "emailAddresses", "ipAddresses"], + properties : + { + fullName : { type : "string" }, + age : { type : "integer", minimum : 0 }, + optionalItem : { type : "string" }, + state : { type : "string" }, + city : { type : "string" }, + zip : { type : "integer", minimum : 0, maximum : 99999 }, + married : { type : "boolean" }, + dozen : { type : "integer", minimum : 12, maximum : 12 }, + dozenOrBakersDozen : { type : "integer", minimum : 12, maximum : 13 }, + favoriteEvenNumber : { type : "integer", multipleOf : 2 }, + topThreeFavoriteColors : { type : "array", minItems : 3, maxItems : 3, uniqueItems : true, items : { type : "string" }}, + favoriteSingleDigitWholeNumbers : { type : "array", minItems : 1, maxItems : 10, uniqueItems : true, items : { type : "integer", minimum : 0, maximum : 9 }}, + favoriteFiveLetterWord : { type : "string", minLength : 5, maxLength : 5 }, + emailAddresses : { type : "array", minItems : 1, uniqueItems : true, items : { type : "string", format : "email" }}, + ipAddresses : { type : "array", uniqueItems : true, items : { type : "string", format : "ipv4" }}, + } + } \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalItems.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalItems.json new file mode 100644 index 0000000..521745c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalItems.json @@ -0,0 +1,82 @@ +[ + { + "description": "additionalItems as schema", + "schema": { + "items": [{}], + "additionalItems": {"type": "integer"} + }, + "tests": [ + { + "description": "additional items match schema", + "data": [ null, 2, 3, 4 ], + "valid": true + }, + { + "description": "additional items do not match schema", + "data": [ null, 2, 3, "foo" ], + "valid": false + } + ] + }, + { + "description": "items is schema, no additionalItems", + "schema": { + "items": {}, + "additionalItems": false + }, + "tests": [ + { + "description": "all items match schema", + "data": [ 1, 2, 3, 4, 5 ], + "valid": true + } + ] + }, + { + "description": "array of items with no additionalItems", + "schema": { + "items": [{}, {}, {}], + "additionalItems": false + }, + "tests": [ + { + "description": "no additional items present", + "data": [ 1, 2, 3 ], + "valid": true + }, + { + "description": "additional items are not permitted", + "data": [ 1, 2, 3, 4 ], + "valid": false + } + ] + }, + { + "description": "additionalItems as false without items", + "schema": {"additionalItems": false}, + "tests": [ + { + "description": + "items defaults to empty schema so everything is valid", + "data": [ 1, 2, 3, 4, 5 ], + "valid": true + }, + { + "description": "ignores non-arrays", + "data": {"foo" : "bar"}, + "valid": true + } + ] + }, + { + "description": "additionalItems are allowed by default", + "schema": {"items": [{"type": "integer"}]}, + "tests": [ + { + "description": "only the first item is validated", + "data": [1, "foo", false], + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalProperties.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalProperties.json new file mode 100644 index 0000000..40831f9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/additionalProperties.json @@ -0,0 +1,88 @@ +[ + { + "description": + "additionalProperties being false does not allow other properties", + "schema": { + "properties": {"foo": {}, "bar": {}}, + "patternProperties": { "^v": {} }, + "additionalProperties": false + }, + "tests": [ + { + "description": "no additional properties is valid", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "an additional property is invalid", + "data": {"foo" : 1, "bar" : 2, "quux" : "boom"}, + "valid": false + }, + { + "description": "ignores non-objects", + "data": [1, 2, 3], + "valid": true + }, + { + "description": "patternProperties are not additional properties", + "data": {"foo":1, "vroom": 2}, + "valid": true + } + ] + }, + { + "description": + "additionalProperties allows a schema which should validate", + "schema": { + "properties": {"foo": {}, "bar": {}}, + "additionalProperties": {"type": "boolean"} + }, + "tests": [ + { + "description": "no additional properties is valid", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "an additional valid property is valid", + "data": {"foo" : 1, "bar" : 2, "quux" : true}, + "valid": true + }, + { + "description": "an additional invalid property is invalid", + "data": {"foo" : 1, "bar" : 2, "quux" : 12}, + "valid": false + } + ] + }, + { + "description": + "additionalProperties can exist by itself", + "schema": { + "additionalProperties": {"type": "boolean"} + }, + "tests": [ + { + "description": "an additional valid property is valid", + "data": {"foo" : true}, + "valid": true + }, + { + "description": "an additional invalid property is invalid", + "data": {"foo" : 1}, + "valid": false + } + ] + }, + { + "description": "additionalProperties are allowed by default", + "schema": {"properties": {"foo": {}, "bar": {}}}, + "tests": [ + { + "description": "additional properties are allowed", + "data": {"foo": 1, "bar": 2, "quux": true}, + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/allOf.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/allOf.json new file mode 100644 index 0000000..bbb5f89 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/allOf.json @@ -0,0 +1,112 @@ +[ + { + "description": "allOf", + "schema": { + "allOf": [ + { + "properties": { + "bar": {"type": "integer"} + }, + "required": ["bar"] + }, + { + "properties": { + "foo": {"type": "string"} + }, + "required": ["foo"] + } + ] + }, + "tests": [ + { + "description": "allOf", + "data": {"foo": "baz", "bar": 2}, + "valid": true + }, + { + "description": "mismatch second", + "data": {"foo": "baz"}, + "valid": false + }, + { + "description": "mismatch first", + "data": {"bar": 2}, + "valid": false + }, + { + "description": "wrong type", + "data": {"foo": "baz", "bar": "quux"}, + "valid": false + } + ] + }, + { + "description": "allOf with base schema", + "schema": { + "properties": {"bar": {"type": "integer"}}, + "required": ["bar"], + "allOf" : [ + { + "properties": { + "foo": {"type": "string"} + }, + "required": ["foo"] + }, + { + "properties": { + "baz": {"type": "null"} + }, + "required": ["baz"] + } + ] + }, + "tests": [ + { + "description": "valid", + "data": {"foo": "quux", "bar": 2, "baz": null}, + "valid": true + }, + { + "description": "mismatch base schema", + "data": {"foo": "quux", "baz": null}, + "valid": false + }, + { + "description": "mismatch first allOf", + "data": {"bar": 2, "baz": null}, + "valid": false + }, + { + "description": "mismatch second allOf", + "data": {"foo": "quux", "bar": 2}, + "valid": false + }, + { + "description": "mismatch both", + "data": {"bar": 2}, + "valid": false + } + ] + }, + { + "description": "allOf simple types", + "schema": { + "allOf": [ + {"maximum": 30}, + {"minimum": 20} + ] + }, + "tests": [ + { + "description": "valid", + "data": 25, + "valid": true + }, + { + "description": "mismatch one", + "data": 35, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/anyOf.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/anyOf.json new file mode 100644 index 0000000..a58714a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/anyOf.json @@ -0,0 +1,68 @@ +[ + { + "description": "anyOf", + "schema": { + "anyOf": [ + { + "type": "integer" + }, + { + "minimum": 2 + } + ] + }, + "tests": [ + { + "description": "first anyOf valid", + "data": 1, + "valid": true + }, + { + "description": "second anyOf valid", + "data": 2.5, + "valid": true + }, + { + "description": "both anyOf valid", + "data": 3, + "valid": true + }, + { + "description": "neither anyOf valid", + "data": 1.5, + "valid": false + } + ] + }, + { + "description": "anyOf with base schema", + "schema": { + "type": "string", + "anyOf" : [ + { + "maxLength": 2 + }, + { + "minLength": 4 + } + ] + }, + "tests": [ + { + "description": "mismatch base schema", + "data": 3, + "valid": false + }, + { + "description": "one anyOf valid", + "data": "foobar", + "valid": true + }, + { + "description": "both anyOf invalid", + "data": "foo", + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/bignum.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/bignum.json new file mode 100644 index 0000000..ccc7c17 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/bignum.json @@ -0,0 +1,107 @@ +[ + { + "description": "integer", + "schema": {"type": "integer"}, + "tests": [ + { + "description": "a bignum is an integer", + "data": 12345678910111213141516171819202122232425262728293031, + "valid": true + } + ] + }, + { + "description": "number", + "schema": {"type": "number"}, + "tests": [ + { + "description": "a bignum is a number", + "data": 98249283749234923498293171823948729348710298301928331, + "valid": true + } + ] + }, + { + "description": "integer", + "schema": {"type": "integer"}, + "tests": [ + { + "description": "a negative bignum is an integer", + "data": -12345678910111213141516171819202122232425262728293031, + "valid": true + } + ] + }, + { + "description": "number", + "schema": {"type": "number"}, + "tests": [ + { + "description": "a negative bignum is a number", + "data": -98249283749234923498293171823948729348710298301928331, + "valid": true + } + ] + }, + { + "description": "string", + "schema": {"type": "string"}, + "tests": [ + { + "description": "a bignum is not a string", + "data": 98249283749234923498293171823948729348710298301928331, + "valid": false + } + ] + }, + { + "description": "integer comparison", + "schema": {"maximum": 18446744073709551615}, + "tests": [ + { + "description": "comparison works for high numbers", + "data": 18446744073709551600, + "valid": true + } + ] + }, + { + "description": "float comparison with high precision", + "schema": { + "maximum": 972783798187987123879878123.18878137, + "exclusiveMaximum": true + }, + "tests": [ + { + "description": "comparison works for high numbers", + "data": 972783798187987123879878123.188781371, + "valid": false + } + ] + }, + { + "description": "integer comparison", + "schema": {"minimum": -18446744073709551615}, + "tests": [ + { + "description": "comparison works for very negative numbers", + "data": -18446744073709551600, + "valid": true + } + ] + }, + { + "description": "float comparison with high precision on negative numbers", + "schema": { + "minimum": -972783798187987123879878123.18878137, + "exclusiveMinimum": true + }, + "tests": [ + { + "description": "comparison works for very negative numbers", + "data": -972783798187987123879878123.188781371, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/default.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/default.json new file mode 100644 index 0000000..1762977 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/default.json @@ -0,0 +1,49 @@ +[ + { + "description": "invalid type for default", + "schema": { + "properties": { + "foo": { + "type": "integer", + "default": [] + } + } + }, + "tests": [ + { + "description": "valid when property is specified", + "data": {"foo": 13}, + "valid": true + }, + { + "description": "still valid when the invalid default is used", + "data": {}, + "valid": true + } + ] + }, + { + "description": "invalid string value for default", + "schema": { + "properties": { + "bar": { + "type": "string", + "minLength": 4, + "default": "bad" + } + } + }, + "tests": [ + { + "description": "valid when property is specified", + "data": {"bar": "good"}, + "valid": true + }, + { + "description": "still valid when the invalid default is used", + "data": {}, + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/definitions.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/definitions.json new file mode 100644 index 0000000..cf935a3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/definitions.json @@ -0,0 +1,32 @@ +[ + { + "description": "valid definition", + "schema": {"$ref": "http://json-schema.org/draft-04/schema#"}, + "tests": [ + { + "description": "valid definition schema", + "data": { + "definitions": { + "foo": {"type": "integer"} + } + }, + "valid": true + } + ] + }, + { + "description": "invalid definition", + "schema": {"$ref": "http://json-schema.org/draft-04/schema#"}, + "tests": [ + { + "description": "invalid definition schema", + "data": { + "definitions": { + "foo": {"type": 1} + } + }, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/dependencies.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/dependencies.json new file mode 100644 index 0000000..7b9b16a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/dependencies.json @@ -0,0 +1,113 @@ +[ + { + "description": "dependencies", + "schema": { + "dependencies": {"bar": ["foo"]} + }, + "tests": [ + { + "description": "neither", + "data": {}, + "valid": true + }, + { + "description": "nondependant", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "with dependency", + "data": {"foo": 1, "bar": 2}, + "valid": true + }, + { + "description": "missing dependency", + "data": {"bar": 2}, + "valid": false + }, + { + "description": "ignores non-objects", + "data": "foo", + "valid": true + } + ] + }, + { + "description": "multiple dependencies", + "schema": { + "dependencies": {"quux": ["foo", "bar"]} + }, + "tests": [ + { + "description": "neither", + "data": {}, + "valid": true + }, + { + "description": "nondependants", + "data": {"foo": 1, "bar": 2}, + "valid": true + }, + { + "description": "with dependencies", + "data": {"foo": 1, "bar": 2, "quux": 3}, + "valid": true + }, + { + "description": "missing dependency", + "data": {"foo": 1, "quux": 2}, + "valid": false + }, + { + "description": "missing other dependency", + "data": {"bar": 1, "quux": 2}, + "valid": false + }, + { + "description": "missing both dependencies", + "data": {"quux": 1}, + "valid": false + } + ] + }, + { + "description": "multiple dependencies subschema", + "schema": { + "dependencies": { + "bar": { + "properties": { + "foo": {"type": "integer"}, + "bar": {"type": "integer"} + } + } + } + }, + "tests": [ + { + "description": "valid", + "data": {"foo": 1, "bar": 2}, + "valid": true + }, + { + "description": "no dependency", + "data": {"foo": "quux"}, + "valid": true + }, + { + "description": "wrong type", + "data": {"foo": "quux", "bar": 2}, + "valid": false + }, + { + "description": "wrong type other", + "data": {"foo": 2, "bar": "quux"}, + "valid": false + }, + { + "description": "wrong type both", + "data": {"foo": "quux", "bar": "quux"}, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/enum.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/enum.json new file mode 100644 index 0000000..f124436 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/enum.json @@ -0,0 +1,72 @@ +[ + { + "description": "simple enum validation", + "schema": {"enum": [1, 2, 3]}, + "tests": [ + { + "description": "one of the enum is valid", + "data": 1, + "valid": true + }, + { + "description": "something else is invalid", + "data": 4, + "valid": false + } + ] + }, + { + "description": "heterogeneous enum validation", + "schema": {"enum": [6, "foo", [], true, {"foo": 12}]}, + "tests": [ + { + "description": "one of the enum is valid", + "data": [], + "valid": true + }, + { + "description": "something else is invalid", + "data": null, + "valid": false + }, + { + "description": "objects are deep compared", + "data": {"foo": false}, + "valid": false + } + ] + }, + { + "description": "enums in properties", + "schema": { + "type":"object", + "properties": { + "foo": {"enum":["foo"]}, + "bar": {"enum":["bar"]} + }, + "required": ["bar"] + }, + "tests": [ + { + "description": "both properties are valid", + "data": {"foo":"foo", "bar":"bar"}, + "valid": true + }, + { + "description": "missing optional property is valid", + "data": {"bar":"bar"}, + "valid": true + }, + { + "description": "missing required property is invalid", + "data": {"foo":"foo"}, + "valid": false + }, + { + "description": "missing all properties is invalid", + "data": {}, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/format.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/format.json new file mode 100644 index 0000000..53c5d25 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/format.json @@ -0,0 +1,143 @@ +[ + { + "description": "validation of date-time strings", + "schema": {"format": "date-time"}, + "tests": [ + { + "description": "a valid date-time string", + "data": "1963-06-19T08:30:06.283185Z", + "valid": true + }, + { + "description": "an invalid date-time string", + "data": "06/19/1963 08:30:06 PST", + "valid": false + }, + { + "description": "only RFC3339 not all of ISO 8601 are valid", + "data": "2013-350T01:01:01", + "valid": false + } + ] + }, + { + "description": "validation of URIs", + "schema": {"format": "uri"}, + "tests": [ + { + "description": "a valid URI", + "data": "http://foo.bar/?baz=qux#quux", + "valid": true + }, + { + "description": "an invalid URI", + "data": "\\\\WINDOWS\\fileshare", + "valid": false + }, + { + "description": "an invalid URI though valid URI reference", + "data": "abc", + "valid": false + } + ] + }, + { + "description": "validation of e-mail addresses", + "schema": {"format": "email"}, + "tests": [ + { + "description": "a valid e-mail address", + "data": "joe.bloggs@example.com", + "valid": true + }, + { + "description": "an invalid e-mail address", + "data": "2962", + "valid": false + } + ] + }, + { + "description": "validation of IP addresses", + "schema": {"format": "ipv4"}, + "tests": [ + { + "description": "a valid IP address", + "data": "192.168.0.1", + "valid": true + }, + { + "description": "an IP address with too many components", + "data": "127.0.0.0.1", + "valid": false + }, + { + "description": "an IP address with out-of-range values", + "data": "256.256.256.256", + "valid": false + }, + { + "description": "an IP address without 4 components", + "data": "127.0", + "valid": false + }, + { + "description": "an IP address as an integer", + "data": "0x7f000001", + "valid": false + } + ] + }, + { + "description": "validation of IPv6 addresses", + "schema": {"format": "ipv6"}, + "tests": [ + { + "description": "a valid IPv6 address", + "data": "::1", + "valid": true + }, + { + "description": "an IPv6 address with out-of-range values", + "data": "12345::", + "valid": false + }, + { + "description": "an IPv6 address with too many components", + "data": "1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1", + "valid": false + }, + { + "description": "an IPv6 address containing illegal characters", + "data": "::laptop", + "valid": false + } + ] + }, + { + "description": "validation of host names", + "schema": {"format": "hostname"}, + "tests": [ + { + "description": "a valid host name", + "data": "www.example.com", + "valid": true + }, + { + "description": "a host name starting with an illegal character", + "data": "-a-host-name-that-starts-with--", + "valid": false + }, + { + "description": "a host name containing illegal characters", + "data": "not_a_valid_host_name", + "valid": false + }, + { + "description": "a host name with a component too long", + "data": "a-vvvvvvvvvvvvvvvveeeeeeeeeeeeeeeerrrrrrrrrrrrrrrryyyyyyyyyyyyyyyy-long-host-name-component", + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/items.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/items.json new file mode 100644 index 0000000..f5e18a1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/items.json @@ -0,0 +1,46 @@ +[ + { + "description": "a schema given for items", + "schema": { + "items": {"type": "integer"} + }, + "tests": [ + { + "description": "valid items", + "data": [ 1, 2, 3 ], + "valid": true + }, + { + "description": "wrong type of items", + "data": [1, "x"], + "valid": false + }, + { + "description": "ignores non-arrays", + "data": {"foo" : "bar"}, + "valid": true + } + ] + }, + { + "description": "an array of schemas for items", + "schema": { + "items": [ + {"type": "integer"}, + {"type": "string"} + ] + }, + "tests": [ + { + "description": "correct types", + "data": [ 1, "foo" ], + "valid": true + }, + { + "description": "wrong types", + "data": [ "foo", 1 ], + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxItems.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxItems.json new file mode 100644 index 0000000..3b53a6b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxItems.json @@ -0,0 +1,28 @@ +[ + { + "description": "maxItems validation", + "schema": {"maxItems": 2}, + "tests": [ + { + "description": "shorter is valid", + "data": [1], + "valid": true + }, + { + "description": "exact length is valid", + "data": [1, 2], + "valid": true + }, + { + "description": "too long is invalid", + "data": [1, 2, 3], + "valid": false + }, + { + "description": "ignores non-arrays", + "data": "foobar", + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxLength.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxLength.json new file mode 100644 index 0000000..48eb129 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxLength.json @@ -0,0 +1,28 @@ +[ + { + "description": "maxLength validation", + "schema": {"maxLength": 2}, + "tests": [ + { + "description": "shorter is valid", + "data": "f", + "valid": true + }, + { + "description": "exact length is valid", + "data": "fo", + "valid": true + }, + { + "description": "too long is invalid", + "data": "foo", + "valid": false + }, + { + "description": "ignores non-strings", + "data": 100, + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxProperties.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxProperties.json new file mode 100644 index 0000000..d282446 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maxProperties.json @@ -0,0 +1,28 @@ +[ + { + "description": "maxProperties validation", + "schema": {"maxProperties": 2}, + "tests": [ + { + "description": "shorter is valid", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "exact length is valid", + "data": {"foo": 1, "bar": 2}, + "valid": true + }, + { + "description": "too long is invalid", + "data": {"foo": 1, "bar": 2, "baz": 3}, + "valid": false + }, + { + "description": "ignores non-objects", + "data": "foobar", + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maximum.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maximum.json new file mode 100644 index 0000000..86c7b89 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/maximum.json @@ -0,0 +1,42 @@ +[ + { + "description": "maximum validation", + "schema": {"maximum": 3.0}, + "tests": [ + { + "description": "below the maximum is valid", + "data": 2.6, + "valid": true + }, + { + "description": "above the maximum is invalid", + "data": 3.5, + "valid": false + }, + { + "description": "ignores non-numbers", + "data": "x", + "valid": true + } + ] + }, + { + "description": "exclusiveMaximum validation", + "schema": { + "maximum": 3.0, + "exclusiveMaximum": true + }, + "tests": [ + { + "description": "below the maximum is still valid", + "data": 2.2, + "valid": true + }, + { + "description": "boundary point is invalid", + "data": 3.0, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minItems.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minItems.json new file mode 100644 index 0000000..ed51188 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minItems.json @@ -0,0 +1,28 @@ +[ + { + "description": "minItems validation", + "schema": {"minItems": 1}, + "tests": [ + { + "description": "longer is valid", + "data": [1, 2], + "valid": true + }, + { + "description": "exact length is valid", + "data": [1], + "valid": true + }, + { + "description": "too short is invalid", + "data": [], + "valid": false + }, + { + "description": "ignores non-arrays", + "data": "", + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minLength.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minLength.json new file mode 100644 index 0000000..e9c14b1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minLength.json @@ -0,0 +1,28 @@ +[ + { + "description": "minLength validation", + "schema": {"minLength": 2}, + "tests": [ + { + "description": "longer is valid", + "data": "foo", + "valid": true + }, + { + "description": "exact length is valid", + "data": "fo", + "valid": true + }, + { + "description": "too short is invalid", + "data": "f", + "valid": false + }, + { + "description": "ignores non-strings", + "data": 1, + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minProperties.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minProperties.json new file mode 100644 index 0000000..a72c7d2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minProperties.json @@ -0,0 +1,28 @@ +[ + { + "description": "minProperties validation", + "schema": {"minProperties": 1}, + "tests": [ + { + "description": "longer is valid", + "data": {"foo": 1, "bar": 2}, + "valid": true + }, + { + "description": "exact length is valid", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "too short is invalid", + "data": {}, + "valid": false + }, + { + "description": "ignores non-objects", + "data": "", + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minimum.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minimum.json new file mode 100644 index 0000000..d5bf000 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/minimum.json @@ -0,0 +1,42 @@ +[ + { + "description": "minimum validation", + "schema": {"minimum": 1.1}, + "tests": [ + { + "description": "above the minimum is valid", + "data": 2.6, + "valid": true + }, + { + "description": "below the minimum is invalid", + "data": 0.6, + "valid": false + }, + { + "description": "ignores non-numbers", + "data": "x", + "valid": true + } + ] + }, + { + "description": "exclusiveMinimum validation", + "schema": { + "minimum": 1.1, + "exclusiveMinimum": true + }, + "tests": [ + { + "description": "above the minimum is still valid", + "data": 1.2, + "valid": true + }, + { + "description": "boundary point is invalid", + "data": 1.1, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/multipleOf.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/multipleOf.json new file mode 100644 index 0000000..ca3b761 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/multipleOf.json @@ -0,0 +1,60 @@ +[ + { + "description": "by int", + "schema": {"multipleOf": 2}, + "tests": [ + { + "description": "int by int", + "data": 10, + "valid": true + }, + { + "description": "int by int fail", + "data": 7, + "valid": false + }, + { + "description": "ignores non-numbers", + "data": "foo", + "valid": true + } + ] + }, + { + "description": "by number", + "schema": {"multipleOf": 1.5}, + "tests": [ + { + "description": "zero is multiple of anything", + "data": 0, + "valid": true + }, + { + "description": "4.5 is multiple of 1.5", + "data": 4.5, + "valid": true + }, + { + "description": "35 is not multiple of 1.5", + "data": 35, + "valid": false + } + ] + }, + { + "description": "by small number", + "schema": {"multipleOf": 0.0001}, + "tests": [ + { + "description": "0.0075 is multiple of 0.0001", + "data": 0.0075, + "valid": true + }, + { + "description": "0.00751 is not multiple of 0.0001", + "data": 0.00751, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/not.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/not.json new file mode 100644 index 0000000..cbb7f46 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/not.json @@ -0,0 +1,96 @@ +[ + { + "description": "not", + "schema": { + "not": {"type": "integer"} + }, + "tests": [ + { + "description": "allowed", + "data": "foo", + "valid": true + }, + { + "description": "disallowed", + "data": 1, + "valid": false + } + ] + }, + { + "description": "not multiple types", + "schema": { + "not": {"type": ["integer", "boolean"]} + }, + "tests": [ + { + "description": "valid", + "data": "foo", + "valid": true + }, + { + "description": "mismatch", + "data": 1, + "valid": false + }, + { + "description": "other mismatch", + "data": true, + "valid": false + } + ] + }, + { + "description": "not more complex schema", + "schema": { + "not": { + "type": "object", + "properties": { + "foo": { + "type": "string" + } + } + } + }, + "tests": [ + { + "description": "match", + "data": 1, + "valid": true + }, + { + "description": "other match", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "mismatch", + "data": {"foo": "bar"}, + "valid": false + } + ] + }, + { + "description": "forbidden property", + "schema": { + "properties": { + "foo": { + "not": {} + } + } + }, + "tests": [ + { + "description": "property present", + "data": {"foo": 1, "bar": 2}, + "valid": false + }, + { + "description": "property absent", + "data": {"bar": 1, "baz": 2}, + "valid": true + } + ] + } + +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/nullAndFormat.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/nullAndFormat.json new file mode 100644 index 0000000..d7fce9f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/nullAndFormat.json @@ -0,0 +1,18 @@ +[ + { + "description": "validation of null and format", + "schema": {"type": ["null", "string"], "format": "date-time"}, + "tests": [ + { + "description": "a valid date-time string", + "data": "1963-06-19T08:30:06.283185Z", + "valid": true + }, + { + "description": "allow null", + "data": null, + "valid": true + } + ] + } +] \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/oneOf.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/oneOf.json new file mode 100644 index 0000000..1eaa4e4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/oneOf.json @@ -0,0 +1,68 @@ +[ + { + "description": "oneOf", + "schema": { + "oneOf": [ + { + "type": "integer" + }, + { + "minimum": 2 + } + ] + }, + "tests": [ + { + "description": "first oneOf valid", + "data": 1, + "valid": true + }, + { + "description": "second oneOf valid", + "data": 2.5, + "valid": true + }, + { + "description": "both oneOf valid", + "data": 3, + "valid": false + }, + { + "description": "neither oneOf valid", + "data": 1.5, + "valid": false + } + ] + }, + { + "description": "oneOf with base schema", + "schema": { + "type": "string", + "oneOf" : [ + { + "minLength": 2 + }, + { + "maxLength": 4 + } + ] + }, + "tests": [ + { + "description": "mismatch base schema", + "data": 3, + "valid": false + }, + { + "description": "one oneOf valid", + "data": "foobar", + "valid": true + }, + { + "description": "both oneOf valid", + "data": "foo", + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/pattern.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/pattern.json new file mode 100644 index 0000000..befc4b5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/pattern.json @@ -0,0 +1,23 @@ +[ + { + "description": "pattern validation", + "schema": {"pattern": "^a*$"}, + "tests": [ + { + "description": "a matching pattern is valid", + "data": "aaa", + "valid": true + }, + { + "description": "a non-matching pattern is invalid", + "data": "abc", + "valid": false + }, + { + "description": "ignores non-strings", + "data": true, + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/patternProperties.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/patternProperties.json new file mode 100644 index 0000000..18586e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/patternProperties.json @@ -0,0 +1,110 @@ +[ + { + "description": + "patternProperties validates properties matching a regex", + "schema": { + "patternProperties": { + "f.*o": {"type": "integer"} + } + }, + "tests": [ + { + "description": "a single valid match is valid", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "multiple valid matches is valid", + "data": {"foo": 1, "foooooo" : 2}, + "valid": true + }, + { + "description": "a single invalid match is invalid", + "data": {"foo": "bar", "fooooo": 2}, + "valid": false + }, + { + "description": "multiple invalid matches is invalid", + "data": {"foo": "bar", "foooooo" : "baz"}, + "valid": false + }, + { + "description": "ignores non-objects", + "data": 12, + "valid": true + } + ] + }, + { + "description": "multiple simultaneous patternProperties are validated", + "schema": { + "patternProperties": { + "a*": {"type": "integer"}, + "aaa*": {"maximum": 20} + } + }, + "tests": [ + { + "description": "a single valid match is valid", + "data": {"a": 21}, + "valid": true + }, + { + "description": "a simultaneous match is valid", + "data": {"aaaa": 18}, + "valid": true + }, + { + "description": "multiple matches is valid", + "data": {"a": 21, "aaaa": 18}, + "valid": true + }, + { + "description": "an invalid due to one is invalid", + "data": {"a": "bar"}, + "valid": false + }, + { + "description": "an invalid due to the other is invalid", + "data": {"aaaa": 31}, + "valid": false + }, + { + "description": "an invalid due to both is invalid", + "data": {"aaa": "foo", "aaaa": 31}, + "valid": false + } + ] + }, + { + "description": "regexes are not anchored by default and are case sensitive", + "schema": { + "patternProperties": { + "[0-9]{2,}": { "type": "boolean" }, + "X_": { "type": "string" } + } + }, + "tests": [ + { + "description": "non recognized members are ignored", + "data": { "answer 1": "42" }, + "valid": true + }, + { + "description": "recognized members are accounted for", + "data": { "a31b": null }, + "valid": false + }, + { + "description": "regexes are case sensitive", + "data": { "a_x_3": 3 }, + "valid": true + }, + { + "description": "regexes are case sensitive, 2", + "data": { "a_X_3": 3 }, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/properties.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/properties.json new file mode 100644 index 0000000..cd1644d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/properties.json @@ -0,0 +1,92 @@ +[ + { + "description": "object properties validation", + "schema": { + "properties": { + "foo": {"type": "integer"}, + "bar": {"type": "string"} + } + }, + "tests": [ + { + "description": "both properties present and valid is valid", + "data": {"foo": 1, "bar": "baz"}, + "valid": true + }, + { + "description": "one property invalid is invalid", + "data": {"foo": 1, "bar": {}}, + "valid": false + }, + { + "description": "both properties invalid is invalid", + "data": {"foo": [], "bar": {}}, + "valid": false + }, + { + "description": "doesn't invalidate other properties", + "data": {"quux": []}, + "valid": true + }, + { + "description": "ignores non-objects", + "data": [], + "valid": true + } + ] + }, + { + "description": + "properties, patternProperties, additionalProperties interaction", + "schema": { + "properties": { + "foo": {"type": "array", "maxItems": 3}, + "bar": {"type": "array"} + }, + "patternProperties": {"f.o": {"minItems": 2}}, + "additionalProperties": {"type": "integer"} + }, + "tests": [ + { + "description": "property validates property", + "data": {"foo": [1, 2]}, + "valid": true + }, + { + "description": "property invalidates property", + "data": {"foo": [1, 2, 3, 4]}, + "valid": false + }, + { + "description": "patternProperty invalidates property", + "data": {"foo": []}, + "valid": false + }, + { + "description": "patternProperty validates nonproperty", + "data": {"fxo": [1, 2]}, + "valid": true + }, + { + "description": "patternProperty invalidates nonproperty", + "data": {"fxo": []}, + "valid": false + }, + { + "description": "additionalProperty ignores property", + "data": {"bar": []}, + "valid": true + }, + { + "description": "additionalProperty validates others", + "data": {"quux": 3}, + "valid": true + }, + { + "description": "additionalProperty invalidates others", + "data": {"quux": "foo"}, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/ref.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/ref.json new file mode 100644 index 0000000..d8214bc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/ref.json @@ -0,0 +1,128 @@ +[ + { + "description": "root pointer ref", + "schema": { + "properties": { + "foo": {"$ref": "#"} + }, + "additionalProperties": false + }, + "tests": [ + { + "description": "match", + "data": {"foo": false}, + "valid": true + }, + { + "description": "recursive match", + "data": {"foo": {"foo": false}}, + "valid": true + }, + { + "description": "mismatch", + "data": {"bar": false}, + "valid": false + }, + { + "description": "recursive mismatch", + "data": {"foo": {"bar": false}}, + "valid": false + } + ] + }, + { + "description": "relative pointer ref to object", + "schema": { + "properties": { + "foo": {"type": "integer"}, + "bar": {"$ref": "#/properties/foo"} + } + }, + "tests": [ + { + "description": "match", + "data": {"bar": 3}, + "valid": true + }, + { + "description": "mismatch", + "data": {"bar": true}, + "valid": false + } + ] + }, + { + "description": "relative pointer ref to array", + "schema": { + "items": [ + {"type": "integer"}, + {"$ref": "#/items/0"} + ] + }, + "tests": [ + { + "description": "match array", + "data": [1, 2], + "valid": true + }, + { + "description": "mismatch array", + "data": [1, "foo"], + "valid": false + } + ] + }, + { + "description": "escaped pointer ref", + "schema": { + "tilda~field": {"type": "integer"}, + "slash/field": {"type": "integer"}, + "percent%field": {"type": "integer"}, + "properties": { + "tilda": {"$ref": "#/tilda~0field"}, + "slash": {"$ref": "#/slash~1field"}, + "percent": {"$ref": "#/percent%25field"} + } + }, + "tests": [ + { + "description": "slash", + "data": {"slash": "aoeu"}, + "valid": false + }, + { + "description": "tilda", + "data": {"tilda": "aoeu"}, + "valid": false + }, + { + "description": "percent", + "data": {"percent": "aoeu"}, + "valid": false + } + ] + }, + { + "description": "nested refs", + "schema": { + "definitions": { + "a": {"type": "integer"}, + "b": {"$ref": "#/definitions/a"}, + "c": {"$ref": "#/definitions/b"} + }, + "$ref": "#/definitions/c" + }, + "tests": [ + { + "description": "nested ref valid", + "data": 5, + "valid": true + }, + { + "description": "nested ref invalid", + "data": "a", + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/refRemote.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/refRemote.json new file mode 100644 index 0000000..4ca8047 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/refRemote.json @@ -0,0 +1,74 @@ +[ + { + "description": "remote ref", + "schema": {"$ref": "http://localhost:1234/integer.json"}, + "tests": [ + { + "description": "remote ref valid", + "data": 1, + "valid": true + }, + { + "description": "remote ref invalid", + "data": "a", + "valid": false + } + ] + }, + { + "description": "fragment within remote ref", + "schema": {"$ref": "http://localhost:1234/subSchemas.json#/integer"}, + "tests": [ + { + "description": "remote fragment valid", + "data": 1, + "valid": true + }, + { + "description": "remote fragment invalid", + "data": "a", + "valid": false + } + ] + }, + { + "description": "ref within remote ref", + "schema": { + "$ref": "http://localhost:1234/subSchemas.json#/refToInteger" + }, + "tests": [ + { + "description": "ref within ref valid", + "data": 1, + "valid": true + }, + { + "description": "ref within ref invalid", + "data": "a", + "valid": false + } + ] + }, + { + "description": "change resolution scope", + "schema": { + "id": "http://localhost:1234/", + "items": { + "id": "folder/", + "items": {"$ref": "folderInteger.json"} + } + }, + "tests": [ + { + "description": "changed scope ref valid", + "data": [[1]], + "valid": true + }, + { + "description": "changed scope ref invalid", + "data": [["a"]], + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/required.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/required.json new file mode 100644 index 0000000..612f73f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/required.json @@ -0,0 +1,39 @@ +[ + { + "description": "required validation", + "schema": { + "properties": { + "foo": {}, + "bar": {} + }, + "required": ["foo"] + }, + "tests": [ + { + "description": "present required property is valid", + "data": {"foo": 1}, + "valid": true + }, + { + "description": "non-present required property is invalid", + "data": {"bar": 1}, + "valid": false + } + ] + }, + { + "description": "required default validation", + "schema": { + "properties": { + "foo": {} + } + }, + "tests": [ + { + "description": "not required by default", + "data": {}, + "valid": true + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/type.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/type.json new file mode 100644 index 0000000..257f051 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/type.json @@ -0,0 +1,330 @@ +[ + { + "description": "integer type matches integers", + "schema": {"type": "integer"}, + "tests": [ + { + "description": "an integer is an integer", + "data": 1, + "valid": true + }, + { + "description": "a float is not an integer", + "data": 1.1, + "valid": false + }, + { + "description": "a string is not an integer", + "data": "foo", + "valid": false + }, + { + "description": "an object is not an integer", + "data": {}, + "valid": false + }, + { + "description": "an array is not an integer", + "data": [], + "valid": false + }, + { + "description": "a boolean is not an integer", + "data": true, + "valid": false + }, + { + "description": "null is not an integer", + "data": null, + "valid": false + } + ] + }, + { + "description": "number type matches numbers", + "schema": {"type": "number"}, + "tests": [ + { + "description": "an integer is a number", + "data": 1, + "valid": true + }, + { + "description": "a float is a number", + "data": 1.1, + "valid": true + }, + { + "description": "a string is not a number", + "data": "foo", + "valid": false + }, + { + "description": "an object is not a number", + "data": {}, + "valid": false + }, + { + "description": "an array is not a number", + "data": [], + "valid": false + }, + { + "description": "a boolean is not a number", + "data": true, + "valid": false + }, + { + "description": "null is not a number", + "data": null, + "valid": false + } + ] + }, + { + "description": "string type matches strings", + "schema": {"type": "string"}, + "tests": [ + { + "description": "1 is not a string", + "data": 1, + "valid": false + }, + { + "description": "a float is not a string", + "data": 1.1, + "valid": false + }, + { + "description": "a string is a string", + "data": "foo", + "valid": true + }, + { + "description": "an object is not a string", + "data": {}, + "valid": false + }, + { + "description": "an array is not a string", + "data": [], + "valid": false + }, + { + "description": "a boolean is not a string", + "data": true, + "valid": false + }, + { + "description": "null is not a string", + "data": null, + "valid": false + } + ] + }, + { + "description": "object type matches objects", + "schema": {"type": "object"}, + "tests": [ + { + "description": "an integer is not an object", + "data": 1, + "valid": false + }, + { + "description": "a float is not an object", + "data": 1.1, + "valid": false + }, + { + "description": "a string is not an object", + "data": "foo", + "valid": false + }, + { + "description": "an object is an object", + "data": {}, + "valid": true + }, + { + "description": "an array is not an object", + "data": [], + "valid": false + }, + { + "description": "a boolean is not an object", + "data": true, + "valid": false + }, + { + "description": "null is not an object", + "data": null, + "valid": false + } + ] + }, + { + "description": "array type matches arrays", + "schema": {"type": "array"}, + "tests": [ + { + "description": "an integer is not an array", + "data": 1, + "valid": false + }, + { + "description": "a float is not an array", + "data": 1.1, + "valid": false + }, + { + "description": "a string is not an array", + "data": "foo", + "valid": false + }, + { + "description": "an object is not an array", + "data": {}, + "valid": false + }, + { + "description": "an array is not an array", + "data": [], + "valid": true + }, + { + "description": "a boolean is not an array", + "data": true, + "valid": false + }, + { + "description": "null is not an array", + "data": null, + "valid": false + } + ] + }, + { + "description": "boolean type matches booleans", + "schema": {"type": "boolean"}, + "tests": [ + { + "description": "an integer is not a boolean", + "data": 1, + "valid": false + }, + { + "description": "a float is not a boolean", + "data": 1.1, + "valid": false + }, + { + "description": "a string is not a boolean", + "data": "foo", + "valid": false + }, + { + "description": "an object is not a boolean", + "data": {}, + "valid": false + }, + { + "description": "an array is not a boolean", + "data": [], + "valid": false + }, + { + "description": "a boolean is not a boolean", + "data": true, + "valid": true + }, + { + "description": "null is not a boolean", + "data": null, + "valid": false + } + ] + }, + { + "description": "null type matches only the null object", + "schema": {"type": "null"}, + "tests": [ + { + "description": "an integer is not null", + "data": 1, + "valid": false + }, + { + "description": "a float is not null", + "data": 1.1, + "valid": false + }, + { + "description": "a string is not null", + "data": "foo", + "valid": false + }, + { + "description": "an object is not null", + "data": {}, + "valid": false + }, + { + "description": "an array is not null", + "data": [], + "valid": false + }, + { + "description": "a boolean is not null", + "data": true, + "valid": false + }, + { + "description": "null is null", + "data": null, + "valid": true + } + ] + }, + { + "description": "multiple types can be specified in an array", + "schema": {"type": ["integer", "string"]}, + "tests": [ + { + "description": "an integer is valid", + "data": 1, + "valid": true + }, + { + "description": "a string is valid", + "data": "foo", + "valid": true + }, + { + "description": "a float is invalid", + "data": 1.1, + "valid": false + }, + { + "description": "an object is invalid", + "data": {}, + "valid": false + }, + { + "description": "an array is invalid", + "data": [], + "valid": false + }, + { + "description": "a boolean is invalid", + "data": true, + "valid": false + }, + { + "description": "null is invalid", + "data": null, + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/uniqueItems.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/uniqueItems.json new file mode 100644 index 0000000..c1f4ab9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema-draft4/uniqueItems.json @@ -0,0 +1,79 @@ +[ + { + "description": "uniqueItems validation", + "schema": {"uniqueItems": true}, + "tests": [ + { + "description": "unique array of integers is valid", + "data": [1, 2], + "valid": true + }, + { + "description": "non-unique array of integers is invalid", + "data": [1, 1], + "valid": false + }, + { + "description": "numbers are unique if mathematically unequal", + "data": [1.0, 1.00, 1], + "valid": false + }, + { + "description": "unique array of objects is valid", + "data": [{"foo": "bar"}, {"foo": "baz"}], + "valid": true + }, + { + "description": "non-unique array of objects is invalid", + "data": [{"foo": "bar"}, {"foo": "bar"}], + "valid": false + }, + { + "description": "unique array of nested objects is valid", + "data": [ + {"foo": {"bar" : {"baz" : true}}}, + {"foo": {"bar" : {"baz" : false}}} + ], + "valid": true + }, + { + "description": "non-unique array of nested objects is invalid", + "data": [ + {"foo": {"bar" : {"baz" : true}}}, + {"foo": {"bar" : {"baz" : true}}} + ], + "valid": false + }, + { + "description": "unique array of arrays is valid", + "data": [["foo"], ["bar"]], + "valid": true + }, + { + "description": "non-unique array of arrays is invalid", + "data": [["foo"], ["foo"]], + "valid": false + }, + { + "description": "1 and true are unique", + "data": [1, true], + "valid": true + }, + { + "description": "0 and false are unique", + "data": [0, false], + "valid": true + }, + { + "description": "unique heterogeneous types are valid", + "data": [{}, [1], true, null, 1], + "valid": true + }, + { + "description": "non-unique heterogeneous types are invalid", + "data": [{}, [1], true, null, {}, 1], + "valid": false + } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema.js new file mode 100644 index 0000000..e68a263 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/json-schema.js @@ -0,0 +1,23 @@ +var tape = require('tape') +var fs = require('fs') +var validator = require('../') + +var files = fs.readdirSync(__dirname+'/json-schema-draft4') + .map(function(file) { + if (file === 'definitions.json') return null + if (file === 'refRemote.json') return null + return require('./json-schema-draft4/'+file) + }) + .filter(Boolean) + +files.forEach(function(file) { + file.forEach(function(f) { + tape('json-schema-test-suite '+f.description, function(t) { + var validate = validator(f.schema) + f.tests.forEach(function(test) { + t.same(validate(test.data), test.valid, test.description) + }) + t.end() + }) + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/misc.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/misc.js new file mode 100644 index 0000000..b5109e5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/test/misc.js @@ -0,0 +1,429 @@ +var tape = require('tape') +var cosmic = require('./fixtures/cosmic') +var validator = require('../') +var validatorRequire = require('../require') + +tape('simple', function(t) { + var schema = { + required: true, + type: 'object', + properties: { + hello: {type:'string', required:true} + } + } + + var validate = validator(schema) + + t.ok(validate({hello: 'world'}), 'should be valid') + t.notOk(validate(), 'should be invalid') + t.notOk(validate({}), 'should be invalid') + t.end() +}) + +tape('advanced', function(t) { + var validate = validator(cosmic.schema) + + t.ok(validate(cosmic.valid), 'should be valid') + t.notOk(validate(cosmic.invalid), 'should be invalid') + t.end() +}) + +tape('greedy/false', function(t) { + var validate = validator({ + type: 'object', + properties: { + x: { + type: 'number' + } + }, + required: ['x', 'y'] + }); + t.notOk(validate({}), 'should be invalid') + t.strictEqual(validate.errors.length, 2); + t.strictEqual(validate.errors[0].field, 'data.x') + t.strictEqual(validate.errors[0].message, 'is required') + t.strictEqual(validate.errors[1].field, 'data.y') + t.strictEqual(validate.errors[1].message, 'is required') + t.notOk(validate({x: 'string'}), 'should be invalid') + t.strictEqual(validate.errors.length, 1); + t.strictEqual(validate.errors[0].field, 'data.y') + t.strictEqual(validate.errors[0].message, 'is required') + t.notOk(validate({x: 'string', y: 'value'}), 'should be invalid') + t.strictEqual(validate.errors.length, 1); + t.strictEqual(validate.errors[0].field, 'data.x') + t.strictEqual(validate.errors[0].message, 'is the wrong type') + t.end(); +}); + +tape('greedy/true', function(t) { + var validate = validator({ + type: 'object', + properties: { + x: { + type: 'number' + } + }, + required: ['x', 'y'] + }, { + greedy: true + }); + t.notOk(validate({}), 'should be invalid') + t.strictEqual(validate.errors.length, 2); + t.strictEqual(validate.errors[0].field, 'data.x') + t.strictEqual(validate.errors[0].message, 'is required') + t.strictEqual(validate.errors[1].field, 'data.y') + t.strictEqual(validate.errors[1].message, 'is required') + t.notOk(validate({x: 'string'}), 'should be invalid') + t.strictEqual(validate.errors.length, 2); + t.strictEqual(validate.errors[0].field, 'data.y') + t.strictEqual(validate.errors[0].message, 'is required') + t.strictEqual(validate.errors[1].field, 'data.x') + t.strictEqual(validate.errors[1].message, 'is the wrong type') + t.notOk(validate({x: 'string', y: 'value'}), 'should be invalid') + t.strictEqual(validate.errors.length, 1); + t.strictEqual(validate.errors[0].field, 'data.x') + t.strictEqual(validate.errors[0].message, 'is the wrong type') + t.ok(validate({x: 1, y: 'value'}), 'should be invalid') + t.end(); +}); + +tape('additional props', function(t) { + var validate = validator({ + type: 'object', + additionalProperties: false + }, { + verbose: true + }) + + t.ok(validate({})) + t.notOk(validate({foo:'bar'})) + t.ok(validate.errors[0].value === 'data.foo', 'should output the property not allowed in verbose mode') + t.end() +}) + +tape('array', function(t) { + var validate = validator({ + type: 'array', + required: true, + items: { + type: 'string' + } + }) + + t.notOk(validate({}), 'wrong type') + t.notOk(validate(), 'is required') + t.ok(validate(['test'])) + t.end() +}) + +tape('nested array', function(t) { + var validate = validator({ + type: 'object', + properties: { + list: { + type: 'array', + required: true, + items: { + type: 'string' + } + } + } + }) + + t.notOk(validate({}), 'is required') + t.ok(validate({list:['test']})) + t.notOk(validate({list:[1]})) + t.end() +}) + +tape('enum', function(t) { + var validate = validator({ + type: 'object', + properties: { + foo: { + type: 'number', + required: true, + enum: [42] + } + } + }) + + t.notOk(validate({}), 'is required') + t.ok(validate({foo:42})) + t.notOk(validate({foo:43})) + t.end() +}) + +tape('minimum/maximum', function(t) { + var validate = validator({ + type: 'object', + properties: { + foo: { + type: 'number', + minimum: 0, + maximum: 0 + } + } + }) + + t.notOk(validate({foo:-42})) + t.ok(validate({foo:0})) + t.notOk(validate({foo:42})) + t.end() +}) + +tape('exclusiveMinimum/exclusiveMaximum', function(t) { + var validate = validator({ + type: 'object', + properties: { + foo: { + type: 'number', + minimum: 10, + maximum: 20, + exclusiveMinimum: true, + exclusiveMaximum: true + } + } + }) + + t.notOk(validate({foo:10})) + t.ok(validate({foo:11})) + t.notOk(validate({foo:20})) + t.ok(validate({foo:19})) + t.end() +}) + +tape('custom format', function(t) { + var validate = validator({ + type: 'object', + properties: { + foo: { + type: 'string', + format: 'as' + } + } + }, {formats: {as:/^a+$/}}) + + t.notOk(validate({foo:''}), 'not as') + t.notOk(validate({foo:'b'}), 'not as') + t.notOk(validate({foo:'aaab'}), 'not as') + t.ok(validate({foo:'a'}), 'as') + t.ok(validate({foo:'aaaaaa'}), 'as') + t.end() +}) + +tape('custom format function', function(t) { + var validate = validator({ + type: 'object', + properties: { + foo: { + type: 'string', + format: 'as' + } + } + }, {formats: {as:function(s) { return /^a+$/.test(s) } }}) + + t.notOk(validate({foo:''}), 'not as') + t.notOk(validate({foo:'b'}), 'not as') + t.notOk(validate({foo:'aaab'}), 'not as') + t.ok(validate({foo:'a'}), 'as') + t.ok(validate({foo:'aaaaaa'}), 'as') + t.end() +}) + +tape('do not mutate schema', function(t) { + var sch = { + items: [ + {} + ], + additionalItems: { + type: 'integer' + } + } + + var copy = JSON.parse(JSON.stringify(sch)) + + validator(sch) + + t.same(sch, copy, 'did not mutate') + t.end() +}) + +tape('#toJSON()', function(t) { + var schema = { + required: true, + type: 'object', + properties: { + hello: {type:'string', required:true} + } + } + + var validate = validator(schema) + + t.deepEqual(validate.toJSON(), schema, 'should return original schema') + t.end() +}) + +tape('external schemas', function(t) { + var ext = {type: 'string'} + var schema = { + required: true, + $ref: '#ext' + } + + var validate = validator(schema, {schemas: {ext:ext}}) + + t.ok(validate('hello string'), 'is a string') + t.notOk(validate(42), 'not a string') + t.end() +}) + +tape('top-level external schema', function(t) { + var defs = { + "string": { + type: "string" + }, + "sex": { + type: "string", + enum: ["male", "female", "other"] + } + } + var schema = { + type: "object", + properties: { + "name": { $ref: "definitions.json#/string" }, + "sex": { $ref: "definitions.json#/sex" } + }, + required: ["name", "sex"] + } + + var validate = validator(schema, { + schemas: { + "definitions.json": defs + } + }) + t.ok(validate({name:"alice", sex:"female"}), 'is an object') + t.notOk(validate({name:"alice", sex: "bob"}), 'recognizes external schema') + t.notOk(validate({name:2, sex: "female"}), 'recognizes external schema') + t.end() +}) + +tape('nested required array decl', function(t) { + var schema = { + properties: { + x: { + type: 'object', + properties: { + y: { + type: 'object', + properties: { + z: { + type: 'string' + } + }, + required: ['z'] + } + } + } + }, + required: ['x'] + } + + var validate = validator(schema) + + t.ok(validate({x: {}}), 'should be valid') + t.notOk(validate({}), 'should not be valid') + t.strictEqual(validate.errors[0].field, 'data.x', 'should output the missing field') + t.end() +}) + +tape('verbose mode', function(t) { + var schema = { + required: true, + type: 'object', + properties: { + hello: { + required: true, + type: 'string' + } + } + }; + + var validate = validator(schema, {verbose: true}) + + t.ok(validate({hello: 'string'}), 'should be valid') + t.notOk(validate({hello: 100}), 'should not be valid') + t.strictEqual(validate.errors[0].value, 100, 'error object should contain the invalid value') + t.end() +}) + +tape('additional props in verbose mode', function(t) { + var schema = { + type: 'object', + required: true, + additionalProperties: false, + properties: { + foo: { + type: 'string' + }, + 'hello world': { + type: 'object', + required: true, + additionalProperties: false, + properties: { + foo: { + type: 'string' + } + } + } + } + }; + + var validate = validator(schema, {verbose: true}) + + validate({'hello world': {bar: 'string'}}); + + t.strictEqual(validate.errors[0].value, 'data["hello world"].bar', 'should output the path to the additional prop in the error') + t.end() +}) + +tape('Date.now() is an integer', function(t) { + var schema = {type: 'integer'} + var validate = validator(schema) + + t.ok(validate(Date.now()), 'is integer') + t.end() +}) + +tape('field shows item index in arrays', function(t) { + var schema = { + type: 'array', + items: { + type: 'array', + items: { + properties: { + foo: { + type: 'string', + required: true + } + } + } + } + } + + var validate = validator(schema) + + validate([ + [ + { foo: 'test' }, + { foo: 'test' } + ], + [ + { foo: 'test' }, + { baz: 'test' } + ] + ]) + + t.strictEqual(validate.errors[0].field, 'data.1.1.foo', 'should output the field with specific index of failing item in the error') + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/package.json new file mode 100644 index 0000000..8255961 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/package.json @@ -0,0 +1,84 @@ +{ + "version": "1.7.1", + "name": "har-validator", + "description": "Extremely fast HTTP Archive (HAR) validator using JSON Schema", + "author": { + "name": "Ahmad Nassri", + "email": "ahmad@ahmadnassri.com", + "url": "https://www.ahmadnassri.com/" + }, + "homepage": "https://github.com/ahmadnassri/har-validator", + "repository": { + "type": "git", + "url": "https://github.com/ahmadnassri/har-validator" + }, + "license": "MIT", + "main": "./src/index.js", + "bin": { + "har-validator": "./bin/har-validator" + }, + "keywords": [ + "har", + "http", + "archive", + "validate", + "validator" + ], + "engines": { + "node": ">=0.10" + }, + "files": [ + "bin", + "src" + ], + "bugs": { + "url": "https://github.com/ahmadnassri/har-validator/issues" + }, + "scripts": { + "test": "standard && echint && mocha --reporter spec", + "coverage": "istanbul cover ./node_modules/mocha/bin/_mocha", + "codeclimate": "codeclimate < coverage/lcov.info" + }, + "echint": { + "ignore": [ + "coverage/**" + ] + }, + "devDependencies": { + "codeclimate-test-reporter": "0.0.4", + "echint": "^1.1.0", + "istanbul": "^0.3.14", + "mocha": "^2.2.5", + "require-directory": "^2.1.0", + "should": "^6.0.3", + "standard": "^3.11.1" + }, + "dependencies": { + "bluebird": "^2.9.26", + "chalk": "^1.0.0", + "commander": "^2.8.1", + "is-my-json-valid": "^2.12.0" + }, + "gitHead": "328d7f2f37affcc4fca1db13da68f2be817ad31c", + "_id": "har-validator@1.7.1", + "_shasum": "8ec8952f8287d21b451ba3e36f27ed8d997d8a95", + "_from": "har-validator@>=1.6.1 <2.0.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "ahmadnassri", + "email": "ahmad@ahmadnassri.com" + }, + "maintainers": [ + { + "name": "ahmadnassri", + "email": "ahmad@ahmadnassri.com" + } + ], + "dist": { + "shasum": "8ec8952f8287d21b451ba3e36f27ed8d997d8a95", + "tarball": "http://registry.npmjs.org/har-validator/-/har-validator-1.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/har-validator/-/har-validator-1.7.1.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/error.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/error.js new file mode 100644 index 0000000..fc08a87 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/error.js @@ -0,0 +1,10 @@ +'use strict' + +function ValidationError (errors) { + this.name = 'ValidationError' + this.errors = errors +} + +ValidationError.prototype = Error.prototype + +module.exports = ValidationError diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/index.js new file mode 100644 index 0000000..d0324cc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/index.js @@ -0,0 +1,39 @@ +'use strict' + +var schemas = require('./schemas') +var ValidationError = require('./error') +var validator = require('is-my-json-valid') + +var runner = function (schema, data, cb) { + var validate = validator(schema, { + greedy: true, + verbose: true, + schemas: schemas + }) + + var valid = false + + if (data !== undefined) { + // execute is-my-json-valid + valid = validate(data) + } + + // callback? + if (!cb) { + return !validate.errors > 0 + } else { + return cb(validate.errors ? new ValidationError(validate.errors) : null, valid) + } + + return valid +} + +module.exports = function (data, cb) { + return runner(schemas.har, data, cb) +} + +Object.keys(schemas).map(function (name) { + module.exports[name] = function (data, cb) { + return runner(schemas[name], data, cb) + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cache.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cache.json new file mode 100644 index 0000000..a3ab682 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cache.json @@ -0,0 +1,13 @@ +{ + "properties": { + "beforeRequest": { + "$ref": "#cacheEntry" + }, + "afterRequest": { + "$ref": "#cacheEntry" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cacheEntry.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cacheEntry.json new file mode 100644 index 0000000..a397439 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cacheEntry.json @@ -0,0 +1,31 @@ +{ + "oneOf": [{ + "type": "object", + "optional": true, + "required": [ + "lastAccess", + "eTag", + "hitCount" + ], + "properties": { + "expires": { + "type": "string" + }, + "lastAccess": { + "type": "string" + }, + "eTag": { + "type": "string" + }, + "hitCount": { + "type": "integer" + }, + "comment": { + "type": "string" + } + } + }, { + "type": null, + "additionalProperties": false + }] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/content.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/content.json new file mode 100644 index 0000000..3710d79 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/content.json @@ -0,0 +1,27 @@ +{ + "type": "object", + "required": [ + "size", + "mimeType" + ], + "properties": { + "size": { + "type": "integer" + }, + "compression": { + "type": "integer" + }, + "mimeType": { + "type": "string" + }, + "text": { + "type": "string" + }, + "encoding": { + "type": "string" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cookie.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cookie.json new file mode 100644 index 0000000..5768181 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/cookie.json @@ -0,0 +1,34 @@ +{ + "type": "object", + "required": [ + "name", + "value" + ], + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "string" + }, + "path": { + "type": "string" + }, + "domain": { + "type": "string" + }, + "expires": { + "type": ["string", "null"], + "format": "date-time" + }, + "httpOnly": { + "type": "boolean" + }, + "secure": { + "type": "boolean" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/creator.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/creator.json new file mode 100644 index 0000000..5058600 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/creator.json @@ -0,0 +1,18 @@ +{ + "type": "object", + "required": [ + "name", + "version" + ], + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/entry.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/entry.json new file mode 100644 index 0000000..7acdc1b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/entry.json @@ -0,0 +1,48 @@ +{ + "type": "object", + "optional": true, + "required": [ + "startedDateTime", + "time", + "request", + "response", + "cache", + "timings" + ], + "properties": { + "pageref": { + "type": "string" + }, + "startedDateTime": { + "type": "string", + "format": "date-time", + "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))" + }, + "time": { + "type": "number", + "min": 0 + }, + "request": { + "$ref": "#request" + }, + "response": { + "$ref": "#response" + }, + "cache": { + "$ref": "#cache" + }, + "timings": { + "$ref": "#timings" + }, + "serverIPAddress": { + "type": "string", + "format": "ipv4" + }, + "connection": { + "type": "string" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/har.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/har.json new file mode 100644 index 0000000..b542782 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/har.json @@ -0,0 +1,11 @@ +{ + "type": "object", + "required": [ + "log" + ], + "properties": { + "log": { + "$ref": "#log" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/index.js new file mode 100644 index 0000000..7b6db7d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/index.js @@ -0,0 +1,49 @@ +'use strict' + +var schemas = { + cache: require('./cache.json'), + cacheEntry: require('./cacheEntry.json'), + content: require('./content.json'), + cookie: require('./cookie.json'), + creator: require('./creator.json'), + entry: require('./entry.json'), + har: require('./har.json'), + log: require('./log.json'), + page: require('./page.json'), + pageTimings: require('./pageTimings.json'), + postData: require('./postData.json'), + record: require('./record.json'), + request: require('./request.json'), + response: require('./response.json'), + timings: require('./timings.json') +} + +// is-my-json-valid does not provide meaningful error messages for external schemas +// this is a workaround +schemas.cache.properties.beforeRequest = schemas.cacheEntry +schemas.cache.properties.afterRequest = schemas.cacheEntry + +schemas.page.properties.pageTimings = schemas.pageTimings + +schemas.request.properties.cookies.items = schemas.cookie +schemas.request.properties.headers.items = schemas.record +schemas.request.properties.queryString.items = schemas.record +schemas.request.properties.postData = schemas.postData + +schemas.response.properties.cookies.items = schemas.cookie +schemas.response.properties.headers.items = schemas.record +schemas.response.properties.content = schemas.content + +schemas.entry.properties.request = schemas.request +schemas.entry.properties.response = schemas.response +schemas.entry.properties.cache = schemas.cache +schemas.entry.properties.timings = schemas.timings + +schemas.log.properties.creator = schemas.creator +schemas.log.properties.browser = schemas.creator +schemas.log.properties.pages.items = schemas.page +schemas.log.properties.entries.items = schemas.entry + +schemas.har.properties.log = schemas.log + +module.exports = schemas diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/log.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/log.json new file mode 100644 index 0000000..0c91d38 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/log.json @@ -0,0 +1,34 @@ +{ + "type": "object", + "required": [ + "version", + "creator", + "entries" + ], + "properties": { + "version": { + "type": "string" + }, + "creator": { + "$ref": "#creator" + }, + "browser": { + "$ref": "#creator" + }, + "pages": { + "type": "array", + "items": { + "$ref": "#page" + } + }, + "entries": { + "type": "array", + "items": { + "$ref": "#entry" + } + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/page.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/page.json new file mode 100644 index 0000000..ef64abe --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/page.json @@ -0,0 +1,30 @@ +{ + "type": "object", + "optional": true, + "required": [ + "startedDateTime", + "id", + "title", + "pageTimings" + ], + "properties": { + "startedDateTime": { + "type": "string", + "format": "date-time", + "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))" + }, + "id": { + "type": "string", + "unique": true + }, + "title": { + "type": "string" + }, + "pageTimings": { + "$ref": "#pageTimings" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/pageTimings.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/pageTimings.json new file mode 100644 index 0000000..adc83cc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/pageTimings.json @@ -0,0 +1,16 @@ +{ + "type": "object", + "properties": { + "onContentLoad": { + "type": "number", + "min": -1 + }, + "onLoad": { + "type": "number", + "min": -1 + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/postData.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/postData.json new file mode 100644 index 0000000..91958b6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/postData.json @@ -0,0 +1,41 @@ +{ + "type": "object", + "optional": true, + "required": [ + "mimeType" + ], + "properties": { + "mimeType": { + "type": "string" + }, + "text": { + "type": "string" + }, + "params": { + "type": "array", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "string" + }, + "fileName": { + "type": "string" + }, + "contentType": { + "type": "string" + }, + "comment": { + "type": "string" + } + } + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/record.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/record.json new file mode 100644 index 0000000..04acd51 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/record.json @@ -0,0 +1,18 @@ +{ + "type": "object", + "required": [ + "name", + "value" + ], + "properties": { + "name": { + "type": "string" + }, + "value": { + "type": "string" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/request.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/request.json new file mode 100644 index 0000000..639af06 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/request.json @@ -0,0 +1,55 @@ +{ + "type": "object", + "required": [ + "method", + "url", + "httpVersion", + "cookies", + "headers", + "queryString", + "headersSize", + "bodySize" + ], + "properties": { + "method": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + }, + "httpVersion": { + "type": "string" + }, + "cookies": { + "type": "array", + "items": { + "$ref": "#cookie" + } + }, + "headers": { + "type": "array", + "items": { + "$ref": "#record" + } + }, + "queryString": { + "type": "array", + "items": { + "$ref": "#record" + } + }, + "postData": { + "$ref": "#postData" + }, + "headersSize": { + "type": "integer" + }, + "bodySize": { + "type": "integer" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/response.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/response.json new file mode 100644 index 0000000..de99c55 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/response.json @@ -0,0 +1,52 @@ +{ + "type": "object", + "required": [ + "status", + "statusText", + "httpVersion", + "cookies", + "headers", + "content", + "redirectURL", + "headersSize", + "bodySize" + ], + "properties": { + "status": { + "type": "integer" + }, + "statusText": { + "type": "string" + }, + "httpVersion": { + "type": "string" + }, + "cookies": { + "type": "array", + "items": { + "$ref": "#cookie" + } + }, + "headers": { + "type": "array", + "items": { + "$ref": "#record" + } + }, + "content": { + "$ref": "#content" + }, + "redirectURL": { + "type": "string" + }, + "headersSize": { + "type": "integer" + }, + "bodySize": { + "type": "integer" + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/timings.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/timings.json new file mode 100644 index 0000000..066ef71 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/har-validator/src/schemas/timings.json @@ -0,0 +1,40 @@ +{ + "required": [ + "send", + "wait", + "receive" + ], + "properties": { + "dns": { + "type": "number", + "min": -1 + }, + "connect": { + "type": "number", + "min": -1 + }, + "blocked": { + "type": "number", + "min": -1 + }, + "send": { + "type": "number", + "min": -1 + }, + "wait": { + "type": "number", + "min": -1 + }, + "receive": { + "type": "number", + "min": -1 + }, + "ssl": { + "type": "number", + "min": -1 + }, + "comment": { + "type": "string" + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.npmignore new file mode 100644 index 0000000..70febc0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.npmignore @@ -0,0 +1,20 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +components +build +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.travis.yml new file mode 100755 index 0000000..047f7e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/.travis.yml @@ -0,0 +1,5 @@ +language: node_js + +node_js: + - 0.10 + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/LICENSE new file mode 100755 index 0000000..7880936 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2012-2014, Eran Hammer and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hueniverse/hawk/graphs/contributors diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/Makefile new file mode 100755 index 0000000..b102d5a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/Makefile @@ -0,0 +1,8 @@ +test: + @node node_modules/lab/bin/lab -a code +test-cov: + @node node_modules/lab/bin/lab -a code -t 100 +test-cov-html: + @node node_modules/lab/bin/lab -a code -r html -o coverage.html + +.PHONY: test test-cov test-cov-html diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/README.md new file mode 100755 index 0000000..0bcd287 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/hawk/README.md @@ -0,0 +1,635 @@ +![hawk Logo](https://raw.github.com/hueniverse/hawk/master/images/hawk.png) + + **Hawk** is an HTTP authentication scheme using a message authentication code (MAC) algorithm to provide partial +HTTP request cryptographic verification. For more complex use cases such as access delegation, see [Oz](https://github.com/hueniverse/oz). + +Current version: **2.3** + +Note: 2.x is the same exact protocol as 1.1. The version increment reflects a change in the internal error format +used by the module and used by the node API. + +[![Build Status](https://secure.travis-ci.org/hueniverse/hawk.png)](http://travis-ci.org/hueniverse/hawk) + +# Table of Content + +- [**Introduction**](#introduction) + - [Replay Protection](#replay-protection) + - [Usage Example](#usage-example) + - [Protocol Example](#protocol-example) + - [Payload Validation](#payload-validation) + - [Response Payload Validation](#response-payload-validation) + - [Browser Support and Considerations](#browser-support-and-considerations) +

+- [**Single URI Authorization**](#single-uri-authorization) + - [Usage Example](#bewit-usage-example) +

+- [**Security Considerations**](#security-considerations) + - [MAC Keys Transmission](#mac-keys-transmission) + - [Confidentiality of Requests](#confidentiality-of-requests) + - [Spoofing by Counterfeit Servers](#spoofing-by-counterfeit-servers) + - [Plaintext Storage of Credentials](#plaintext-storage-of-credentials) + - [Entropy of Keys](#entropy-of-keys) + - [Coverage Limitations](#coverage-limitations) + - [Future Time Manipulation](#future-time-manipulation) + - [Client Clock Poisoning](#client-clock-poisoning) + - [Bewit Limitations](#bewit-limitations) + - [Host Header Forgery](#host-header-forgery) +

+- [**Frequently Asked Questions**](#frequently-asked-questions) +

+- [**Implementations**](#implementations) +- [**Acknowledgements**](#acknowledgements) + +# Introduction + +**Hawk** is an HTTP authentication scheme providing mechanisms for making authenticated HTTP requests with +partial cryptographic verification of the request and response, covering the HTTP method, request URI, host, +and optionally the request payload. + +Similar to the HTTP [Digest access authentication schemes](http://www.ietf.org/rfc/rfc2617.txt), **Hawk** uses a set of +client credentials which include an identifier (e.g. username) and key (e.g. password). Likewise, just as with the Digest scheme, +the key is never included in authenticated requests. Instead, it is used to calculate a request MAC value which is +included in its place. + +However, **Hawk** has several differences from Digest. In particular, while both use a nonce to limit the possibility of +replay attacks, in **Hawk** the client generates the nonce and uses it in combination with a timestamp, leading to less +"chattiness" (interaction with the server). + +Also unlike Digest, this scheme is not intended to protect the key itself (the password in Digest) because +the client and server must both have access to the key material in the clear. + +The primary design goals of this scheme are to: +* simplify and improve HTTP authentication for services that are unwilling or unable to deploy TLS for all resources, +* secure credentials against leakage (e.g., when the client uses some form of dynamic configuration to determine where + to send an authenticated request), and +* avoid the exposure of credentials sent to a malicious server over an unauthenticated secure channel due to client + failure to validate the server's identity as part of its TLS handshake. + +In addition, **Hawk** supports a method for granting third-parties temporary access to individual resources using +a query parameter called _bewit_ (in falconry, a leather strap used to attach a tracking device to the leg of a hawk). + +The **Hawk** scheme requires the establishment of a shared symmetric key between the client and the server, +which is beyond the scope of this module. Typically, the shared credentials are established via an initial +TLS-protected phase or derived from some other shared confidential information available to both the client +and the server. + + +## Replay Protection + +Without replay protection, an attacker can use a compromised (but otherwise valid and authenticated) request more +than once, gaining access to a protected resource. To mitigate this, clients include both a nonce and a timestamp when +making requests. This gives the server enough information to prevent replay attacks. + +The nonce is generated by the client, and is a string unique across all requests with the same timestamp and +key identifier combination. + +The timestamp enables the server to restrict the validity period of the credentials where requests occuring afterwards +are rejected. It also removes the need for the server to retain an unbounded number of nonce values for future checks. +By default, **Hawk** uses a time window of 1 minute to allow for time skew between the client and server (which in +practice translates to a maximum of 2 minutes as the skew can be positive or negative). + +Using a timestamp requires the client's clock to be in sync with the server's clock. **Hawk** requires both the client +clock and the server clock to use NTP to ensure synchronization. However, given the limitations of some client types +(e.g. browsers) to deploy NTP, the server provides the client with its current time (in seconds precision) in response +to a bad timestamp. + +There is no expectation that the client will adjust its system clock to match the server (in fact, this would be a +potential attack vector). Instead, the client only uses the server's time to calculate an offset used only +for communications with that particular server. The protocol rewards clients with synchronized clocks by reducing +the number of round trips required to authenticate the first request. + + +## Usage Example + +Server code: + +```javascript +var Http = require('http'); +var Hawk = require('hawk'); + + +// Credentials lookup function + +var credentialsFunc = function (id, callback) { + + var credentials = { + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'Steve' + }; + + return callback(null, credentials); +}; + +// Create HTTP server + +var handler = function (req, res) { + + // Authenticate incoming request + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + // Prepare response + + var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!'); + var headers = { 'Content-Type': 'text/plain' }; + + // Generate Server-Authorization response header + + var header = Hawk.server.header(credentials, artifacts, { payload: payload, contentType: headers['Content-Type'] }); + headers['Server-Authorization'] = header; + + // Send the response back + + res.writeHead(!err ? 200 : 401, headers); + res.end(payload); + }); +}; + +// Start server + +Http.createServer(handler).listen(8000, 'example.com'); +``` + +Client code: + +```javascript +var Request = require('request'); +var Hawk = require('hawk'); + + +// Client credentials + +var credentials = { + id: 'dh37fgj492je', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256' +} + +// Request options + +var requestOptions = { + uri: 'http://example.com:8000/resource/1?b=1&a=2', + method: 'GET', + headers: {} +}; + +// Generate Authorization request header + +var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'some-app-data' }); +requestOptions.headers.Authorization = header.field; + +// Send authenticated request + +Request(requestOptions, function (error, response, body) { + + // Authenticate the server's response + + var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body }); + + // Output results + + console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)')); +}); +``` + +**Hawk** utilized the [**SNTP**](https://github.com/hueniverse/sntp) module for time sync management. By default, the local +machine time is used. To automatically retrieve and synchronice the clock within the application, use the SNTP 'start()' method. + +```javascript +Hawk.sntp.start(); +``` + + +## Protocol Example + +The client attempts to access a protected resource without authentication, sending the following HTTP request to +the resource server: + +``` +GET /resource/1?b=1&a=2 HTTP/1.1 +Host: example.com:8000 +``` + +The resource server returns an authentication challenge. + +``` +HTTP/1.1 401 Unauthorized +WWW-Authenticate: Hawk +``` + +The client has previously obtained a set of **Hawk** credentials for accessing resources on the "http://example.com/" +server. The **Hawk** credentials issued to the client include the following attributes: + +* Key identifier: dh37fgj492je +* Key: werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn +* Algorithm: sha256 + +The client generates the authentication header by calculating a timestamp (e.g. the number of seconds since January 1, +1970 00:00:00 GMT), generating a nonce, and constructing the normalized request string (each value followed by a newline +character): + +``` +hawk.1.header +1353832234 +j4h3g2 +GET +/resource/1?b=1&a=2 +example.com +8000 + +some-app-ext-data + +``` + +The request MAC is calculated using HMAC with the specified hash algorithm "sha256" and the key over the normalized request string. +The result is base64-encoded to produce the request MAC: + +``` +6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE= +``` + +The client includes the **Hawk** key identifier, timestamp, nonce, application specific data, and request MAC with the request using +the HTTP `Authorization` request header field: + +``` +GET /resource/1?b=1&a=2 HTTP/1.1 +Host: example.com:8000 +Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=" +``` + +The server validates the request by calculating the request MAC again based on the request received and verifies the validity +and scope of the **Hawk** credentials. If valid, the server responds with the requested resource. + + +### Payload Validation + +**Hawk** provides optional payload validation. When generating the authentication header, the client calculates a payload hash +using the specified hash algorithm. The hash is calculated over the concatenated value of (each followed by a newline character): +* `hawk.1.payload` +* the content-type in lowercase, without any parameters (e.g. `application/json`) +* the request payload prior to any content encoding (the exact representation requirements should be specified by the server for payloads other than simple single-part ascii to ensure interoperability) + +For example: + +* Payload: `Thank you for flying Hawk` +* Content Type: `text/plain` +* Hash (sha256): `Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=` + +Results in the following input to the payload hash function (newline terminated values): + +``` +hawk.1.payload +text/plain +Thank you for flying Hawk + +``` + +Which produces the following hash value: + +``` +Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY= +``` + +The client constructs the normalized request string (newline terminated values): + +``` +hawk.1.header +1353832234 +j4h3g2 +POST +/resource/1?a=1&b=2 +example.com +8000 +Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY= +some-app-ext-data + +``` + +Then calculates the request MAC and includes the **Hawk** key identifier, timestamp, nonce, payload hash, application specific data, +and request MAC, with the request using the HTTP `Authorization` request header field: + +``` +POST /resource/1?a=1&b=2 HTTP/1.1 +Host: example.com:8000 +Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw=" +``` + +It is up to the server if and when it validates the payload for any given request, based solely on it's security policy +and the nature of the data included. + +If the payload is available at the time of authentication, the server uses the hash value provided by the client to construct +the normalized string and validates the MAC. If the MAC is valid, the server calculates the payload hash and compares the value +with the provided payload hash in the header. In many cases, checking the MAC first is faster than calculating the payload hash. + +However, if the payload is not available at authentication time (e.g. too large to fit in memory, streamed elsewhere, or processed +at a different stage in the application), the server may choose to defer payload validation for later by retaining the hash value +provided by the client after validating the MAC. + +It is important to note that MAC validation does not mean the hash value provided by the client is valid, only that the value +included in the header was not modified. Without calculating the payload hash on the server and comparing it to the value provided +by the client, the payload may be modified by an attacker. + + +## Response Payload Validation + +**Hawk** provides partial response payload validation. The server includes the `Server-Authorization` response header which enables the +client to authenticate the response and ensure it is talking to the right server. **Hawk** defines the HTTP `Server-Authorization` header +as a response header using the exact same syntax as the `Authorization` request header field. + +The header is contructed using the same process as the client's request header. The server uses the same credentials and other +artifacts provided by the client to constructs the normalized request string. The `ext` and `hash` values are replaced with +new values based on the server response. The rest as identical to those used by the client. + +The result MAC digest is included with the optional `hash` and `ext` values: + +``` +Server-Authorization: Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific" +``` + + +## Browser Support and Considerations + +A browser script is provided for including using a `'); + expect(encoded).to.equal('\\x3cscript\\x3ealert\\x281\\x29\\x3c\\x2fscript\\x3e'); + done(); + }); + + it('encodes \' characters', function (done) { + + var encoded = Hoek.escapeJavaScript('something(\'param\')'); + expect(encoded).to.equal('something\\x28\\x27param\\x27\\x29'); + done(); + }); + + it('encodes large unicode characters with the correct padding', function (done) { + + var encoded = Hoek.escapeJavaScript(String.fromCharCode(500) + String.fromCharCode(1000)); + expect(encoded).to.equal('\\u0500\\u1000'); + done(); + }); + + it('doesn\'t throw an exception when passed null', function (done) { + + var encoded = Hoek.escapeJavaScript(null); + expect(encoded).to.equal(''); + done(); + }); +}); + +describe('escapeHtml()', function () { + + it('encodes / characters', function (done) { + + var encoded = Hoek.escapeHtml(''); + expect(encoded).to.equal('<script>alert(1)</script>'); + done(); + }); + + it('encodes < and > as named characters', function (done) { + + var encoded = Hoek.escapeHtml(' +``` + +Or in node.js: + +``` +npm install node-uuid +``` + +```javascript +var uuid = require('node-uuid'); +``` + +Then create some ids ... + +```javascript +// Generate a v1 (time-based) id +uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' + +// Generate a v4 (random) id +uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' +``` + +## API + +### uuid.v1([`options` [, `buffer` [, `offset`]]]) + +Generate and return a RFC4122 v1 (timestamp-based) UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + + * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1. + * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. + * `msecs` - (Number | Date) Time in milliseconds since unix Epoch. Default: The current time is used. + * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. + +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Notes: + +1. The randomly generated node id is only guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.) + +Example: Generate string UUID with fully-specified options + +```javascript +uuid.v1({ + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678 +}); // -> "710b962e-041c-11e1-9234-0123456789ab" +``` + +Example: In-place generation of two binary IDs + +```javascript +// Generate two ids in an array +var arr = new Array(32); // -> [] +uuid.v1(null, arr, 0); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15] +uuid.v1(null, arr, 16); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15 02 a3 1c b0 14 32 11 e1 85 58 0b 48 8e 4f c1 15] + +// Optionally use uuid.unparse() to get stringify the ids +uuid.unparse(buffer); // -> '02a2ce90-1432-11e1-8558-0b488e4fc115' +uuid.unparse(buffer, 16) // -> '02a31cb0-1432-11e1-8558-0b488e4fc115' +``` + +### uuid.v4([`options` [, `buffer` [, `offset`]]]) + +Generate and return a RFC4122 v4 UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + + * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values + * `rng` - (Function) Random # generator to use. Set to one of the built-in generators - `uuid.mathRNG` (all platforms), `uuid.nodeRNG` (node.js only), `uuid.whatwgRNG` (WebKit only) - or a custom function that returns an array[16] of byte values. + +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: Generate string UUID with fully-specified options + +```javascript +uuid.v4({ + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, + 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 + ] +}); +// -> "109156be-c4fb-41ea-b1b4-efe1671c5836" +``` + +Example: Generate two IDs in a single buffer + +```javascript +var buffer = new Array(32); // (or 'new Buffer' in node.js) +uuid.v4(null, buffer, 0); +uuid.v4(null, buffer, 16); +``` + +### uuid.parse(id[, buffer[, offset]]) +### uuid.unparse(buffer[, offset]) + +Parse and unparse UUIDs + + * `id` - (String) UUID(-like) string + * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. Default: A new Array or Buffer is used + * `offset` - (Number) Starting index in `buffer` at which to begin writing. Default: 0 + +Example parsing and unparsing a UUID string + +```javascript +var bytes = uuid.parse('797ff043-11eb-11e1-80d6-510998755d10'); // -> +var string = uuid.unparse(bytes); // -> '797ff043-11eb-11e1-80d6-510998755d10' +``` + +### uuid.noConflict() + +(Browsers only) Set `uuid` property back to it's previous value. + +Returns the node-uuid object. + +Example: + +```javascript +var myUuid = uuid.noConflict(); +myUuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' +``` + +## Deprecated APIs + +Support for the following v1.2 APIs is available in v1.3, but is deprecated and will be removed in the next major version. + +### uuid([format [, buffer [, offset]]]) + +uuid() has become uuid.v4(), and the `format` argument is now implicit in the `buffer` argument. (i.e. if you specify a buffer, the format is assumed to be binary). + +### uuid.BufferClass + +The class of container created when generating binary uuid data if no buffer argument is specified. This is expected to go away, with no replacement API. + +## Command Line Interface + +To use the executable, it's probably best to install this library globally. + +`npm install -g node-uuid` + +Usage: + +``` +USAGE: uuid [version] [options] + + +options: + +--help Display this message and exit +``` + +`version` must be an RFC4122 version that is supported by this library, which is currently version 1 and version 4 (denoted by "v1" and "v4", respectively). `version` defaults to version 4 when not supplied. + +### Examples + +``` +> uuid +3a91f950-dec8-4688-ba14-5b7bbfc7a563 +``` + +``` +> uuid v1 +9d0b43e0-7696-11e3-964b-250efa37a98e +``` + +``` +> uuid v4 +6790ac7c-24ac-4f98-8464-42f6d98a53ae +``` + +## Testing + +In node.js + +``` +npm test +``` + +In Browser + +``` +open test/test.html +``` + +### Benchmarking + +Requires node.js + +``` +npm install uuid uuid-js +node benchmark/benchmark.js +``` + +For a more complete discussion of node-uuid performance, please see the `benchmark/README.md` file, and the [benchmark wiki](https://github.com/broofa/node-uuid/wiki/Benchmark) + +For browser performance [checkout the JSPerf tests](http://jsperf.com/node-uuid-performance). + +## Release notes + +### 1.4.0 + +* Improved module context detection +* Removed public RNG functions + +### 1.3.2 + +* Improve tests and handling of v1() options (Issue #24) +* Expose RNG option to allow for perf testing with different generators + +### 1.3.0 + +* Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +* Support for node.js crypto API +* De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/README.md new file mode 100644 index 0000000..aaeb2ea --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/README.md @@ -0,0 +1,53 @@ +# node-uuid Benchmarks + +### Results + +To see the results of our benchmarks visit https://github.com/broofa/node-uuid/wiki/Benchmark + +### Run them yourself + +node-uuid comes with some benchmarks to measure performance of generating UUIDs. These can be run using node.js. node-uuid is being benchmarked against some other uuid modules, that are available through npm namely `uuid` and `uuid-js`. + +To prepare and run the benchmark issue; + +``` +npm install uuid uuid-js +node benchmark/benchmark.js +``` + +You'll see an output like this one: + +``` +# v4 +nodeuuid.v4(): 854700 uuids/second +nodeuuid.v4('binary'): 788643 uuids/second +nodeuuid.v4('binary', buffer): 1336898 uuids/second +uuid(): 479386 uuids/second +uuid('binary'): 582072 uuids/second +uuidjs.create(4): 312304 uuids/second + +# v1 +nodeuuid.v1(): 938086 uuids/second +nodeuuid.v1('binary'): 683060 uuids/second +nodeuuid.v1('binary', buffer): 1644736 uuids/second +uuidjs.create(1): 190621 uuids/second +``` + +* The `uuid()` entries are for Nikhil Marathe's [uuid module](https://bitbucket.org/nikhilm/uuidjs) which is a wrapper around the native libuuid library. +* The `uuidjs()` entries are for Patrick Negri's [uuid-js module](https://github.com/pnegri/uuid-js) which is a pure javascript implementation based on [UUID.js](https://github.com/LiosK/UUID.js) by LiosK. + +If you want to get more reliable results you can run the benchmark multiple times and write the output into a log file: + +``` +for i in {0..9}; do node benchmark/benchmark.js >> benchmark/bench_0.4.12.log; done; +``` + +If you're interested in how performance varies between different node versions, you can issue the above command multiple times. + +You can then use the shell script `bench.sh` provided in this directory to calculate the averages over all benchmark runs and draw a nice plot: + +``` +(cd benchmark/ && ./bench.sh) +``` + +This assumes you have [gnuplot](http://www.gnuplot.info/) and [ImageMagick](http://www.imagemagick.org/) installed. You'll find a nice `bench.png` graph in the `benchmark/` directory then. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.gnu b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.gnu new file mode 100644 index 0000000..a342fbb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.gnu @@ -0,0 +1,174 @@ +#!/opt/local/bin/gnuplot -persist +# +# +# G N U P L O T +# Version 4.4 patchlevel 3 +# last modified March 2011 +# System: Darwin 10.8.0 +# +# Copyright (C) 1986-1993, 1998, 2004, 2007-2010 +# Thomas Williams, Colin Kelley and many others +# +# gnuplot home: http://www.gnuplot.info +# faq, bugs, etc: type "help seeking-assistance" +# immediate help: type "help" +# plot window: hit 'h' +set terminal postscript eps noenhanced defaultplex \ + leveldefault color colortext \ + solid linewidth 1.2 butt noclip \ + palfuncparam 2000,0.003 \ + "Helvetica" 14 +set output 'bench.eps' +unset clip points +set clip one +unset clip two +set bar 1.000000 front +set border 31 front linetype -1 linewidth 1.000 +set xdata +set ydata +set zdata +set x2data +set y2data +set timefmt x "%d/%m/%y,%H:%M" +set timefmt y "%d/%m/%y,%H:%M" +set timefmt z "%d/%m/%y,%H:%M" +set timefmt x2 "%d/%m/%y,%H:%M" +set timefmt y2 "%d/%m/%y,%H:%M" +set timefmt cb "%d/%m/%y,%H:%M" +set boxwidth +set style fill empty border +set style rectangle back fc lt -3 fillstyle solid 1.00 border lt -1 +set style circle radius graph 0.02, first 0, 0 +set dummy x,y +set format x "% g" +set format y "% g" +set format x2 "% g" +set format y2 "% g" +set format z "% g" +set format cb "% g" +set angles radians +unset grid +set key title "" +set key outside left top horizontal Right noreverse enhanced autotitles columnhead nobox +set key noinvert samplen 4 spacing 1 width 0 height 0 +set key maxcolumns 2 maxrows 0 +unset label +unset arrow +set style increment default +unset style line +set style line 1 linetype 1 linewidth 2.000 pointtype 1 pointsize default pointinterval 0 +unset style arrow +set style histogram clustered gap 2 title offset character 0, 0, 0 +unset logscale +set offsets graph 0.05, 0.15, 0, 0 +set pointsize 1.5 +set pointintervalbox 1 +set encoding default +unset polar +unset parametric +unset decimalsign +set view 60, 30, 1, 1 +set samples 100, 100 +set isosamples 10, 10 +set surface +unset contour +set clabel '%8.3g' +set mapping cartesian +set datafile separator whitespace +unset hidden3d +set cntrparam order 4 +set cntrparam linear +set cntrparam levels auto 5 +set cntrparam points 5 +set size ratio 0 1,1 +set origin 0,0 +set style data points +set style function lines +set xzeroaxis linetype -2 linewidth 1.000 +set yzeroaxis linetype -2 linewidth 1.000 +set zzeroaxis linetype -2 linewidth 1.000 +set x2zeroaxis linetype -2 linewidth 1.000 +set y2zeroaxis linetype -2 linewidth 1.000 +set ticslevel 0.5 +set mxtics default +set mytics default +set mztics default +set mx2tics default +set my2tics default +set mcbtics default +set xtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 +set xtics norangelimit +set xtics () +set ytics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 +set ytics autofreq norangelimit +set ztics border in scale 1,0.5 nomirror norotate offset character 0, 0, 0 +set ztics autofreq norangelimit +set nox2tics +set noy2tics +set cbtics border in scale 1,0.5 mirror norotate offset character 0, 0, 0 +set cbtics autofreq norangelimit +set title "" +set title offset character 0, 0, 0 font "" norotate +set timestamp bottom +set timestamp "" +set timestamp offset character 0, 0, 0 font "" norotate +set rrange [ * : * ] noreverse nowriteback # (currently [8.98847e+307:-8.98847e+307] ) +set autoscale rfixmin +set autoscale rfixmax +set trange [ * : * ] noreverse nowriteback # (currently [-5.00000:5.00000] ) +set autoscale tfixmin +set autoscale tfixmax +set urange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) +set autoscale ufixmin +set autoscale ufixmax +set vrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) +set autoscale vfixmin +set autoscale vfixmax +set xlabel "" +set xlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate +set x2label "" +set x2label offset character 0, 0, 0 font "" textcolor lt -1 norotate +set xrange [ * : * ] noreverse nowriteback # (currently [-0.150000:3.15000] ) +set autoscale xfixmin +set autoscale xfixmax +set x2range [ * : * ] noreverse nowriteback # (currently [0.00000:3.00000] ) +set autoscale x2fixmin +set autoscale x2fixmax +set ylabel "" +set ylabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 +set y2label "" +set y2label offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 +set yrange [ 0.00000 : 1.90000e+06 ] noreverse nowriteback # (currently [:] ) +set autoscale yfixmin +set autoscale yfixmax +set y2range [ * : * ] noreverse nowriteback # (currently [0.00000:1.90000e+06] ) +set autoscale y2fixmin +set autoscale y2fixmax +set zlabel "" +set zlabel offset character 0, 0, 0 font "" textcolor lt -1 norotate +set zrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) +set autoscale zfixmin +set autoscale zfixmax +set cblabel "" +set cblabel offset character 0, 0, 0 font "" textcolor lt -1 rotate by -270 +set cbrange [ * : * ] noreverse nowriteback # (currently [8.98847e+307:-8.98847e+307] ) +set autoscale cbfixmin +set autoscale cbfixmax +set zero 1e-08 +set lmargin -1 +set bmargin -1 +set rmargin -1 +set tmargin -1 +set pm3d explicit at s +set pm3d scansautomatic +set pm3d interpolate 1,1 flush begin noftriangles nohidden3d corners2color mean +set palette positive nops_allcF maxcolors 0 gamma 1.5 color model RGB +set palette rgbformulae 7, 5, 15 +set colorbox default +set colorbox vertical origin screen 0.9, 0.2, 0 size screen 0.05, 0.6, 0 front bdefault +set loadpath +set fontpath +set fit noerrorvariables +GNUTERM = "aqua" +plot 'bench_results.txt' using 2:xticlabel(1) w lp lw 2, '' using 3:xticlabel(1) w lp lw 2, '' using 4:xticlabel(1) w lp lw 2, '' using 5:xticlabel(1) w lp lw 2, '' using 6:xticlabel(1) w lp lw 2, '' using 7:xticlabel(1) w lp lw 2, '' using 8:xticlabel(1) w lp lw 2, '' using 9:xticlabel(1) w lp lw 2 +# EOF diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.sh new file mode 100755 index 0000000..d870a0c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/bench.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +# for a given node version run: +# for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done; + +PATTERNS=('nodeuuid.v1()' "nodeuuid.v1('binary'," 'nodeuuid.v4()' "nodeuuid.v4('binary'," "uuid()" "uuid('binary')" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte') +FILES=(node_uuid_v1_string node_uuid_v1_buf node_uuid_v4_string node_uuid_v4_buf libuuid_v4_string libuuid_v4_binary uuidjs_v1_string uuidjs_v4_string 140byte_es) +INDICES=(2 3 2 3 2 2 2 2 2) +VERSIONS=$( ls bench_*.log | sed -e 's/^bench_\([0-9\.]*\)\.log/\1/' | tr "\\n" " " ) +TMPJOIN="tmp_join" +OUTPUT="bench_results.txt" + +for I in ${!FILES[*]}; do + F=${FILES[$I]} + P=${PATTERNS[$I]} + INDEX=${INDICES[$I]} + echo "version $F" > $F + for V in $VERSIONS; do + (VAL=$( grep "$P" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F + done + if [ $I == 0 ]; then + cat $F > $TMPJOIN + else + join $TMPJOIN $F > $OUTPUT + cp $OUTPUT $TMPJOIN + fi + rm $F +done + +rm $TMPJOIN + +gnuplot bench.gnu +convert -density 200 -resize 800x560 -flatten bench.eps bench.png +rm bench.eps diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark-native.c b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark-native.c new file mode 100644 index 0000000..dbfc75f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark-native.c @@ -0,0 +1,34 @@ +/* +Test performance of native C UUID generation + +To Compile: cc -luuid benchmark-native.c -o benchmark-native +*/ + +#include +#include +#include +#include + +int main() { + uuid_t myid; + char buf[36+1]; + int i; + struct timeval t; + double start, finish; + + gettimeofday(&t, NULL); + start = t.tv_sec + t.tv_usec/1e6; + + int n = 2e5; + for (i = 0; i < n; i++) { + uuid_generate(myid); + uuid_unparse(myid, buf); + } + + gettimeofday(&t, NULL); + finish = t.tv_sec + t.tv_usec/1e6; + double dur = finish - start; + + printf("%d uuids/sec", (int)(n/dur)); + return 0; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark.js new file mode 100644 index 0000000..40e6efb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/benchmark/benchmark.js @@ -0,0 +1,84 @@ +try { + var nodeuuid = require('../uuid'); +} catch (e) { + console.error('node-uuid require failed - skipping tests'); +} + +try { + var uuid = require('uuid'); +} catch (e) { + console.error('uuid require failed - skipping tests'); +} + +try { + var uuidjs = require('uuid-js'); +} catch (e) { + console.error('uuid-js require failed - skipping tests'); +} + +var N = 5e5; + +function rate(msg, t) { + console.log(msg + ': ' + + (N / (Date.now() - t) * 1e3 | 0) + + ' uuids/second'); +} + +console.log('# v4'); + +// node-uuid - string form +if (nodeuuid) { + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4(); + rate('nodeuuid.v4() - using node.js crypto RNG', t); + + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4({rng: nodeuuid.mathRNG}); + rate('nodeuuid.v4() - using Math.random() RNG', t); + + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4('binary'); + rate('nodeuuid.v4(\'binary\')', t); + + var buffer = new nodeuuid.BufferClass(16); + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v4('binary', buffer); + rate('nodeuuid.v4(\'binary\', buffer)', t); +} + +// libuuid - string form +if (uuid) { + for (var i = 0, t = Date.now(); i < N; i++) uuid(); + rate('uuid()', t); + + for (var i = 0, t = Date.now(); i < N; i++) uuid('binary'); + rate('uuid(\'binary\')', t); +} + +// uuid-js - string form +if (uuidjs) { + for (var i = 0, t = Date.now(); i < N; i++) uuidjs.create(4); + rate('uuidjs.create(4)', t); +} + +// 140byte.es +for (var i = 0, t = Date.now(); i < N; i++) 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(s,r){r=Math.random()*16|0;return (s=='x'?r:r&0x3|0x8).toString(16)}); +rate('140byte.es_v4', t); + +console.log(''); +console.log('# v1'); + +// node-uuid - v1 string form +if (nodeuuid) { + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1(); + rate('nodeuuid.v1()', t); + + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1('binary'); + rate('nodeuuid.v1(\'binary\')', t); + + var buffer = new nodeuuid.BufferClass(16); + for (var i = 0, t = Date.now(); i < N; i++) nodeuuid.v1('binary', buffer); + rate('nodeuuid.v1(\'binary\', buffer)', t); +} + +// uuid-js - v1 string form +if (uuidjs) { + for (var i = 0, t = Date.now(); i < N; i++) uuidjs.create(1); + rate('uuidjs.create(1)', t); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bin/uuid b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bin/uuid new file mode 100755 index 0000000..f732e99 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bin/uuid @@ -0,0 +1,26 @@ +#!/usr/bin/env node + +var path = require('path'); +var uuid = require(path.join(__dirname, '..')); + +var arg = process.argv[2]; + +if ('--help' === arg) { + console.log('\n USAGE: uuid [version] [options]\n\n'); + console.log(' options:\n'); + console.log(' --help Display this message and exit\n'); + process.exit(0); +} + +if (null == arg) { + console.log(uuid()); + process.exit(0); +} + +if ('v1' !== arg && 'v4' !== arg) { + console.error('Version must be RFC4122 version 1 or version 4, denoted as "v1" or "v4"'); + process.exit(1); +} + +console.log(uuid[arg]()); +process.exit(0); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bower.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bower.json new file mode 100644 index 0000000..1656dc8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/bower.json @@ -0,0 +1,23 @@ +{ + "name": "node-uuid", + "version": "1.4.3", + "homepage": "https://github.com/broofa/node-uuid", + "authors": [ + "Robert Kieffer " + ], + "description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.", + "main": "uuid.js", + "keywords": [ + "uuid", + "gid", + "rfc4122" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/component.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/component.json new file mode 100644 index 0000000..149f84b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/component.json @@ -0,0 +1,18 @@ +{ + "name": "node-uuid", + "repo": "broofa/node-uuid", + "description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.", + "version": "1.4.3", + "author": "Robert Kieffer ", + "contributors": [ + {"name": "Christoph Tavan ", "github": "https://github.com/ctavan"} + ], + "keywords": ["uuid", "guid", "rfc4122"], + "dependencies": {}, + "development": {}, + "main": "uuid.js", + "scripts": [ + "uuid.js" + ], + "license": "MIT" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/package.json new file mode 100644 index 0000000..37754ad --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/package.json @@ -0,0 +1,49 @@ +{ + "name": "node-uuid", + "description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.", + "url": "http://github.com/broofa/node-uuid", + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "author": { + "name": "Robert Kieffer", + "email": "robert@broofa.com" + }, + "contributors": [ + { + "name": "Christoph Tavan", + "email": "dev@tavan.de" + } + ], + "bin": { + "uuid": "./bin/uuid" + }, + "scripts": { + "test": "node test/test.js" + }, + "lib": ".", + "main": "./uuid.js", + "repository": { + "type": "git", + "url": "git+https://github.com/broofa/node-uuid.git" + }, + "version": "1.4.3", + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/broofa/node-uuid/master/LICENSE.md" + } + ], + "readme": "# node-uuid\n\nSimple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS.\n\nFeatures:\n\n* Generate RFC4122 version 1 or version 4 UUIDs\n* Runs in node.js and all browsers.\n* Registered as a [ComponentJS](https://github.com/component/component) [component](https://github.com/component/component/wiki/Components) ('broofa/node-uuid').\n* Cryptographically strong random # generation on supporting platforms\n* 1.1K minified and gzip'ed (Want something smaller? Check this [crazy shit](https://gist.github.com/982883) out! )\n* [Annotated source code](http://broofa.github.com/node-uuid/docs/uuid.html)\n* Comes with a Command Line Interface for generating uuids on the command line\n\n## Getting Started\n\nInstall it in your browser:\n\n```html\n\n```\n\nOr in node.js:\n\n```\nnpm install node-uuid\n```\n\n```javascript\nvar uuid = require('node-uuid');\n```\n\nThen create some ids ...\n\n```javascript\n// Generate a v1 (time-based) id\nuuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'\n\n// Generate a v4 (random) id\nuuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1'\n```\n\n## API\n\n### uuid.v1([`options` [, `buffer` [, `offset`]]])\n\nGenerate and return a RFC4122 v1 (timestamp-based) UUID.\n\n* `options` - (Object) Optional uuid state to apply. Properties may include:\n\n * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1.\n * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used.\n * `msecs` - (Number | Date) Time in milliseconds since unix Epoch. Default: The current time is used.\n * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2.\n\n* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.\n* `offset` - (Number) Starting index in `buffer` at which to begin writing.\n\nReturns `buffer`, if specified, otherwise the string form of the UUID\n\nNotes:\n\n1. The randomly generated node id is only guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.)\n\nExample: Generate string UUID with fully-specified options\n\n```javascript\nuuid.v1({\n node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],\n clockseq: 0x1234,\n msecs: new Date('2011-11-01').getTime(),\n nsecs: 5678\n}); // -> \"710b962e-041c-11e1-9234-0123456789ab\"\n```\n\nExample: In-place generation of two binary IDs\n\n```javascript\n// Generate two ids in an array\nvar arr = new Array(32); // -> []\nuuid.v1(null, arr, 0); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15]\nuuid.v1(null, arr, 16); // -> [02 a2 ce 90 14 32 11 e1 85 58 0b 48 8e 4f c1 15 02 a3 1c b0 14 32 11 e1 85 58 0b 48 8e 4f c1 15]\n\n// Optionally use uuid.unparse() to get stringify the ids\nuuid.unparse(buffer); // -> '02a2ce90-1432-11e1-8558-0b488e4fc115'\nuuid.unparse(buffer, 16) // -> '02a31cb0-1432-11e1-8558-0b488e4fc115'\n```\n\n### uuid.v4([`options` [, `buffer` [, `offset`]]])\n\nGenerate and return a RFC4122 v4 UUID.\n\n* `options` - (Object) Optional uuid state to apply. Properties may include:\n\n * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values\n * `rng` - (Function) Random # generator to use. Set to one of the built-in generators - `uuid.mathRNG` (all platforms), `uuid.nodeRNG` (node.js only), `uuid.whatwgRNG` (WebKit only) - or a custom function that returns an array[16] of byte values.\n\n* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.\n* `offset` - (Number) Starting index in `buffer` at which to begin writing.\n\nReturns `buffer`, if specified, otherwise the string form of the UUID\n\nExample: Generate string UUID with fully-specified options\n\n```javascript\nuuid.v4({\n random: [\n 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,\n 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36\n ]\n});\n// -> \"109156be-c4fb-41ea-b1b4-efe1671c5836\"\n```\n\nExample: Generate two IDs in a single buffer\n\n```javascript\nvar buffer = new Array(32); // (or 'new Buffer' in node.js)\nuuid.v4(null, buffer, 0);\nuuid.v4(null, buffer, 16);\n```\n\n### uuid.parse(id[, buffer[, offset]])\n### uuid.unparse(buffer[, offset])\n\nParse and unparse UUIDs\n\n * `id` - (String) UUID(-like) string\n * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. Default: A new Array or Buffer is used\n * `offset` - (Number) Starting index in `buffer` at which to begin writing. Default: 0\n\nExample parsing and unparsing a UUID string\n\n```javascript\nvar bytes = uuid.parse('797ff043-11eb-11e1-80d6-510998755d10'); // -> \nvar string = uuid.unparse(bytes); // -> '797ff043-11eb-11e1-80d6-510998755d10'\n```\n\n### uuid.noConflict()\n\n(Browsers only) Set `uuid` property back to it's previous value.\n\nReturns the node-uuid object.\n\nExample:\n\n```javascript\nvar myUuid = uuid.noConflict();\nmyUuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'\n```\n\n## Deprecated APIs\n\nSupport for the following v1.2 APIs is available in v1.3, but is deprecated and will be removed in the next major version.\n\n### uuid([format [, buffer [, offset]]])\n\nuuid() has become uuid.v4(), and the `format` argument is now implicit in the `buffer` argument. (i.e. if you specify a buffer, the format is assumed to be binary).\n\n### uuid.BufferClass\n\nThe class of container created when generating binary uuid data if no buffer argument is specified. This is expected to go away, with no replacement API.\n\n## Command Line Interface\n\nTo use the executable, it's probably best to install this library globally.\n\n`npm install -g node-uuid`\n\nUsage:\n\n```\nUSAGE: uuid [version] [options]\n\n\noptions:\n\n--help Display this message and exit\n```\n\n`version` must be an RFC4122 version that is supported by this library, which is currently version 1 and version 4 (denoted by \"v1\" and \"v4\", respectively). `version` defaults to version 4 when not supplied.\n\n### Examples\n\n```\n> uuid\n3a91f950-dec8-4688-ba14-5b7bbfc7a563\n```\n\n```\n> uuid v1\n9d0b43e0-7696-11e3-964b-250efa37a98e\n```\n\n```\n> uuid v4\n6790ac7c-24ac-4f98-8464-42f6d98a53ae\n```\n\n## Testing\n\nIn node.js\n\n```\nnpm test\n```\n\nIn Browser\n\n```\nopen test/test.html\n```\n\n### Benchmarking\n\nRequires node.js\n\n```\nnpm install uuid uuid-js\nnode benchmark/benchmark.js\n```\n\nFor a more complete discussion of node-uuid performance, please see the `benchmark/README.md` file, and the [benchmark wiki](https://github.com/broofa/node-uuid/wiki/Benchmark)\n\nFor browser performance [checkout the JSPerf tests](http://jsperf.com/node-uuid-performance).\n\n## Release notes\n\n### 1.4.0\n\n* Improved module context detection\n* Removed public RNG functions\n\n### 1.3.2\n\n* Improve tests and handling of v1() options (Issue #24)\n* Expose RNG option to allow for perf testing with different generators\n\n### 1.3.0\n\n* Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)!\n* Support for node.js crypto API\n* De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/broofa/node-uuid/issues" + }, + "homepage": "https://github.com/broofa/node-uuid#readme", + "_id": "node-uuid@1.4.3", + "_shasum": "319bb7a56e7cb63f00b5c0cd7851cd4b4ddf1df9", + "_resolved": "https://registry.npmjs.org/node-uuid/-/node-uuid-1.4.3.tgz", + "_from": "node-uuid@>=1.4.0 <1.5.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/compare_v1.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/compare_v1.js new file mode 100644 index 0000000..05af822 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/compare_v1.js @@ -0,0 +1,63 @@ +var assert = require('assert'), + nodeuuid = require('../uuid'), + uuidjs = require('uuid-js'), + libuuid = require('uuid').generate, + util = require('util'), + exec = require('child_process').exec, + os = require('os'); + +// On Mac Os X / macports there's only the ossp-uuid package that provides uuid +// On Linux there's uuid-runtime which provides uuidgen +var uuidCmd = os.type() === 'Darwin' ? 'uuid -1' : 'uuidgen -t'; + +function compare(ids) { + console.log(ids); + for (var i = 0; i < ids.length; i++) { + var id = ids[i].split('-'); + id = [id[2], id[1], id[0]].join(''); + ids[i] = id; + } + var sorted = ([].concat(ids)).sort(); + + if (sorted.toString() !== ids.toString()) { + console.log('Warning: sorted !== ids'); + } else { + console.log('everything in order!'); + } +} + +// Test time order of v1 uuids +var ids = []; +while (ids.length < 10e3) ids.push(nodeuuid.v1()); + +var max = 10; +console.log('node-uuid:'); +ids = []; +for (var i = 0; i < max; i++) ids.push(nodeuuid.v1()); +compare(ids); + +console.log(''); +console.log('uuidjs:'); +ids = []; +for (var i = 0; i < max; i++) ids.push(uuidjs.create(1).toString()); +compare(ids); + +console.log(''); +console.log('libuuid:'); +ids = []; +var count = 0; +var last = function() { + compare(ids); +} +var cb = function(err, stdout, stderr) { + ids.push(stdout.substring(0, stdout.length-1)); + count++; + if (count < max) { + return next(); + } + last(); +}; +var next = function() { + exec(uuidCmd, cb); +}; +next(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.html b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.html new file mode 100644 index 0000000..d80326e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.html @@ -0,0 +1,17 @@ + + + + + + + + + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.js new file mode 100644 index 0000000..2469225 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/test/test.js @@ -0,0 +1,228 @@ +if (!this.uuid) { + // node.js + uuid = require('../uuid'); +} + +// +// x-platform log/assert shims +// + +function _log(msg, type) { + type = type || 'log'; + + if (typeof(document) != 'undefined') { + document.write('
' + msg.replace(/\n/g, '
') + '
'); + } + if (typeof(console) != 'undefined') { + var color = { + log: '\033[39m', + warn: '\033[33m', + error: '\033[31m' + }; + console[type](color[type] + msg + color.log); + } +} + +function log(msg) {_log(msg, 'log');} +function warn(msg) {_log(msg, 'warn');} +function error(msg) {_log(msg, 'error');} + +function assert(res, msg) { + if (!res) { + error('FAIL: ' + msg); + } else { + log('Pass: ' + msg); + } +} + +// +// Unit tests +// + +// Verify ordering of v1 ids created with explicit times +var TIME = 1321644961388; // 2011-11-18 11:36:01.388-08:00 + +function compare(name, ids) { + ids = ids.map(function(id) { + return id.split('-').reverse().join('-'); + }).sort(); + var sorted = ([].concat(ids)).sort(); + + assert(sorted.toString() == ids.toString(), name + ' have expected order'); +} + +// Verify ordering of v1 ids created using default behavior +compare('uuids with current time', [ + uuid.v1(), + uuid.v1(), + uuid.v1(), + uuid.v1(), + uuid.v1() +]); + +// Verify ordering of v1 ids created with explicit times +compare('uuids with time option', [ + uuid.v1({msecs: TIME - 10*3600*1000}), + uuid.v1({msecs: TIME - 1}), + uuid.v1({msecs: TIME}), + uuid.v1({msecs: TIME + 1}), + uuid.v1({msecs: TIME + 28*24*3600*1000}) +]); + +assert( + uuid.v1({msecs: TIME}) != uuid.v1({msecs: TIME}), + 'IDs created at same msec are different' +); + +// Verify throw if too many ids created +var thrown = false; +try { + uuid.v1({msecs: TIME, nsecs: 10000}); +} catch (e) { + thrown = true; +} +assert(thrown, 'Exception thrown when > 10K ids created in 1 ms'); + +// Verify clock regression bumps clockseq +var uidt = uuid.v1({msecs: TIME}); +var uidtb = uuid.v1({msecs: TIME - 1}); +assert( + parseInt(uidtb.split('-')[3], 16) - parseInt(uidt.split('-')[3], 16) === 1, + 'Clock regression by msec increments the clockseq' +); + +// Verify clock regression bumps clockseq +var uidtn = uuid.v1({msecs: TIME, nsecs: 10}); +var uidtnb = uuid.v1({msecs: TIME, nsecs: 9}); +assert( + parseInt(uidtnb.split('-')[3], 16) - parseInt(uidtn.split('-')[3], 16) === 1, + 'Clock regression by nsec increments the clockseq' +); + +// Verify explicit options produce expected id +var id = uuid.v1({ + msecs: 1321651533573, + nsecs: 5432, + clockseq: 0x385c, + node: [ 0x61, 0xcd, 0x3c, 0xbb, 0x32, 0x10 ] +}); +assert(id == 'd9428888-122b-11e1-b85c-61cd3cbb3210', 'Explicit options produce expected id'); + +// Verify adjacent ids across a msec boundary are 1 time unit apart +var u0 = uuid.v1({msecs: TIME, nsecs: 9999}); +var u1 = uuid.v1({msecs: TIME + 1, nsecs: 0}); + +var before = u0.split('-')[0], after = u1.split('-')[0]; +var dt = parseInt(after, 16) - parseInt(before, 16); +assert(dt === 1, 'Ids spanning 1ms boundary are 100ns apart'); + +// +// Test parse/unparse +// + +id = '00112233445566778899aabbccddeeff'; +assert(uuid.unparse(uuid.parse(id.substr(0,10))) == + '00112233-4400-0000-0000-000000000000', 'Short parse'); +assert(uuid.unparse(uuid.parse('(this is the uuid -> ' + id + id)) == + '00112233-4455-6677-8899-aabbccddeeff', 'Dirty parse'); + +// +// Perf tests +// + +var generators = { + v1: uuid.v1, + v4: uuid.v4 +}; + +var UUID_FORMAT = { + v1: /[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i, + v4: /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i +}; + +var N = 1e4; + +// Get %'age an actual value differs from the ideal value +function divergence(actual, ideal) { + return Math.round(100*100*(actual - ideal)/ideal)/100; +} + +function rate(msg, t) { + log(msg + ': ' + (N / (Date.now() - t) * 1e3 | 0) + ' uuids\/second'); +} + +for (var version in generators) { + var counts = {}, max = 0; + var generator = generators[version]; + var format = UUID_FORMAT[version]; + + log('\nSanity check ' + N + ' ' + version + ' uuids'); + for (var i = 0, ok = 0; i < N; i++) { + id = generator(); + if (!format.test(id)) { + throw Error(id + ' is not a valid UUID string'); + } + + if (id != uuid.unparse(uuid.parse(id))) { + assert(fail, id + ' is not a valid id'); + } + + // Count digits for our randomness check + if (version == 'v4') { + var digits = id.replace(/-/g, '').split(''); + for (var j = digits.length-1; j >= 0; j--) { + var c = digits[j]; + max = Math.max(max, counts[c] = (counts[c] || 0) + 1); + } + } + } + + // Check randomness for v4 UUIDs + if (version == 'v4') { + // Limit that we get worried about randomness. (Purely empirical choice, this!) + var limit = 2*100*Math.sqrt(1/N); + + log('\nChecking v4 randomness. Distribution of Hex Digits (% deviation from ideal)'); + + for (var i = 0; i < 16; i++) { + var c = i.toString(16); + var bar = '', n = counts[c], p = Math.round(n/max*100|0); + + // 1-3,5-8, and D-F: 1:16 odds over 30 digits + var ideal = N*30/16; + if (i == 4) { + // 4: 1:1 odds on 1 digit, plus 1:16 odds on 30 digits + ideal = N*(1 + 30/16); + } else if (i >= 8 && i <= 11) { + // 8-B: 1:4 odds on 1 digit, plus 1:16 odds on 30 digits + ideal = N*(1/4 + 30/16); + } else { + // Otherwise: 1:16 odds on 30 digits + ideal = N*30/16; + } + var d = divergence(n, ideal); + + // Draw bar using UTF squares (just for grins) + var s = n/max*50 | 0; + while (s--) bar += '='; + + assert(Math.abs(d) < limit, c + ' |' + bar + '| ' + counts[c] + ' (' + d + '% < ' + limit + '%)'); + } + } +} + +// Perf tests +for (var version in generators) { + log('\nPerformance testing ' + version + ' UUIDs'); + var generator = generators[version]; + var buf = new uuid.BufferClass(16); + + for (var i = 0, t = Date.now(); i < N; i++) generator(); + rate('uuid.' + version + '()', t); + + for (var i = 0, t = Date.now(); i < N; i++) generator('binary'); + rate('uuid.' + version + '(\'binary\')', t); + + for (var i = 0, t = Date.now(); i < N; i++) generator('binary', buf); + rate('uuid.' + version + '(\'binary\', buffer)', t); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/uuid.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/uuid.js new file mode 100644 index 0000000..0a61769 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/node-uuid/uuid.js @@ -0,0 +1,247 @@ +// uuid.js +// +// Copyright (c) 2010-2012 Robert Kieffer +// MIT License - http://opensource.org/licenses/mit-license.php + +(function() { + var _global = this; + + // Unique ID creation requires a high quality random # generator. We feature + // detect to determine the best RNG source, normalizing to a function that + // returns 128-bits of randomness, since that's what's usually required + var _rng; + + // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html + // + // Moderately fast, high quality + if (typeof(_global.require) == 'function') { + try { + var _rb = _global.require('crypto').randomBytes; + _rng = _rb && function() {return _rb(16);}; + } catch(e) {} + } + + if (!_rng && _global.crypto && crypto.getRandomValues) { + // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto + // + // Moderately fast, high quality + var _rnds8 = new Uint8Array(16); + _rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; + } + + if (!_rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + _rng = function() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return _rnds; + }; + } + + // Buffer class to use + var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array; + + // Maps for number <-> hex string conversion + var _byteToHex = []; + var _hexToByte = {}; + for (var i = 0; i < 256; i++) { + _byteToHex[i] = (i + 0x100).toString(16).substr(1); + _hexToByte[_byteToHex[i]] = i; + } + + // **`parse()` - Parse a UUID into it's component bytes** + function parse(s, buf, offset) { + var i = (buf && offset) || 0, ii = 0; + + buf = buf || []; + s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { + if (ii < 16) { // Don't overflow! + buf[i + ii++] = _hexToByte[oct]; + } + }); + + // Zero out remaining bytes if string was short + while (ii < 16) { + buf[i + ii++] = 0; + } + + return buf; + } + + // **`unparse()` - Convert UUID byte array (ala parse()) into a string** + function unparse(buf, offset) { + var i = offset || 0, bth = _byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; + } + + // **`v1()` - Generate time-based UUID** + // + // Inspired by https://github.com/LiosK/UUID.js + // and http://docs.python.org/library/uuid.html + + // random #'s we need to init node and clockseq + var _seedBytes = _rng(); + + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + var _nodeId = [ + _seedBytes[0] | 0x01, + _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] + ]; + + // Per 4.2.2, randomize (14 bit) clockseq + var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; + + // Previous uuid creation time + var _lastMSecs = 0, _lastNSecs = 0; + + // See https://github.com/broofa/node-uuid for API details + function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + + var clockseq = options.clockseq != null ? options.clockseq : _clockseq; + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs != null ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq == null) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + var node = options.node || _nodeId; + for (var n = 0; n < 6; n++) { + b[i + n] = node[n]; + } + + return buf ? buf : unparse(b); + } + + // **`v4()` - Generate random UUID** + + // See https://github.com/broofa/node-uuid for API details + function v4(options, buf, offset) { + // Deprecated - 'format' argument, as supported in v1.2 + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options == 'binary' ? new BufferClass(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || _rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ii++) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || unparse(rnds); + } + + // Export public API + var uuid = v4; + uuid.v1 = v1; + uuid.v4 = v4; + uuid.parse = parse; + uuid.unparse = unparse; + uuid.BufferClass = BufferClass; + + if (typeof(module) != 'undefined' && module.exports) { + // Publish as node.js module + module.exports = uuid; + } else if (typeof define === 'function' && define.amd) { + // Publish as AMD module + define(function() {return uuid;}); + + + } else { + // Publish as global (in browsers) + var _previousRoot = _global.uuid; + + // **`noConflict()` - (browser only) to reset global 'uuid' var** + uuid.noConflict = function() { + _global.uuid = _previousRoot; + return uuid; + }; + + _global.uuid = uuid; + } +}).call(this); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/README.md new file mode 100644 index 0000000..34c4a85 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/README.md @@ -0,0 +1,4 @@ +oauth-sign +========== + +OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/index.js new file mode 100644 index 0000000..a587541 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/index.js @@ -0,0 +1,134 @@ +var crypto = require('crypto') + , qs = require('querystring') + ; + +function sha1 (key, body) { + return crypto.createHmac('sha1', key).update(body).digest('base64') +} + +function rsa (key, body) { + return crypto.createSign("RSA-SHA1").update(body).sign(key, 'base64'); +} + +function rfc3986 (str) { + return encodeURIComponent(str) + .replace(/!/g,'%21') + .replace(/\*/g,'%2A') + .replace(/\(/g,'%28') + .replace(/\)/g,'%29') + .replace(/'/g,'%27') + ; +} + +// Maps object to bi-dimensional array +// Converts { foo: 'A', bar: [ 'b', 'B' ]} to +// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ] +function map (obj) { + var key, val, arr = [] + for (key in obj) { + val = obj[key] + if (Array.isArray(val)) + for (var i = 0; i < val.length; i++) + arr.push([key, val[i]]) + else if (typeof val === "object") + for (var prop in val) + arr.push([key + '[' + prop + ']', val[prop]]); + else + arr.push([key, val]) + } + return arr +} + +// Compare function for sort +function compare (a, b) { + return a > b ? 1 : a < b ? -1 : 0 +} + +function generateBase (httpMethod, base_uri, params) { + // adapted from https://dev.twitter.com/docs/auth/oauth and + // https://dev.twitter.com/docs/auth/creating-signature + + // Parameter normalization + // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 + var normalized = map(params) + // 1. First, the name and value of each parameter are encoded + .map(function (p) { + return [ rfc3986(p[0]), rfc3986(p[1] || '') ] + }) + // 2. The parameters are sorted by name, using ascending byte value + // ordering. If two or more parameters share the same name, they + // are sorted by their value. + .sort(function (a, b) { + return compare(a[0], b[0]) || compare(a[1], b[1]) + }) + // 3. The name of each parameter is concatenated to its corresponding + // value using an "=" character (ASCII code 61) as a separator, even + // if the value is empty. + .map(function (p) { return p.join('=') }) + // 4. The sorted name/value pairs are concatenated together into a + // single string by using an "&" character (ASCII code 38) as + // separator. + .join('&') + + var base = [ + rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'), + rfc3986(base_uri), + rfc3986(normalized) + ].join('&') + + return base +} + +function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) { + var base = generateBase(httpMethod, base_uri, params) + var key = [ + consumer_secret || '', + token_secret || '' + ].map(rfc3986).join('&') + + return sha1(key, base) +} + +function rsasign (httpMethod, base_uri, params, private_key, token_secret) { + var base = generateBase(httpMethod, base_uri, params) + var key = private_key || '' + + return rsa(key, base) +} + +function plaintext (consumer_secret, token_secret) { + var key = [ + consumer_secret || '', + token_secret || '' + ].map(rfc3986).join('&') + + return key +} + +function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) { + var method + var skipArgs = 1 + + switch (signMethod) { + case 'RSA-SHA1': + method = rsasign + break + case 'HMAC-SHA1': + method = hmacsign + break + case 'PLAINTEXT': + method = plaintext + skipArgs = 4 + break + default: + throw new Error("Signature method not supported: " + signMethod) + } + + return method.apply(null, [].slice.call(arguments, skipArgs)) +} + +exports.hmacsign = hmacsign +exports.rsasign = rsasign +exports.plaintext = plaintext +exports.sign = sign +exports.rfc3986 = rfc3986 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/package.json new file mode 100644 index 0000000..074a72b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/package.json @@ -0,0 +1,58 @@ +{ + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "name": "oauth-sign", + "description": "OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module.", + "version": "0.8.0", + "license": "Apache-2.0", + "repository": { + "url": "git+https://github.com/mikeal/oauth-sign.git" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "scripts": { + "test": "node test.js" + }, + "gitHead": "e1f2b42ff039901ce977f8e81918767d97d496b5", + "bugs": { + "url": "https://github.com/mikeal/oauth-sign/issues" + }, + "homepage": "https://github.com/mikeal/oauth-sign#readme", + "_id": "oauth-sign@0.8.0", + "_shasum": "938fdc875765ba527137d8aec9d178e24debc553", + "_from": "oauth-sign@>=0.8.0 <0.9.0", + "_npmVersion": "2.10.1", + "_nodeVersion": "0.12.4", + "_npmUser": { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + }, + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "nylen", + "email": "jnylen@gmail.com" + }, + { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + } + ], + "dist": { + "shasum": "938fdc875765ba527137d8aec9d178e24debc553", + "tarball": "http://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.8.0.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/test.js new file mode 100644 index 0000000..a884727 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/oauth-sign/test.js @@ -0,0 +1,89 @@ +var oauth = require('./index') + , hmacsign = oauth.hmacsign + , assert = require('assert') + , qs = require('querystring') + ; + +// Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth + +var reqsign = hmacsign('POST', 'https://api.twitter.com/oauth/request_token', + { oauth_callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11' + , oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g' + , oauth_nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk' + , oauth_signature_method: 'HMAC-SHA1' + , oauth_timestamp: '1272323042' + , oauth_version: '1.0' + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98") + +console.log(reqsign) +console.log('8wUi7m5HFQy76nowoCThusfgB+Q=') +assert.equal(reqsign, '8wUi7m5HFQy76nowoCThusfgB+Q=') + +var accsign = hmacsign('POST', 'https://api.twitter.com/oauth/access_token', + { oauth_consumer_key: 'GDdmIQH6jhtmLUypg82g' + , oauth_nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8' + , oauth_signature_method: 'HMAC-SHA1' + , oauth_token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc' + , oauth_timestamp: '1272323047' + , oauth_verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY' + , oauth_version: '1.0' + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA") + +console.log(accsign) +console.log('PUw/dHA4fnlJYM6RhXk5IU/0fCc=') +assert.equal(accsign, 'PUw/dHA4fnlJYM6RhXk5IU/0fCc=') + +var upsign = hmacsign('POST', 'http://api.twitter.com/1/statuses/update.json', + { oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" + , oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" + , oauth_signature_method: "HMAC-SHA1" + , oauth_token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" + , oauth_timestamp: "1272325550" + , oauth_version: "1.0" + , status: 'setting up my twitter 私のさえずりを設定する' + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") + +console.log(upsign) +console.log('yOahq5m0YjDDjfjxHaXEsW9D+X0=') +assert.equal(upsign, 'yOahq5m0YjDDjfjxHaXEsW9D+X0=') + +// handle objects in params (useful for Wordpress REST API) +var upsign = hmacsign('POST', 'http://wordpress.com/wp-json', + { oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" + , oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" + , oauth_signature_method: "HMAC-SHA1" + , oauth_token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" + , oauth_timestamp: "1272325550" + , oauth_version: "1.0" + , filter: { number: "-1" } + }, "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") + +console.log(upsign) +console.log('YrJFBdwnjuIitGpKrxLUplcuuUQ=') +assert.equal(upsign, 'YrJFBdwnjuIitGpKrxLUplcuuUQ=') + +// example in rfc5849 +var params = qs.parse('b5=%3D%253D&a3=a&c%40=&a2=r%20b' + '&' + 'c2&a3=2+q') +params.oauth_consumer_key = '9djdj82h48djs9d2' +params.oauth_token = 'kkk9d7dh3k39sjv7' +params.oauth_nonce = '7d8f3e4a' +params.oauth_signature_method = 'HMAC-SHA1' +params.oauth_timestamp = '137131201' + +var rfc5849sign = hmacsign('POST', 'http://example.com/request', + params, "j49sk3j29djd", "dh893hdasih9") + +console.log(rfc5849sign) +console.log('r6/TJjbCOr97/+UU0NsvSne7s5g=') +assert.equal(rfc5849sign, 'r6/TJjbCOr97/+UU0NsvSne7s5g=') + + +// PLAINTEXT + +var plainSign = oauth.sign('PLAINTEXT', 'GET', 'http://dummy.com', {}, 'consumer_secret', 'token_secret') +console.log(plainSign) +assert.equal(plainSign, 'consumer_secret&token_secret') + +plainSign = oauth.plaintext('consumer_secret', 'token_secret') +console.log(plainSign) +assert.equal(plainSign, 'consumer_secret&token_secret') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.eslintignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintrc new file mode 100644 index 0000000..997b3f7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.jshintrc @@ -0,0 +1,10 @@ +{ + "node": true, + + "curly": true, + "latedef": true, + "quotmark": true, + "undef": true, + "unused": true, + "trailing": true +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.npmignore new file mode 100644 index 0000000..2abba8d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.npmignore @@ -0,0 +1,19 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md +dist diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.travis.yml new file mode 100644 index 0000000..f502178 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 0.10 + - 0.12 + - iojs diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CHANGELOG.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..1fadc78 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CHANGELOG.md @@ -0,0 +1,88 @@ + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=open) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/hapijs/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/hapijs/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/hapijs/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/hapijs/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/hapijs/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/hapijs/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/hapijs/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/hapijs/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/hapijs/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/hapijs/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/hapijs/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/hapijs/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/hapijs/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/hapijs/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/hapijs/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/hapijs/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/hapijs/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/hapijs/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/hapijs/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/hapijs/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/hapijs/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/hapijs/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/hapijs/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/hapijs/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/hapijs/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/hapijs/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/hapijs/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CONTRIBUTING.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/Makefile new file mode 100644 index 0000000..31cc899 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/Makefile @@ -0,0 +1,8 @@ +test: + @node node_modules/lab/bin/lab -a code -L +test-cov: + @node node_modules/lab/bin/lab -a code -t 100 -L +test-cov-html: + @node node_modules/lab/bin/lab -a code -L -r html -o coverage.html + +.PHONY: test test-cov test-cov-html diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/README.md new file mode 100644 index 0000000..0c72aba --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/README.md @@ -0,0 +1,303 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`, or prefixing the sub-key with a dot `.`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +The parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods do not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b'); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** always URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array + +```javascript +Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/bower.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/bower.json new file mode 100644 index 0000000..ffd0641 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "3.0.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/index.js new file mode 100644 index 0000000..2291cd8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..1a1e205 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/parse.js @@ -0,0 +1,166 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = Object.create(null); + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return Object.create(null); + } + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = options.allowDots !== false; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = Object.create(null); + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj); + } + + return Utils.compact(obj); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/stringify.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..7414284 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/stringify.js @@ -0,0 +1,121 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return Utils.encode(prefix); + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + return ''; + } + + var arrayFormat; + if (options.arrayFormat in internals.arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } + else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; + } + else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = internals.arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, filter)); + } + + return keys.join(delimiter); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/utils.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..ec93afc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var i = 0; i < 256; ++i) { + internals.hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source) { + + var obj = Object.create(null); + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!target[key]) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/package.json new file mode 100644 index 0000000..257c718 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/package.json @@ -0,0 +1,55 @@ +{ + "name": "qs", + "version": "3.1.0", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "make test-cov", + "dist": "browserify --standalone Qs index.js > dist/qs.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "gitHead": "e53b1b242a55f886531954ebdd78b3b20efadaf0", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@3.1.0", + "_shasum": "d0e9ae745233a12dc43fb4f3055bba446261153c", + "_from": "qs@>=3.1.0 <3.2.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "d0e9ae745233a12dc43fb4f3055bba446261153c", + "tarball": "http://registry.npmjs.org/qs/-/qs-3.1.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-3.1.0.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/parse.js new file mode 100644 index 0000000..9afbf35 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/parse.js @@ -0,0 +1,455 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }, { prototype: false }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }, { prototype: false }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }, { prototype: false }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }, { prototype: false }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }, { prototype: false }); + expect(Qs.parse('foo', {strictNullHandling: true})).to.deep.equal({ foo: null }, { prototype: false }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }, { prototype: false }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }, { prototype: false }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }, { prototype: false }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }, { prototype: false }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }, { prototype: false }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }, { prototype: false }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }, { prototype: false }); + expect(Qs.parse('foo=bar&baz', {strictNullHandling: true})).to.deep.equal({ foo: 'bar', baz: null }, { prototype: false }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }, { prototype: false }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }, { prototype: false }); + done(); + }); + + it('allows disabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ a: { b: 'c' } }, { prototype: false }); + expect(Qs.parse('a.b=c', { allowDots: false })).to.deep.equal({ 'a.b': 'c' }, { prototype: false }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }, { prototype: false }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }, { prototype: false }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, { prototype: false }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }, { prototype: false }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }, { prototype: false }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }, { prototype: false }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }, { prototype: false }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }, { prototype: false }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }, { prototype: false }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }, { prototype: false }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }, { prototype: false }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }, { prototype: false }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }, { prototype: false }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }, { prototype: false }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }, { prototype: false }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }, { prototype: false }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }, { prototype: false }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }, { prototype: false }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }, { prototype: false }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }, { prototype: false }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}, { prototype: false }); + expect(Qs.parse(null)).to.deep.equal({}, { prototype: false }); + expect(Qs.parse(undefined)).to.deep.equal({}, { prototype: false }); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }, { prototype: false }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }, { prototype: false }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }, { prototype: false }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }, { prototype: false }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }, { prototype: false }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({foo: [ {a: 'a', b: 'b'}, {a: 'aa', b: 'bb'} ]}, { prototype: false }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', hasOwnProperty: 'c' } }, { prototype: false }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', hasOwnProperty: 'c', x: 'y' } }, { prototype: false }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [ { baz: 'bar'} ], fool: { bad: 'baz' } }, { prototype: false }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz')).to.deep.equal({ foo: [ { baz: 'bar'} ], fool: { bad: { boo: 'baz' } } }, { prototype: false }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [[ { baz: 'bar'} ]], fool: { bad: 'baz' } }, { prototype: false }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }, { prototype: false }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }, { prototype: false }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }, { prototype: false }); + expect(Qs.parse('foo.bad=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }, { prototype: false }); + expect(Qs.parse('foo[]=bar&foo.bad=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }, { prototype: false }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }, { prototype: false }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb')).to.deep.equal({foo: [ {a: 'a', b: 'b'}, {a: 'aa', b: 'bb'} ]}, { prototype: false }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }, { prototype: false }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }, { prototype: false }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', {strictNullHandling: true})).to.deep.equal({ '{%:%}': null }, { prototype: false }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }, { prototype: false }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }, { prototype: false }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }, { prototype: false }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }, { prototype: false }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }, { prototype: false }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }, { prototype: false }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', {strictNullHandling: true})).to.deep.equal({ a: ['b', null, 'c', ''] }, { prototype: false }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', {strictNullHandling: true})).to.deep.equal({ a: ['b', '', 'c', null] }, { prototype: false }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }, { prototype: false }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }, { prototype: false }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }, { prototype: false }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }, { prototype: false }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }, { prototype: false }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }, { prototype: false }); + expect(Qs.parse('[]&a=b', {strictNullHandling: true})).to.deep.equal({ '0': null, a: 'b' }, { prototype: false }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }, { prototype: false }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }, { prototype: false }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }, { prototype: false }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }, { prototype: false }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }, { prototype: false }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }, { prototype: false }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }, { prototype: false }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }, { prototype: false }); + done(); + }); + + it('allows overriding array limit', function (done) { + + expect(Qs.parse('a[0]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '0': 'b' } }, { prototype: false }); + expect(Qs.parse('a[-1]=b', { arrayLimit: -1 })).to.deep.equal({ a: { '-1': 'b' } }, { prototype: false }); + expect(Qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }, { prototype: false }); + done(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }, { prototype: false }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': {'pop[bob]': 3}, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': {'pop[bob]': 3}, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected, { prototype: false }); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': {'pop[bob]': 3}, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': {'pop[bob]': 3}, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected, { prototype: false }); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': {'pop[bob]': { 'test': 3 }}, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': {'pop[bob]': { 'test': 3 }}, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected, { prototype: false }); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }, { prototype: false }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + expect(parsed).to.contain('foo'); + expect(parsed.foo).to.contain('bar', 'baz'); + expect(parsed.foo.bar).to.equal('baz'); + expect(parsed.foo.baz).to.deep.equal(a, { prototype: false }); + done(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }, { prototype: false }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a, { prototype: false }); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }, { prototype: false }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }, { prototype: false }); + done(); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/stringify.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..7a80c6c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/stringify.js @@ -0,0 +1,259 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('uses indices notation for arrays when indices=true', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { indices: true })).to.equal('a%5B0%5D=b&a%5B1%5D=c'); + done(); + }); + + it('uses indices notation for arrays when no arrayFormat is specified', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c'); + done(); + }); + + it('uses indices notation for arrays when no arrayFormat=indices', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })).to.equal('a%5B0%5D=b&a%5B1%5D=c'); + done(); + }); + + it('uses repeat notation for arrays when no arrayFormat=repeat', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })).to.equal('a=b&a=c'); + done(); + }); + + it('uses brackets notation for arrays when no arrayFormat=brackets', function (done) { + + expect(Qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })).to.equal('a%5B%5D=b&a%5B%5D=c'); + done(); + }); + + it('stringifies a complicated object', function (done) { + + expect(Qs.stringify({ a: { b: 'c', d: 'e' } })).to.equal('a%5Bb%5D=c&a%5Bd%5D=e'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, {strictNullHandling: true})).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, {strictNullHandling: true})).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, {strictNullHandling: true})).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, {strictNullHandling: false})).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, {strictNullHandling: true})).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, {strictNullHandling: false})).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b'})).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + expect(Qs.stringify({ a: 'b', c: 'd' })).to.equal('a=b&c=d'); + global.Buffer = tempBuffer; + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1}, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2]})).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/utils.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.npmignore new file mode 100644 index 0000000..7dccd97 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/LICENSE.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/LICENSE.txt new file mode 100644 index 0000000..eac1881 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/LICENSE.txt @@ -0,0 +1,4 @@ +Copyright 2012 Michael Hart (michael.hart.au@gmail.com) + +This project is free software released under the MIT license: +http://www.opensource.org/licenses/mit-license.php diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/README.md new file mode 100644 index 0000000..32fc982 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/README.md @@ -0,0 +1,38 @@ +# Decode streams into strings The Right Way(tm) + +```javascript +var fs = require('fs') +var zlib = require('zlib') +var strs = require('stringstream') + +var utf8Stream = fs.createReadStream('massiveLogFile.gz') + .pipe(zlib.createGunzip()) + .pipe(strs('utf8')) +``` + +No need to deal with `setEncoding()` weirdness, just compose streams +like they were supposed to be! + +Handles input and output encoding: + +```javascript +// Stream from utf8 to hex to base64... Why not, ay. +var hex64Stream = fs.createReadStream('myFile') + .pipe(strs('utf8', 'hex')) + .pipe(strs('hex', 'base64')) +``` + +Also deals with `base64` output correctly by aligning each emitted data +chunk so that there are no dangling `=` characters: + +```javascript +var stream = fs.createReadStream('myFile').pipe(strs('base64')) + +var base64Str = '' + +stream.on('data', function(data) { base64Str += data }) +stream.on('end', function() { + console.log('My base64 encoded file is: ' + base64Str) // Wouldn't work with setEncoding() + console.log('Original file is: ' + new Buffer(base64Str, 'base64')) +}) +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/example.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/example.js new file mode 100644 index 0000000..f82b85e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/example.js @@ -0,0 +1,27 @@ +var fs = require('fs') +var zlib = require('zlib') +var strs = require('stringstream') + +var utf8Stream = fs.createReadStream('massiveLogFile.gz') + .pipe(zlib.createGunzip()) + .pipe(strs('utf8')) + +utf8Stream.pipe(process.stdout) + +// Stream from utf8 to hex to base64... Why not, ay. +var hex64Stream = fs.createReadStream('myFile') + .pipe(strs('utf8', 'hex')) + .pipe(strs('hex', 'base64')) + +hex64Stream.pipe(process.stdout) + +// Deals with base64 correctly by aligning chunks +var stream = fs.createReadStream('myFile').pipe(strs('base64')) + +var base64Str = '' + +stream.on('data', function(data) { base64Str += data }) +stream.on('end', function() { + console.log('My base64 encoded file is: ' + base64Str) // Wouldn't work with setEncoding() + console.log('Original file is: ' + new Buffer(base64Str, 'base64')) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/package.json new file mode 100644 index 0000000..37b7bec --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/package.json @@ -0,0 +1,32 @@ +{ + "name": "stringstream", + "version": "0.0.4", + "description": "Encode and decode streams into string streams", + "author": { + "name": "Michael Hart", + "email": "michael.hart.au@gmail.com", + "url": "http://github.com/mhart" + }, + "main": "stringstream.js", + "keywords": [ + "string", + "stream", + "base64", + "gzip" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mhart/StringStream.git" + }, + "license": "MIT", + "readme": "# Decode streams into strings The Right Way(tm)\n\n```javascript\nvar fs = require('fs')\nvar zlib = require('zlib')\nvar strs = require('stringstream')\n\nvar utf8Stream = fs.createReadStream('massiveLogFile.gz')\n .pipe(zlib.createGunzip())\n .pipe(strs('utf8'))\n```\n\nNo need to deal with `setEncoding()` weirdness, just compose streams\nlike they were supposed to be!\n\nHandles input and output encoding:\n\n```javascript\n// Stream from utf8 to hex to base64... Why not, ay.\nvar hex64Stream = fs.createReadStream('myFile')\n .pipe(strs('utf8', 'hex'))\n .pipe(strs('hex', 'base64'))\n```\n\nAlso deals with `base64` output correctly by aligning each emitted data\nchunk so that there are no dangling `=` characters:\n\n```javascript\nvar stream = fs.createReadStream('myFile').pipe(strs('base64'))\n\nvar base64Str = ''\n\nstream.on('data', function(data) { base64Str += data })\nstream.on('end', function() {\n console.log('My base64 encoded file is: ' + base64Str) // Wouldn't work with setEncoding()\n console.log('Original file is: ' + new Buffer(base64Str, 'base64'))\n})\n```\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mhart/StringStream/issues" + }, + "homepage": "https://github.com/mhart/StringStream#readme", + "_id": "stringstream@0.0.4", + "_shasum": "0f0e3423f942960b5692ac324a57dd093bc41a92", + "_resolved": "https://registry.npmjs.org/stringstream/-/stringstream-0.0.4.tgz", + "_from": "stringstream@>=0.0.4 <0.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/stringstream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/stringstream.js new file mode 100644 index 0000000..4ece127 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/stringstream/stringstream.js @@ -0,0 +1,102 @@ +var util = require('util') +var Stream = require('stream') +var StringDecoder = require('string_decoder').StringDecoder + +module.exports = StringStream +module.exports.AlignedStringDecoder = AlignedStringDecoder + +function StringStream(from, to) { + if (!(this instanceof StringStream)) return new StringStream(from, to) + + Stream.call(this) + + if (from == null) from = 'utf8' + + this.readable = this.writable = true + this.paused = false + this.toEncoding = (to == null ? from : to) + this.fromEncoding = (to == null ? '' : from) + this.decoder = new AlignedStringDecoder(this.toEncoding) +} +util.inherits(StringStream, Stream) + +StringStream.prototype.write = function(data) { + if (!this.writable) { + var err = new Error('stream not writable') + err.code = 'EPIPE' + this.emit('error', err) + return false + } + if (this.fromEncoding) { + if (Buffer.isBuffer(data)) data = data.toString() + data = new Buffer(data, this.fromEncoding) + } + var string = this.decoder.write(data) + if (string.length) this.emit('data', string) + return !this.paused +} + +StringStream.prototype.flush = function() { + if (this.decoder.flush) { + var string = this.decoder.flush() + if (string.length) this.emit('data', string) + } +} + +StringStream.prototype.end = function() { + if (!this.writable && !this.readable) return + this.flush() + this.emit('end') + this.writable = this.readable = false + this.destroy() +} + +StringStream.prototype.destroy = function() { + this.decoder = null + this.writable = this.readable = false + this.emit('close') +} + +StringStream.prototype.pause = function() { + this.paused = true +} + +StringStream.prototype.resume = function () { + if (this.paused) this.emit('drain') + this.paused = false +} + +function AlignedStringDecoder(encoding) { + StringDecoder.call(this, encoding) + + switch (this.encoding) { + case 'base64': + this.write = alignedWrite + this.alignedBuffer = new Buffer(3) + this.alignedBytes = 0 + break + } +} +util.inherits(AlignedStringDecoder, StringDecoder) + +AlignedStringDecoder.prototype.flush = function() { + if (!this.alignedBuffer || !this.alignedBytes) return '' + var leftover = this.alignedBuffer.toString(this.encoding, 0, this.alignedBytes) + this.alignedBytes = 0 + return leftover +} + +function alignedWrite(buffer) { + var rem = (this.alignedBytes + buffer.length) % this.alignedBuffer.length + if (!rem && !this.alignedBytes) return buffer.toString(this.encoding) + + var returnBuffer = new Buffer(this.alignedBytes + buffer.length - rem) + + this.alignedBuffer.copy(returnBuffer, 0, 0, this.alignedBytes) + buffer.copy(returnBuffer, this.alignedBytes, 0, buffer.length - rem) + + buffer.copy(this.alignedBuffer, 0, buffer.length - rem, buffer.length) + this.alignedBytes = rem + + return returnBuffer.toString(this.encoding) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.editorconfig b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.editorconfig new file mode 100644 index 0000000..e09b844 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.editorconfig @@ -0,0 +1,12 @@ +# This file is for unifying the coding style for different editors and IDEs +# editorconfig.org + +root = true + +[*] +end_of_line = lf +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.jshintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.jshintrc new file mode 100644 index 0000000..fb11913 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.jshintrc @@ -0,0 +1,70 @@ +{ + "passfail" : false, + "maxerr" : 100, + + "browser" : false, + "node" : true, + "rhino" : false, + "couch" : false, + "wsh" : false, + + "jquery" : false, + "prototypejs" : false, + "mootools" : false, + "dojo" : false, + + "debug" : false, + "devel" : false, + + "esnext" : true, + "strict" : true, + "globalstrict" : true, + + "asi" : false, + "laxbreak" : false, + "bitwise" : true, + "boss" : false, + "curly" : true, + "eqeqeq" : false, + "eqnull" : true, + "evil" : false, + "expr" : false, + "forin" : false, + "immed" : true, + "lastsemic" : true, + "latedef" : false, + "loopfunc" : false, + "noarg" : true, + "regexp" : false, + "regexdash" : false, + "scripturl" : false, + "shadow" : false, + "supernew" : false, + "undef" : true, + "unused" : true, + + "newcap" : true, + "noempty" : true, + "nonew" : true, + "nomen" : false, + "onevar" : false, + "onecase" : true, + "plusplus" : false, + "proto" : false, + "sub" : true, + "trailing" : true, + "white" : false, + + "predef": [ + "describe", + "it", + "before", + "beforeEach", + "after", + "afterEach", + "expect", + "setTimeout", + "clearTimeout" + ], + "maxlen": 0 +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.npmignore new file mode 100644 index 0000000..5a8d2d8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.npmignore @@ -0,0 +1,4 @@ +.idea +node_modules/ +.*.sw[nmop] +npm-debug.log diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.travis.yml new file mode 100644 index 0000000..02059d0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: +- "0.10" +- "0.12" +- iojs +matrix: + fast_finish: true + allow_failures: + - node_js: 0.11 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/LICENSE new file mode 100644 index 0000000..84e0cad --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/LICENSE @@ -0,0 +1,74 @@ +Copyright (c) 2015, Salesforce.com, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=== + +The following exceptions apply: + +=== + +`pubSufTest()` of generate-pubsuffix.js is in the public domain. + + // Any copyright is dedicated to the Public Domain. + // http://creativecommons.org/publicdomain/zero/1.0/ + +=== + +`public-suffix.txt` was obtained from + +via . + +That file contains the usual Mozilla triple-license, for which this project uses it +under the terms of the MPL 1.1: + + // ***** BEGIN LICENSE BLOCK ***** + // Version: MPL 1.1/GPL 2.0/LGPL 2.1 + // + // The contents of this file are subject to the Mozilla Public License Version + // 1.1 (the "License"); you may not use this file except in compliance with + // the License. You may obtain a copy of the License at + // http://www.mozilla.org/MPL/ + // + // Software distributed under the License is distributed on an "AS IS" basis, + // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + // for the specific language governing rights and limitations under the + // License. + // + // The Original Code is the Public Suffix List. + // + // The Initial Developer of the Original Code is + // Jo Hermans . + // Portions created by the Initial Developer are Copyright (C) 2007 + // the Initial Developer. All Rights Reserved. + // + // Contributor(s): + // Ruben Arakelyan + // Gervase Markham + // Pamela Greene + // David Triendl + // Jothan Frakes + // The kind representatives of many TLD registries + // + // Alternatively, the contents of this file may be used under the terms of + // either the GNU General Public License Version 2 or later (the "GPL"), or + // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + // in which case the provisions of the GPL or the LGPL are applicable instead + // of those above. If you wish to allow use of your version of this file only + // under the terms of either the GPL or the LGPL, and not to allow others to + // use your version of this file under the terms of the MPL, indicate your + // decision by deleting the provisions above and replace them with the notice + // and other provisions required by the GPL or the LGPL. If you do not delete + // the provisions above, a recipient may use your version of this file under + // the terms of any one of the MPL, the GPL or the LGPL. + // + // ***** END LICENSE BLOCK ***** diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/README.md new file mode 100644 index 0000000..f56d153 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/README.md @@ -0,0 +1,422 @@ +[RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js + +[![Build Status](https://travis-ci.org/SalesforceEng/tough-cookie.png?branch=master)](https://travis-ci.org/SalesforceEng/tough-cookie) + +[![NPM Stats](https://nodei.co/npm/tough-cookie.png?downloads=true&stars=true)](https://npmjs.org/package/tough-cookie) +![NPM Downloads](https://nodei.co/npm-dl/tough-cookie.png?months=9) + +# Synopsis + +``` javascript +var tough = require('tough-cookie'); // note: not 'cookie', 'cookies' or 'node-cookie' +var Cookie = tough.Cookie; +var cookie = Cookie.parse(header); +cookie.value = 'somethingdifferent'; +header = cookie.toString(); + +var cookiejar = new tough.CookieJar(); +cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); +// ... +cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { + res.headers['cookie'] = cookies.join('; '); +}); +``` + +# Installation + +It's _so_ easy! + +`npm install tough-cookie` + +Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. + +# API + +tough +===== + +Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". + +**Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. + +parseDate(string) +----------------- + +Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. + +formatDate(date) +---------------- + +Format a Date into a RFC1123 string (the RFC6265-recommended format). + +canonicalDomain(str) +-------------------- + +Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). + +domainMatch(str,domStr[,canonicalize=true]) +------------------------------------------- + +Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". + +The `canonicalize` parameter will run the other two paramters through `canonicalDomain` or not. + +defaultPath(path) +----------------- + +Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. + +The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. + +pathMatch(reqPath,cookiePath) +----------------------------- + +Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. + +This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. + +parse(header) +---------------------------- + +alias for `Cookie.parse(header)` + +fromJSON(string) +---------------- + +alias for `Cookie.fromJSON(string)` + +getPublicSuffix(hostname) +------------------------- + +Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. + +For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. + +For further information, see http://publicsuffix.org/. This module derives its list from that site. + +cookieCompare(a,b) +------------------ + +For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). Longest `.path`s go first, then sorted oldest to youngest. + +``` javascript +var cookies = [ /* unsorted array of Cookie objects */ ]; +cookies = cookies.sort(cookieCompare); +``` + +permuteDomain(domain) +--------------------- + +Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. + + +permutePath(path) +----------------- + +Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. + +Cookie +====== + +Cookie.parse(header) +----------------------------------- + +Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. + +Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: + +``` javascript +if (res.headers['set-cookie'] instanceof Array) + cookies = res.headers['set-cookie'].map(function (c) { return (Cookie.parse(c)); }); +else + cookies = [Cookie.parse(res.headers['set-cookie'])]; +``` + +Cookie.fromJSON(string) +----------------------- + +Convert a JSON string to a `Cookie` object. Does a `JSON.parse()` and converts the `.created`, `.lastAccessed` and `.expires` properties into `Date` objects. + +Properties +========== + + * _key_ - string - the name or key of the cookie (default "") + * _value_ - string - the value of the cookie (default "") + * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` + * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` + * _domain_ - string - the `Domain=` attribute of the cookie + * _path_ - string - the `Path=` of the cookie + * _secure_ - boolean - the `Secure` cookie flag + * _httpOnly_ - boolean - the `HttpOnly` cookie flag + * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) + +After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: + + * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) + * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. + * _created_ - `Date` - when this cookie was added to the jar + * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. + +Construction([{options}]) +------------ + +Receives an options object that can contain any Cookie properties, uses the default for unspecified properties. + +.toString() +----------- + +encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. + +.cookieString() +--------------- + +encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). + +.setExpires(String) +------------------- + +sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. + +.setMaxAge(number) +------------------- + +sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. + +.expiryTime([now=Date.now()]) +----------------------------- + +.expiryDate([now=Date.now()]) +----------------------------- + +expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. + +Max-Age takes precedence over Expires (as per the RFC). The `.created` attribute -- or, by default, the `now` paramter -- is used to offset the `.maxAge` attribute. + +If Expires (`.expires`) is set, that's returned. + +Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). + +.TTL([now=Date.now()]) +--------- + +compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. + +The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. + +.canonicalizedDoman() +--------------------- + +.cdomain() +---------- + +return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. + +.validate() +----------- + +Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. + +validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: + +``` javascript +if (cookie.validate() === true) { + // it's tasty +} else { + // yuck! +} +``` + +CookieJar +========= + +Construction([store = new MemoryCookieStore()][, rejectPublicSuffixes]) +------------ + +Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. + + +Attributes +---------- + + * _rejectPublicSuffixes_ - boolean - reject cookies with domains like "com" and "co.uk" (default: `true`) + +Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. + +.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie)) +------------------------------------------------------------------- + +Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.created`, `.lastAccessed` and `.hostOnly` properties. + +The `options` object can be omitted and can have the following properties: + + * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. + * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. + * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies + * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. CookieStore errors aren't ignored by this option. + +As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). + +.setCookieSync(cookieOrString, currentUrl, [{options}]) +------------------------------------------------------- + +Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +.storeCookie(cookie, [{options},] cb(err,cookie)) +------------------------------------------------- + +__REMOVED__ removed in lieu of the CookieStore API below + +.getCookies(currentUrl, [{options},] cb(err,cookies)) +----------------------------------------------------- + +Retrieve the list of cookies that can be sent in a Cookie header for the current url. + +If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. + +The `options` object can be omitted and can have the following properties: + + * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. + * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. + * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies + * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). + * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the CookieStore `fetchCookies` function (the default MemoryCookieStore supports it). + +The `.lastAccessed` property of the returned cookies will have been updated. + +.getCookiesSync(currentUrl, [{options}]) +---------------------------------------- + +Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +.getCookieString(...) +--------------------- + +Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. + +.getCookieStringSync(...) +------------------------- + +Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +.getSetCookieStrings(...) +------------------------- + +Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. + +.getSetCookieStringsSync(...) +----------------------------- + +Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +Store +===== + +Base class for CookieJar stores. + +# CookieStore API + +The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. + +Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set, then the `*Sync` methods on the CookieJar can be used. + +All `domain` parameters will have been normalized before calling. + +The Cookie store must have all of the following methods. + +store.findCookie(domain, path, key, cb(err,cookie)) +--------------------------------------------------- + +Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. + +Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). + +store.findCookies(domain, path, cb(err,cookies)) +------------------------------------------------ + +Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. + +If no cookies are found, the callback MUST be passed an empty array. + +The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. + +As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). + +store.putCookie(cookie, cb(err)) +-------------------------------- + +Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. + +The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. + +Pass an error if the cookie cannot be stored. + +store.updateCookie(oldCookie, newCookie, cb(err)) +------------------------------------------------- + +Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. + +The `.lastAccessed` property will always be different between the two objects and `.created` will always be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are sorted (or selected for deletion). + +Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. + +The `newCookie` and `oldCookie` objects MUST NOT be modified. + +Pass an error if the newCookie cannot be stored. + +store.removeCookie(domain, path, key, cb(err)) +---------------------------------------------- + +Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). + +The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. + +store.removeCookies(domain, path, cb(err)) +------------------------------------------ + +Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. + +Pass an error ONLY if removing any existing cookies failed. + +MemoryCookieStore +================= + +Inherits from Store. + +Just-in-memory CookieJar synchronous store implementation, used by default. + +# Copyright and License + +(tl;dr: BSD-3-Clause with some MPL/1.1) + +```text + Copyright (c) 2015, Salesforce.com, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of Salesforce.com nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +``` + +Portions may be licensed under different licenses (in particular public-suffix.txt is MPL/1.1); please read the LICENSE file for full details. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js new file mode 100644 index 0000000..ba054f4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/generate-pubsuffix.js @@ -0,0 +1,293 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +var fs = require('fs'); +var assert = require('assert'); +var punycode = require('punycode'); + +fs.readFile('./public-suffix.txt', 'utf8', function(err,string) { + if (err) { + throw err; + } + var lines = string.split("\n"); + process.nextTick(function() { + processList(lines); + }); +}); + +var index = {}; + +var COMMENT = new RegExp('//.+'); +function processList(lines) { + while (lines.length) { + var line = lines.shift(); + line = line.replace(COMMENT,'').trim(); + if (!line) { + continue; + } + addToIndex(index,line); + } + + pubSufTest(); + + var w = fs.createWriteStream('./lib/pubsuffix.js',{ + flags: 'w', + encoding: 'utf8', + mode: parseInt('644',8) + }); + w.on('end', process.exit); + w.write("/****************************************************\n"); + w.write(" * AUTOMATICALLY GENERATED by generate-pubsuffix.js *\n"); + w.write(" * DO NOT EDIT! *\n"); + w.write(" ****************************************************/\n\n"); + + w.write('"use strict";\n\n'); + w.write("var punycode = require('punycode');\n\n"); + + w.write("module.exports.getPublicSuffix = "); + w.write(getPublicSuffix.toString()); + w.write(";\n\n"); + + w.write("// The following generated structure is used under the MPL version 1.1\n"); + w.write("// See public-suffix.txt for more information\n\n"); + w.write("var index = module.exports.index = Object.freeze(\n"); + w.write(JSON.stringify(index)); + w.write(");\n\n"); + w.write("// END of automatically generated file\n"); + + w.end(); +} + +function addToIndex(index,line) { + var prefix = ''; + if (line.replace(/^(!|\*\.)/)) { + prefix = RegExp.$1; + line = line.slice(prefix.length); + } + line = prefix + punycode.toASCII(line); + + if (line.substr(0,1) == '!') { + index[line.substr(1)] = false; + } else { + index[line] = true; + } +} + +// include the licence in the function since it gets written to pubsuffix.js +function getPublicSuffix(domain) { + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + if (!domain) { + return null; + } + if (domain.match(/^\./)) { + return null; + } + var asciiDomain = punycode.toASCII(domain); + var converted = false; + if (asciiDomain !== domain) { + domain = asciiDomain; + converted = true; + } + if (index[domain]) { + return null; + } + + domain = domain.toLowerCase(); + var parts = domain.split('.').reverse(); + + var suffix = ''; + var suffixLen = 0; + for (var i=0; i suffixLen) { + var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.'); + return converted ? punycode.toUnicode(publicSuffix) : publicSuffix; + } + + return null; +} + +function checkPublicSuffix(give,get) { + var got = getPublicSuffix(give); + assert.equal(got, get, give+' should be '+(get==null?'NULL':get)+' but got '+got); +} + +// pubSufTest() was converted to JavaScript from http://mxr.mozilla.org/mozilla-central/source/netwerk/test/unit/data/test_psl.txt?raw=1 +function pubSufTest() { + // For this function-scope and this function-scope ONLY: + // Any copyright is dedicated to the Public Domain. + // http://creativecommons.org/publicdomain/zero/1.0/ + + // NULL input. + checkPublicSuffix(null, null); + // Mixed case. + checkPublicSuffix('COM', null); + checkPublicSuffix('example.COM', 'example.com'); + checkPublicSuffix('WwW.example.COM', 'example.com'); + // Leading dot. + checkPublicSuffix('.com', null); + checkPublicSuffix('.example', null); + checkPublicSuffix('.example.com', null); + checkPublicSuffix('.example.example', null); + // Unlisted TLD. + checkPublicSuffix('example', null); + checkPublicSuffix('example.example', 'example.example'); + checkPublicSuffix('b.example.example', 'example.example'); + checkPublicSuffix('a.b.example.example', 'example.example'); + // Listed, but non-Internet, TLD. + //checkPublicSuffix('local', null); + //checkPublicSuffix('example.local', null); + //checkPublicSuffix('b.example.local', null); + //checkPublicSuffix('a.b.example.local', null); + // TLD with only 1 rule. + checkPublicSuffix('biz', null); + checkPublicSuffix('domain.biz', 'domain.biz'); + checkPublicSuffix('b.domain.biz', 'domain.biz'); + checkPublicSuffix('a.b.domain.biz', 'domain.biz'); + // TLD with some 2-level rules. + checkPublicSuffix('com', null); + checkPublicSuffix('example.com', 'example.com'); + checkPublicSuffix('b.example.com', 'example.com'); + checkPublicSuffix('a.b.example.com', 'example.com'); + checkPublicSuffix('uk.com', null); + checkPublicSuffix('example.uk.com', 'example.uk.com'); + checkPublicSuffix('b.example.uk.com', 'example.uk.com'); + checkPublicSuffix('a.b.example.uk.com', 'example.uk.com'); + checkPublicSuffix('test.ac', 'test.ac'); + // TLD with only 1 (wildcard) rule. + checkPublicSuffix('cy', null); + checkPublicSuffix('c.cy', null); + checkPublicSuffix('b.c.cy', 'b.c.cy'); + checkPublicSuffix('a.b.c.cy', 'b.c.cy'); + // More complex TLD. + checkPublicSuffix('jp', null); + checkPublicSuffix('test.jp', 'test.jp'); + checkPublicSuffix('www.test.jp', 'test.jp'); + checkPublicSuffix('ac.jp', null); + checkPublicSuffix('test.ac.jp', 'test.ac.jp'); + checkPublicSuffix('www.test.ac.jp', 'test.ac.jp'); + checkPublicSuffix('kyoto.jp', null); + checkPublicSuffix('test.kyoto.jp', 'test.kyoto.jp'); + checkPublicSuffix('ide.kyoto.jp', null); + checkPublicSuffix('b.ide.kyoto.jp', 'b.ide.kyoto.jp'); + checkPublicSuffix('a.b.ide.kyoto.jp', 'b.ide.kyoto.jp'); + checkPublicSuffix('c.kobe.jp', null); + checkPublicSuffix('b.c.kobe.jp', 'b.c.kobe.jp'); + checkPublicSuffix('a.b.c.kobe.jp', 'b.c.kobe.jp'); + checkPublicSuffix('city.kobe.jp', 'city.kobe.jp'); + checkPublicSuffix('www.city.kobe.jp', 'city.kobe.jp'); + // TLD with a wildcard rule and exceptions. + checkPublicSuffix('ck', null); + checkPublicSuffix('test.ck', null); + checkPublicSuffix('b.test.ck', 'b.test.ck'); + checkPublicSuffix('a.b.test.ck', 'b.test.ck'); + checkPublicSuffix('www.ck', 'www.ck'); + checkPublicSuffix('www.www.ck', 'www.ck'); + // US K12. + checkPublicSuffix('us', null); + checkPublicSuffix('test.us', 'test.us'); + checkPublicSuffix('www.test.us', 'test.us'); + checkPublicSuffix('ak.us', null); + checkPublicSuffix('test.ak.us', 'test.ak.us'); + checkPublicSuffix('www.test.ak.us', 'test.ak.us'); + checkPublicSuffix('k12.ak.us', null); + checkPublicSuffix('test.k12.ak.us', 'test.k12.ak.us'); + checkPublicSuffix('www.test.k12.ak.us', 'test.k12.ak.us'); + // IDN labels. + checkPublicSuffix('食狮.com.cn', '食狮.com.cn'); + checkPublicSuffix('食狮.公司.cn', '食狮.公司.cn'); + checkPublicSuffix('www.食狮.公司.cn', '食狮.公司.cn'); + checkPublicSuffix('shishi.公司.cn', 'shishi.公司.cn'); + checkPublicSuffix('公司.cn', null); + checkPublicSuffix('食狮.中国', '食狮.中国'); + checkPublicSuffix('www.食狮.中国', '食狮.中国'); + checkPublicSuffix('shishi.中国', 'shishi.中国'); + checkPublicSuffix('中国', null); + // Same as above, but punycoded. + checkPublicSuffix('xn--85x722f.com.cn', 'xn--85x722f.com.cn'); + checkPublicSuffix('xn--85x722f.xn--55qx5d.cn', 'xn--85x722f.xn--55qx5d.cn'); + checkPublicSuffix('www.xn--85x722f.xn--55qx5d.cn', 'xn--85x722f.xn--55qx5d.cn'); + checkPublicSuffix('shishi.xn--55qx5d.cn', 'shishi.xn--55qx5d.cn'); + checkPublicSuffix('xn--55qx5d.cn', null); + checkPublicSuffix('xn--85x722f.xn--fiqs8s', 'xn--85x722f.xn--fiqs8s'); + checkPublicSuffix('www.xn--85x722f.xn--fiqs8s', 'xn--85x722f.xn--fiqs8s'); + checkPublicSuffix('shishi.xn--fiqs8s', 'shishi.xn--fiqs8s'); + checkPublicSuffix('xn--fiqs8s', null); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/cookie.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/cookie.js new file mode 100644 index 0000000..bec7f90 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/cookie.js @@ -0,0 +1,1088 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +var net = require('net'); +var urlParse = require('url').parse; +var pubsuffix = require('./pubsuffix'); +var Store = require('./store').Store; +var MemoryCookieStore = require('./memstore').MemoryCookieStore; +var pathMatch = require('./pathMatch').pathMatch; + +var punycode; +try { + punycode = require('punycode'); +} catch(e) { + console.warn("cookie: can't load punycode; won't use punycode for domain normalization"); +} + +var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +var COOKIE_OCTET = /[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/; +var COOKIE_OCTETS = new RegExp('^'+COOKIE_OCTET.source+'$'); + +// Double quotes are part of the value (see: S4.1.1). +// '\r', '\n' and '\0' should be treated as a terminator in the "relaxed" mode +// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60) +// '=' and ';' are attribute/values separators +// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L64) +var COOKIE_PAIR = /^([^=;]+)\s*=\s*(("?)[^\n\r\0]*\3)/; + +// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; + +// Used for checking whether or not there is a trailing semi-colon +var TRAILING_SEMICOLON = /;+$/; + +var DAY_OF_MONTH = /^(\d{1,2})[^\d]*$/; +var TIME = /^(\d{1,2})[^\d]*:(\d{1,2})[^\d]*:(\d{1,2})[^\d]*$/; +var MONTH = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i; + +var MONTH_TO_NUM = { + jan:0, feb:1, mar:2, apr:3, may:4, jun:5, + jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 +}; +var NUM_TO_MONTH = [ + 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' +]; +var NUM_TO_DAY = [ + 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' +]; + +var YEAR = /^(\d{2}|\d{4})$/; // 2 to 4 digits + +var MAX_TIME = 2147483647000; // 31-bit max +var MIN_TIME = 0; // 31-bit min + +var cookiesCreated = 0; // Number of cookies created in runtime + + +// RFC6265 S5.1.1 date parser: +function parseDate(str) { + if (!str) { + return; + } + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + var tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + var hour = null; + var minutes = null; + var seconds = null; + var day = null; + var month = null; + var year = null; + + for (var i=0; i 23 || minutes > 59 || seconds > 59) { + return; + } + + continue; + } + } + + /* 2.2. If the found-day-of-month flag is not set and the date-token matches + * the day-of-month production, set the found-day-of- month flag and set + * the day-of-month-value to the number denoted by the date-token. Skip + * the remaining sub-steps and continue to the next date-token. + */ + if (day === null) { + result = DAY_OF_MONTH.exec(token); + if (result) { + day = parseInt(result, 10); + /* RFC6265 S5.1.1.5: + * [fail if] the day-of-month-value is less than 1 or greater than 31 + */ + if(day < 1 || day > 31) { + return; + } + continue; + } + } + + /* 2.3. If the found-month flag is not set and the date-token matches the + * month production, set the found-month flag and set the month-value to + * the month denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (month === null) { + result = MONTH.exec(token); + if (result) { + month = MONTH_TO_NUM[result[1].toLowerCase()]; + continue; + } + } + + /* 2.4. If the found-year flag is not set and the date-token matches the year + * production, set the found-year flag and set the year-value to the number + * denoted by the date-token. Skip the remaining sub-steps and continue to + * the next date-token. + */ + if (year === null) { + result = YEAR.exec(token); + if (result) { + year = parseInt(result[0], 10); + /* From S5.1.1: + * 3. If the year-value is greater than or equal to 70 and less + * than or equal to 99, increment the year-value by 1900. + * 4. If the year-value is greater than or equal to 0 and less + * than or equal to 69, increment the year-value by 2000. + */ + if (70 <= year && year <= 99) { + year += 1900; + } else if (0 <= year && year <= 69) { + year += 2000; + } + + if (year < 1601) { + return; // 5. ... the year-value is less than 1601 + } + } + } + } + + if (seconds === null || day === null || month === null || year === null) { + return; // 5. ... at least one of the found-day-of-month, found-month, found- + // year, or found-time flags is not set, + } + + return new Date(Date.UTC(year, month, day, hour, minutes, seconds)); +} + +function formatDate(date) { + var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; + var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; + var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; + var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; + return NUM_TO_DAY[date.getUTCDay()] + ', ' + + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ + h+':'+m+':'+s+' GMT'; +} + +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); +} + +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * "The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ + + /* "* The string is a host name (i.e., not an IP address)." */ + if (net.isIP(str)) { + return false; + } + + /* "* The domain string is a suffix of the string" */ + var idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // e.g "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { // it's not a suffix + return false; + } + + /* "* The last character of the string that is not included in the domain + * string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; + } + + return true; +} + + +// RFC6265 S5.1.4 Paths and Path-Match + +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0,1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + var rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} + + +function parse(str) { + str = str.trim(); + + // S4.1.1 Trailing semi-colons are not part of the specification. + var semiColonCheck = TRAILING_SEMICOLON.exec(str); + if (semiColonCheck) { + str = str.slice(0, semiColonCheck.index); + } + + // We use a regex to parse the "name-value-pair" part of S5.2 + var firstSemi = str.indexOf(';'); // S5.2 step 1 + var result = COOKIE_PAIR.exec(firstSemi === -1 ? str : str.substr(0,firstSemi)); + + // Rx satisfies the "the name string is empty" and "lacks a %x3D ("=")" + // constraints as well as trimming any whitespace. + if (!result) { + return; + } + + var c = new Cookie(); + c.key = result[1].trim(); + c.value = result[2].trim(); + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + var unparsed = str.slice(firstSemi).replace(/^\s*;\s*/,'').trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + var cookie_avs = unparsed.split(/\s*;\s*/); + while (cookie_avs.length) { + var av = cookie_avs.shift(); + var av_sep = av.indexOf('='); + var av_key, av_value; + + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0,av_sep); + av_value = av.substr(av_sep+1); + } + + av_key = av_key.trim().toLowerCase(); + + if (av_value) { + av_value = av_value.trim(); + } + + switch(av_key) { + case 'expires': // S5.2.1 + if (av_value) { + var exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; + } + } + break; + + case 'max-age': // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + var delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; + + case 'domain': // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + var domain = av_value.trim().replace(/^\./, ''); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; + + case 'path': // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; + + case 'secure': // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; + + case 'httponly': // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + // ensure a default date for sorting: + c.creation = new Date(); + //NOTE: add runtime index for the cookieCompare() to resolve the situation when Date's precision is not enough . + //Store initial UTC time as well, so we will be able to determine if we need to fallback to the Date object. + c._creationRuntimeIdx = ++cookiesCreated; + c._initialCreationTime = c.creation.getTime(); + return c; +} + +function fromJSON(str) { + if (!str) { + return null; + } + + var obj; + try { + obj = JSON.parse(str); + } catch (e) { + return null; + } + + var c = new Cookie(); + for (var i=0; i 1) { + var lindex = path.lastIndexOf('/'); + if (lindex === 0) { + break; + } + path = path.substr(0,lindex); + permutations.push(path); + } + permutations.push('/'); + return permutations; +} + +function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } + catch(err) { + // Silently swallow error + } + + return urlParse(url); +} + +function Cookie (opts) { + if (typeof opts !== "object") { + return; + } + Object.keys(opts).forEach(function (key) { + if (Cookie.prototype.hasOwnProperty(key)) { + this[key] = opts[key] || Cookie.prototype[key]; + } + }.bind(this)); +} + +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; + +Cookie.prototype.key = ""; +Cookie.prototype.value = ""; + +// the order in which the RFC has them: +Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity +Cookie.prototype.maxAge = null; // takes precedence over expires for TTL +Cookie.prototype.domain = null; +Cookie.prototype.path = null; +Cookie.prototype.secure = false; +Cookie.prototype.httpOnly = false; +Cookie.prototype.extensions = null; + +// set by the CookieJar: +Cookie.prototype.hostOnly = null; // boolean when set +Cookie.prototype.pathIsDefault = null; // boolean when set +Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse +Cookie.prototype._initialCreationTime = null; // Used to determine if cookie.creation was modified +Cookie.prototype._creationRuntimeIdx = null; // Runtime index of the created cookie, used in cookieCompare() +Cookie.prototype.lastAccessed = null; // Date when set + +var cookieProperties = Object.freeze(Object.keys(Cookie.prototype).map(function(p) { + if (p instanceof Function) { + return; + } + return p; +})); +var numCookieProperties = cookieProperties.length; + +Cookie.prototype.inspect = function inspect() { + var now = Date.now(); + return 'Cookie="'+this.toString() + + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + + '"'; +}; + +Cookie.prototype.validate = function validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } + + var cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this + } + var suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { // it's a public suffix + return false; + } + } + return true; +}; + +Cookie.prototype.setExpires = function setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } +}; + +Cookie.prototype.setMaxAge = function setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } +}; + +// gives Cookie header format +Cookie.prototype.cookieString = function cookieString() { + var val = this.value; + if (val == null) { + val = ''; + } + return this.key+'='+val; +}; + +// gives Set-Cookie header format +Cookie.prototype.toString = function toString() { + var str = this.cookieString(); + + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += '; Expires='+formatDate(this.expires); + } else { + str += '; Expires='+this.expires; + } + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += '; Max-Age='+this.maxAge; + } + + if (this.domain && !this.hostOnly) { + str += '; Domain='+this.domain; + } + if (this.path) { + str += '; Path='+this.path; + } + + if (this.secure) { + str += '; Secure'; + } + if (this.httpOnly) { + str += '; HttpOnly'; + } + if (this.extensions) { + this.extensions.forEach(function(ext) { + str += '; '+ext; + }); + } + + return str; +}; + +// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere) +// S5.3 says to give the "latest representable date" for which we use Infinity +// For "expired" we use 0 +Cookie.prototype.TTL = function TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge<=0 ? 0 : this.maxAge*1000; + } + + var expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; + } + + if (expires == Infinity) { + return Infinity; + } + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; +}; + +// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere) +Cookie.prototype.expiryTime = function expiryTime(now) { + if (this.maxAge != null) { + var relativeTo = this.creation || now || new Date(); + var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); +}; + +// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() +// elsewhere), except it returns a Date +Cookie.prototype.expiryDate = function expiryDate(now) { + var millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } +}; + +// This replaces the "persistent-flag" parts of S5.3 step 3 +Cookie.prototype.isPersistent = function isPersistent() { + return (this.maxAge != null || this.expires != Infinity); +}; + +// Mostly S5.1.2 and S5.2.3: +Cookie.prototype.cdomain = +Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); +}; + + +function CookieJar(store, rejectPublicSuffixes) { + if (rejectPublicSuffixes != null) { + this.rejectPublicSuffixes = rejectPublicSuffixes; + } + + if (!store) { + store = new MemoryCookieStore(); + } + this.store = store; +} +CookieJar.prototype.store = null; +CookieJar.prototype.rejectPublicSuffixes = true; +var CAN_BE_SYNC = []; + +CAN_BE_SYNC.push('setCookie'); +CookieJar.prototype.setCookie = function(cookie, url, options, cb) { + var err; + var context = getCookieContext(url); + if (options instanceof Function) { + cb = options; + options = {}; + } + + var host = canonicalDomain(context.hostname); + + // S5.3 step 1 + if (!(cookie instanceof Cookie)) { + cookie = Cookie.parse(cookie); + } + if (!cookie) { + err = new Error("Cookie failed to parse"); + return cb(options.ignoreError ? null : err); + } + + // S5.3 step 2 + var now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + var suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); + } + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host); + return cb(options.ignoreError ? null : err); + } + + if (cookie.hostOnly == null) { // don't reset if already set + cookie.hostOnly = false; + } + + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + //S5.2.4 If the attribute-value is empty or if the first character of the + //attribute-value is not %x2F ("/"): + //Let cookie-path be the default-path. + if (!cookie.path || cookie.path[0] !== '/') { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + var store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); + } + + var next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 + } + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); +}; + +// RFC6365 S5.4 +CAN_BE_SYNC.push('getCookies'); +CookieJar.prototype.getCookies = function(url, options, cb) { + var context = getCookieContext(url); + if (options instanceof Function) { + cb = options; + options = {}; + } + + var host = canonicalDomain(context.hostname); + var path = context.pathname || '/'; + + var secure = options.secure; + if (secure == null && context.protocol && + (context.protocol == 'https:' || context.protocol == 'wss:')) + { + secure = true; + } + + var http = options.http; + if (http == null) { + http = true; + } + + var now = options.now || Date.now(); + var expireCheck = options.expire !== false; + var allPaths = !!options.allPaths; + var store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; + } + } else { + if (!domainMatch(host, c.domain, false)) { + return false; + } + } + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; + } + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; + } + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; + } + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored + return false; + } + + return true; + } + + store.findCookies(host, allPaths ? null : path, function(err,cookies) { + if (err) { + return cb(err); + } + + cookies = cookies.filter(matchingCookie); + + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } + + // S5.4 part 3 + var now = new Date(); + cookies.forEach(function(c) { + c.lastAccessed = now; + }); + // TODO persist lastAccessed + + cb(null,cookies); + }); +}; + +CAN_BE_SYNC.push('getCookieString'); +CookieJar.prototype.getCookieString = function(/*..., cb*/) { + var args = Array.prototype.slice.call(arguments,0); + var cb = args.pop(); + var next = function(err,cookies) { + if (err) { + cb(err); + } else { + cb(null, cookies + .sort(cookieCompare) + .map(function(c){ + return c.cookieString(); + }) + .join('; ')); + } + }; + args.push(next); + this.getCookies.apply(this,args); +}; + +CAN_BE_SYNC.push('getSetCookieStrings'); +CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) { + var args = Array.prototype.slice.call(arguments,0); + var cb = args.pop(); + var next = function(err,cookies) { + if (err) { + cb(err); + } else { + cb(null, cookies.map(function(c){ + return c.toString(); + })); + } + }; + args.push(next); + this.getCookies.apply(this,args); +}; + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function() { + if (!this.store.synchronous) { + throw new Error('CookieJar store is not synchronous; use async API instead.'); + } + + var args = Array.prototype.slice.call(arguments); + var syncErr, syncResult; + args.push(function syncCb(err, result) { + syncErr = err; + syncResult = result; + }); + this[method].apply(this, args); + + if (syncErr) { + throw syncErr; + } + return syncResult; + }; +} + +// wrap all declared CAN_BE_SYNC methods in the sync wrapper +CAN_BE_SYNC.forEach(function(method) { + CookieJar.prototype[method+'Sync'] = syncWrap(method); +}); + +module.exports = { + CookieJar: CookieJar, + Cookie: Cookie, + Store: Store, + MemoryCookieStore: MemoryCookieStore, + parseDate: parseDate, + formatDate: formatDate, + parse: parse, + fromJSON: fromJSON, + domainMatch: domainMatch, + defaultPath: defaultPath, + pathMatch: pathMatch, + getPublicSuffix: pubsuffix.getPublicSuffix, + cookieCompare: cookieCompare, + permuteDomain: require('./permuteDomain').permuteDomain, + permutePath: permutePath, + canonicalDomain: canonicalDomain +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/memstore.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/memstore.js new file mode 100644 index 0000000..a9ddc6f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/memstore.js @@ -0,0 +1,142 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +var Store = require('./store').Store; +var permuteDomain = require('./permuteDomain').permuteDomain; +var pathMatch = require('./pathMatch').pathMatch; +var util = require('util'); + +function MemoryCookieStore() { + Store.call(this); + this.idx = {}; +} +util.inherits(MemoryCookieStore, Store); +exports.MemoryCookieStore = MemoryCookieStore; +MemoryCookieStore.prototype.idx = null; +MemoryCookieStore.prototype.synchronous = true; + +// force a default depth: +MemoryCookieStore.prototype.inspect = function() { + return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; +}; + +MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null,undefined); + } + if (!this.idx[domain][path]) { + return cb(null,undefined); + } + return cb(null,this.idx[domain][path][key]||null); +}; + +MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { + var results = []; + if (!domain) { + return cb(null,[]); + } + + var pathMatcher; + if (!path) { + // null means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (var curPath in domainIndex) { + var pathIndex = domainIndex[curPath]; + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + + } else { + pathMatcher = function matchRFC(domainIndex) { + //NOTE: we should use path-match algorithm from S5.1.4 here + //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) + Object.keys(domainIndex).forEach(function (cookiePath) { + if (pathMatch(path, cookiePath)) { + var pathIndex = domainIndex[cookiePath]; + + for (var key in pathIndex) { + results.push(pathIndex[key]); + } + } + }); + }; + } + + var domains = permuteDomain(domain) || [domain]; + var idx = this.idx; + domains.forEach(function(curDomain) { + var domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null,results); +}; + +MemoryCookieStore.prototype.putCookie = function(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); +}; + +MemoryCookieStore.prototype.updateCookie = function updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie,cb); +}; + +MemoryCookieStore.prototype.removeCookie = function removeCookie(domain, path, key, cb) { + if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { + delete this.idx[domain][path][key]; + } + cb(null); +}; + +MemoryCookieStore.prototype.removeCookies = function removeCookies(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js new file mode 100644 index 0000000..7c7a79f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js @@ -0,0 +1,61 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch (reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + var idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } + + return false; +} + +exports.pathMatch = pathMatch; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js new file mode 100644 index 0000000..8af841b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js @@ -0,0 +1,56 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +var pubsuffix = require('./pubsuffix'); + +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +function permuteDomain (domain) { + var pubSuf = pubsuffix.getPublicSuffix(domain); + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; + } + + var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + var parts = prefix.split('.').reverse(); + var cur = pubSuf; + var permutations = [cur]; + while (parts.length) { + cur = parts.shift() + '.' + cur; + permutations.push(cur); + } + return permutations; +} + +exports.permuteDomain = permuteDomain; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js new file mode 100644 index 0000000..f07aa2b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js @@ -0,0 +1,98 @@ +/**************************************************** + * AUTOMATICALLY GENERATED by generate-pubsuffix.js * + * DO NOT EDIT! * + ****************************************************/ + +"use strict"; + +var punycode = require('punycode'); + +module.exports.getPublicSuffix = function getPublicSuffix(domain) { + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + if (!domain) { + return null; + } + if (domain.match(/^\./)) { + return null; + } + var asciiDomain = punycode.toASCII(domain); + var converted = false; + if (asciiDomain !== domain) { + domain = asciiDomain; + converted = true; + } + if (index[domain]) { + return null; + } + + domain = domain.toLowerCase(); + var parts = domain.split('.').reverse(); + + var suffix = ''; + var suffixLen = 0; + for (var i=0; i suffixLen) { + var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.'); + return converted ? punycode.toUnicode(publicSuffix) : publicSuffix; + } + + return null; +}; + +// The following generated structure is used under the MPL version 1.1 +// See public-suffix.txt for more information + +var index = module.exports.index = Object.freeze( +{"ac":true,"com.ac":true,"edu.ac":true,"gov.ac":true,"net.ac":true,"mil.ac":true,"org.ac":true,"ad":true,"nom.ad":true,"ae":true,"co.ae":true,"net.ae":true,"org.ae":true,"sch.ae":true,"ac.ae":true,"gov.ae":true,"mil.ae":true,"aero":true,"accident-investigation.aero":true,"accident-prevention.aero":true,"aerobatic.aero":true,"aeroclub.aero":true,"aerodrome.aero":true,"agents.aero":true,"aircraft.aero":true,"airline.aero":true,"airport.aero":true,"air-surveillance.aero":true,"airtraffic.aero":true,"air-traffic-control.aero":true,"ambulance.aero":true,"amusement.aero":true,"association.aero":true,"author.aero":true,"ballooning.aero":true,"broker.aero":true,"caa.aero":true,"cargo.aero":true,"catering.aero":true,"certification.aero":true,"championship.aero":true,"charter.aero":true,"civilaviation.aero":true,"club.aero":true,"conference.aero":true,"consultant.aero":true,"consulting.aero":true,"control.aero":true,"council.aero":true,"crew.aero":true,"design.aero":true,"dgca.aero":true,"educator.aero":true,"emergency.aero":true,"engine.aero":true,"engineer.aero":true,"entertainment.aero":true,"equipment.aero":true,"exchange.aero":true,"express.aero":true,"federation.aero":true,"flight.aero":true,"freight.aero":true,"fuel.aero":true,"gliding.aero":true,"government.aero":true,"groundhandling.aero":true,"group.aero":true,"hanggliding.aero":true,"homebuilt.aero":true,"insurance.aero":true,"journal.aero":true,"journalist.aero":true,"leasing.aero":true,"logistics.aero":true,"magazine.aero":true,"maintenance.aero":true,"marketplace.aero":true,"media.aero":true,"microlight.aero":true,"modelling.aero":true,"navigation.aero":true,"parachuting.aero":true,"paragliding.aero":true,"passenger-association.aero":true,"pilot.aero":true,"press.aero":true,"production.aero":true,"recreation.aero":true,"repbody.aero":true,"res.aero":true,"research.aero":true,"rotorcraft.aero":true,"safety.aero":true,"scientist.aero":true,"services.aero":true,"show.aero":true,"skydiving.aero":true,"software.aero":true,"student.aero":true,"taxi.aero":true,"trader.aero":true,"trading.aero":true,"trainer.aero":true,"union.aero":true,"workinggroup.aero":true,"works.aero":true,"af":true,"gov.af":true,"com.af":true,"org.af":true,"net.af":true,"edu.af":true,"ag":true,"com.ag":true,"org.ag":true,"net.ag":true,"co.ag":true,"nom.ag":true,"ai":true,"off.ai":true,"com.ai":true,"net.ai":true,"org.ai":true,"al":true,"com.al":true,"edu.al":true,"gov.al":true,"mil.al":true,"net.al":true,"org.al":true,"am":true,"an":true,"com.an":true,"net.an":true,"org.an":true,"edu.an":true,"ao":true,"ed.ao":true,"gv.ao":true,"og.ao":true,"co.ao":true,"pb.ao":true,"it.ao":true,"aq":true,"ar":true,"com.ar":true,"edu.ar":true,"gob.ar":true,"gov.ar":true,"int.ar":true,"mil.ar":true,"net.ar":true,"org.ar":true,"tur.ar":true,"arpa":true,"e164.arpa":true,"in-addr.arpa":true,"ip6.arpa":true,"iris.arpa":true,"uri.arpa":true,"urn.arpa":true,"as":true,"gov.as":true,"asia":true,"at":true,"ac.at":true,"co.at":true,"gv.at":true,"or.at":true,"au":true,"com.au":true,"net.au":true,"org.au":true,"edu.au":true,"gov.au":true,"asn.au":true,"id.au":true,"info.au":true,"conf.au":true,"oz.au":true,"act.au":true,"nsw.au":true,"nt.au":true,"qld.au":true,"sa.au":true,"tas.au":true,"vic.au":true,"wa.au":true,"act.edu.au":true,"nsw.edu.au":true,"nt.edu.au":true,"qld.edu.au":true,"sa.edu.au":true,"tas.edu.au":true,"vic.edu.au":true,"wa.edu.au":true,"qld.gov.au":true,"sa.gov.au":true,"tas.gov.au":true,"vic.gov.au":true,"wa.gov.au":true,"aw":true,"com.aw":true,"ax":true,"az":true,"com.az":true,"net.az":true,"int.az":true,"gov.az":true,"org.az":true,"edu.az":true,"info.az":true,"pp.az":true,"mil.az":true,"name.az":true,"pro.az":true,"biz.az":true,"ba":true,"org.ba":true,"net.ba":true,"edu.ba":true,"gov.ba":true,"mil.ba":true,"unsa.ba":true,"unbi.ba":true,"co.ba":true,"com.ba":true,"rs.ba":true,"bb":true,"biz.bb":true,"co.bb":true,"com.bb":true,"edu.bb":true,"gov.bb":true,"info.bb":true,"net.bb":true,"org.bb":true,"store.bb":true,"tv.bb":true,"*.bd":true,"be":true,"ac.be":true,"bf":true,"gov.bf":true,"bg":true,"a.bg":true,"b.bg":true,"c.bg":true,"d.bg":true,"e.bg":true,"f.bg":true,"g.bg":true,"h.bg":true,"i.bg":true,"j.bg":true,"k.bg":true,"l.bg":true,"m.bg":true,"n.bg":true,"o.bg":true,"p.bg":true,"q.bg":true,"r.bg":true,"s.bg":true,"t.bg":true,"u.bg":true,"v.bg":true,"w.bg":true,"x.bg":true,"y.bg":true,"z.bg":true,"0.bg":true,"1.bg":true,"2.bg":true,"3.bg":true,"4.bg":true,"5.bg":true,"6.bg":true,"7.bg":true,"8.bg":true,"9.bg":true,"bh":true,"com.bh":true,"edu.bh":true,"net.bh":true,"org.bh":true,"gov.bh":true,"bi":true,"co.bi":true,"com.bi":true,"edu.bi":true,"or.bi":true,"org.bi":true,"biz":true,"bj":true,"asso.bj":true,"barreau.bj":true,"gouv.bj":true,"bm":true,"com.bm":true,"edu.bm":true,"gov.bm":true,"net.bm":true,"org.bm":true,"*.bn":true,"bo":true,"com.bo":true,"edu.bo":true,"gov.bo":true,"gob.bo":true,"int.bo":true,"org.bo":true,"net.bo":true,"mil.bo":true,"tv.bo":true,"br":true,"adm.br":true,"adv.br":true,"agr.br":true,"am.br":true,"arq.br":true,"art.br":true,"ato.br":true,"b.br":true,"bio.br":true,"blog.br":true,"bmd.br":true,"cim.br":true,"cng.br":true,"cnt.br":true,"com.br":true,"coop.br":true,"ecn.br":true,"eco.br":true,"edu.br":true,"emp.br":true,"eng.br":true,"esp.br":true,"etc.br":true,"eti.br":true,"far.br":true,"flog.br":true,"fm.br":true,"fnd.br":true,"fot.br":true,"fst.br":true,"g12.br":true,"ggf.br":true,"gov.br":true,"imb.br":true,"ind.br":true,"inf.br":true,"jor.br":true,"jus.br":true,"leg.br":true,"lel.br":true,"mat.br":true,"med.br":true,"mil.br":true,"mp.br":true,"mus.br":true,"net.br":true,"*.nom.br":true,"not.br":true,"ntr.br":true,"odo.br":true,"org.br":true,"ppg.br":true,"pro.br":true,"psc.br":true,"psi.br":true,"qsl.br":true,"radio.br":true,"rec.br":true,"slg.br":true,"srv.br":true,"taxi.br":true,"teo.br":true,"tmp.br":true,"trd.br":true,"tur.br":true,"tv.br":true,"vet.br":true,"vlog.br":true,"wiki.br":true,"zlg.br":true,"bs":true,"com.bs":true,"net.bs":true,"org.bs":true,"edu.bs":true,"gov.bs":true,"bt":true,"com.bt":true,"edu.bt":true,"gov.bt":true,"net.bt":true,"org.bt":true,"bv":true,"bw":true,"co.bw":true,"org.bw":true,"by":true,"gov.by":true,"mil.by":true,"com.by":true,"of.by":true,"bz":true,"com.bz":true,"net.bz":true,"org.bz":true,"edu.bz":true,"gov.bz":true,"ca":true,"ab.ca":true,"bc.ca":true,"mb.ca":true,"nb.ca":true,"nf.ca":true,"nl.ca":true,"ns.ca":true,"nt.ca":true,"nu.ca":true,"on.ca":true,"pe.ca":true,"qc.ca":true,"sk.ca":true,"yk.ca":true,"gc.ca":true,"cat":true,"cc":true,"cd":true,"gov.cd":true,"cf":true,"cg":true,"ch":true,"ci":true,"org.ci":true,"or.ci":true,"com.ci":true,"co.ci":true,"edu.ci":true,"ed.ci":true,"ac.ci":true,"net.ci":true,"go.ci":true,"asso.ci":true,"xn--aroport-bya.ci":true,"int.ci":true,"presse.ci":true,"md.ci":true,"gouv.ci":true,"*.ck":true,"www.ck":false,"cl":true,"gov.cl":true,"gob.cl":true,"co.cl":true,"mil.cl":true,"cm":true,"co.cm":true,"com.cm":true,"gov.cm":true,"net.cm":true,"cn":true,"ac.cn":true,"com.cn":true,"edu.cn":true,"gov.cn":true,"net.cn":true,"org.cn":true,"mil.cn":true,"xn--55qx5d.cn":true,"xn--io0a7i.cn":true,"xn--od0alg.cn":true,"ah.cn":true,"bj.cn":true,"cq.cn":true,"fj.cn":true,"gd.cn":true,"gs.cn":true,"gz.cn":true,"gx.cn":true,"ha.cn":true,"hb.cn":true,"he.cn":true,"hi.cn":true,"hl.cn":true,"hn.cn":true,"jl.cn":true,"js.cn":true,"jx.cn":true,"ln.cn":true,"nm.cn":true,"nx.cn":true,"qh.cn":true,"sc.cn":true,"sd.cn":true,"sh.cn":true,"sn.cn":true,"sx.cn":true,"tj.cn":true,"xj.cn":true,"xz.cn":true,"yn.cn":true,"zj.cn":true,"hk.cn":true,"mo.cn":true,"tw.cn":true,"co":true,"arts.co":true,"com.co":true,"edu.co":true,"firm.co":true,"gov.co":true,"info.co":true,"int.co":true,"mil.co":true,"net.co":true,"nom.co":true,"org.co":true,"rec.co":true,"web.co":true,"com":true,"coop":true,"cr":true,"ac.cr":true,"co.cr":true,"ed.cr":true,"fi.cr":true,"go.cr":true,"or.cr":true,"sa.cr":true,"cu":true,"com.cu":true,"edu.cu":true,"org.cu":true,"net.cu":true,"gov.cu":true,"inf.cu":true,"cv":true,"cw":true,"com.cw":true,"edu.cw":true,"net.cw":true,"org.cw":true,"cx":true,"gov.cx":true,"*.cy":true,"cz":true,"de":true,"dj":true,"dk":true,"dm":true,"com.dm":true,"net.dm":true,"org.dm":true,"edu.dm":true,"gov.dm":true,"do":true,"art.do":true,"com.do":true,"edu.do":true,"gob.do":true,"gov.do":true,"mil.do":true,"net.do":true,"org.do":true,"sld.do":true,"web.do":true,"dz":true,"com.dz":true,"org.dz":true,"net.dz":true,"gov.dz":true,"edu.dz":true,"asso.dz":true,"pol.dz":true,"art.dz":true,"ec":true,"com.ec":true,"info.ec":true,"net.ec":true,"fin.ec":true,"k12.ec":true,"med.ec":true,"pro.ec":true,"org.ec":true,"edu.ec":true,"gov.ec":true,"gob.ec":true,"mil.ec":true,"edu":true,"ee":true,"edu.ee":true,"gov.ee":true,"riik.ee":true,"lib.ee":true,"med.ee":true,"com.ee":true,"pri.ee":true,"aip.ee":true,"org.ee":true,"fie.ee":true,"eg":true,"com.eg":true,"edu.eg":true,"eun.eg":true,"gov.eg":true,"mil.eg":true,"name.eg":true,"net.eg":true,"org.eg":true,"sci.eg":true,"*.er":true,"es":true,"com.es":true,"nom.es":true,"org.es":true,"gob.es":true,"edu.es":true,"et":true,"com.et":true,"gov.et":true,"org.et":true,"edu.et":true,"biz.et":true,"name.et":true,"info.et":true,"eu":true,"fi":true,"aland.fi":true,"*.fj":true,"*.fk":true,"fm":true,"fo":true,"fr":true,"com.fr":true,"asso.fr":true,"nom.fr":true,"prd.fr":true,"presse.fr":true,"tm.fr":true,"aeroport.fr":true,"assedic.fr":true,"avocat.fr":true,"avoues.fr":true,"cci.fr":true,"chambagri.fr":true,"chirurgiens-dentistes.fr":true,"experts-comptables.fr":true,"geometre-expert.fr":true,"gouv.fr":true,"greta.fr":true,"huissier-justice.fr":true,"medecin.fr":true,"notaires.fr":true,"pharmacien.fr":true,"port.fr":true,"veterinaire.fr":true,"ga":true,"gb":true,"gd":true,"ge":true,"com.ge":true,"edu.ge":true,"gov.ge":true,"org.ge":true,"mil.ge":true,"net.ge":true,"pvt.ge":true,"gf":true,"gg":true,"co.gg":true,"net.gg":true,"org.gg":true,"gh":true,"com.gh":true,"edu.gh":true,"gov.gh":true,"org.gh":true,"mil.gh":true,"gi":true,"com.gi":true,"ltd.gi":true,"gov.gi":true,"mod.gi":true,"edu.gi":true,"org.gi":true,"gl":true,"gm":true,"gn":true,"ac.gn":true,"com.gn":true,"edu.gn":true,"gov.gn":true,"org.gn":true,"net.gn":true,"gov":true,"gp":true,"com.gp":true,"net.gp":true,"mobi.gp":true,"edu.gp":true,"org.gp":true,"asso.gp":true,"gq":true,"gr":true,"com.gr":true,"edu.gr":true,"net.gr":true,"org.gr":true,"gov.gr":true,"gs":true,"gt":true,"com.gt":true,"edu.gt":true,"gob.gt":true,"ind.gt":true,"mil.gt":true,"net.gt":true,"org.gt":true,"*.gu":true,"gw":true,"gy":true,"co.gy":true,"com.gy":true,"net.gy":true,"hk":true,"com.hk":true,"edu.hk":true,"gov.hk":true,"idv.hk":true,"net.hk":true,"org.hk":true,"xn--55qx5d.hk":true,"xn--wcvs22d.hk":true,"xn--lcvr32d.hk":true,"xn--mxtq1m.hk":true,"xn--gmqw5a.hk":true,"xn--ciqpn.hk":true,"xn--gmq050i.hk":true,"xn--zf0avx.hk":true,"xn--io0a7i.hk":true,"xn--mk0axi.hk":true,"xn--od0alg.hk":true,"xn--od0aq3b.hk":true,"xn--tn0ag.hk":true,"xn--uc0atv.hk":true,"xn--uc0ay4a.hk":true,"hm":true,"hn":true,"com.hn":true,"edu.hn":true,"org.hn":true,"net.hn":true,"mil.hn":true,"gob.hn":true,"hr":true,"iz.hr":true,"from.hr":true,"name.hr":true,"com.hr":true,"ht":true,"com.ht":true,"shop.ht":true,"firm.ht":true,"info.ht":true,"adult.ht":true,"net.ht":true,"pro.ht":true,"org.ht":true,"med.ht":true,"art.ht":true,"coop.ht":true,"pol.ht":true,"asso.ht":true,"edu.ht":true,"rel.ht":true,"gouv.ht":true,"perso.ht":true,"hu":true,"co.hu":true,"info.hu":true,"org.hu":true,"priv.hu":true,"sport.hu":true,"tm.hu":true,"2000.hu":true,"agrar.hu":true,"bolt.hu":true,"casino.hu":true,"city.hu":true,"erotica.hu":true,"erotika.hu":true,"film.hu":true,"forum.hu":true,"games.hu":true,"hotel.hu":true,"ingatlan.hu":true,"jogasz.hu":true,"konyvelo.hu":true,"lakas.hu":true,"media.hu":true,"news.hu":true,"reklam.hu":true,"sex.hu":true,"shop.hu":true,"suli.hu":true,"szex.hu":true,"tozsde.hu":true,"utazas.hu":true,"video.hu":true,"id":true,"ac.id":true,"biz.id":true,"co.id":true,"desa.id":true,"go.id":true,"mil.id":true,"my.id":true,"net.id":true,"or.id":true,"sch.id":true,"web.id":true,"ie":true,"gov.ie":true,"*.il":true,"im":true,"ac.im":true,"co.im":true,"com.im":true,"ltd.co.im":true,"net.im":true,"org.im":true,"plc.co.im":true,"tt.im":true,"tv.im":true,"in":true,"co.in":true,"firm.in":true,"net.in":true,"org.in":true,"gen.in":true,"ind.in":true,"nic.in":true,"ac.in":true,"edu.in":true,"res.in":true,"gov.in":true,"mil.in":true,"info":true,"int":true,"eu.int":true,"io":true,"com.io":true,"iq":true,"gov.iq":true,"edu.iq":true,"mil.iq":true,"com.iq":true,"org.iq":true,"net.iq":true,"ir":true,"ac.ir":true,"co.ir":true,"gov.ir":true,"id.ir":true,"net.ir":true,"org.ir":true,"sch.ir":true,"xn--mgba3a4f16a.ir":true,"xn--mgba3a4fra.ir":true,"is":true,"net.is":true,"com.is":true,"edu.is":true,"gov.is":true,"org.is":true,"int.is":true,"it":true,"gov.it":true,"edu.it":true,"abr.it":true,"abruzzo.it":true,"aosta-valley.it":true,"aostavalley.it":true,"bas.it":true,"basilicata.it":true,"cal.it":true,"calabria.it":true,"cam.it":true,"campania.it":true,"emilia-romagna.it":true,"emiliaromagna.it":true,"emr.it":true,"friuli-v-giulia.it":true,"friuli-ve-giulia.it":true,"friuli-vegiulia.it":true,"friuli-venezia-giulia.it":true,"friuli-veneziagiulia.it":true,"friuli-vgiulia.it":true,"friuliv-giulia.it":true,"friulive-giulia.it":true,"friulivegiulia.it":true,"friulivenezia-giulia.it":true,"friuliveneziagiulia.it":true,"friulivgiulia.it":true,"fvg.it":true,"laz.it":true,"lazio.it":true,"lig.it":true,"liguria.it":true,"lom.it":true,"lombardia.it":true,"lombardy.it":true,"lucania.it":true,"mar.it":true,"marche.it":true,"mol.it":true,"molise.it":true,"piedmont.it":true,"piemonte.it":true,"pmn.it":true,"pug.it":true,"puglia.it":true,"sar.it":true,"sardegna.it":true,"sardinia.it":true,"sic.it":true,"sicilia.it":true,"sicily.it":true,"taa.it":true,"tos.it":true,"toscana.it":true,"trentino-a-adige.it":true,"trentino-aadige.it":true,"trentino-alto-adige.it":true,"trentino-altoadige.it":true,"trentino-s-tirol.it":true,"trentino-stirol.it":true,"trentino-sud-tirol.it":true,"trentino-sudtirol.it":true,"trentino-sued-tirol.it":true,"trentino-suedtirol.it":true,"trentinoa-adige.it":true,"trentinoaadige.it":true,"trentinoalto-adige.it":true,"trentinoaltoadige.it":true,"trentinos-tirol.it":true,"trentinostirol.it":true,"trentinosud-tirol.it":true,"trentinosudtirol.it":true,"trentinosued-tirol.it":true,"trentinosuedtirol.it":true,"tuscany.it":true,"umb.it":true,"umbria.it":true,"val-d-aosta.it":true,"val-daosta.it":true,"vald-aosta.it":true,"valdaosta.it":true,"valle-aosta.it":true,"valle-d-aosta.it":true,"valle-daosta.it":true,"valleaosta.it":true,"valled-aosta.it":true,"valledaosta.it":true,"vallee-aoste.it":true,"valleeaoste.it":true,"vao.it":true,"vda.it":true,"ven.it":true,"veneto.it":true,"ag.it":true,"agrigento.it":true,"al.it":true,"alessandria.it":true,"alto-adige.it":true,"altoadige.it":true,"an.it":true,"ancona.it":true,"andria-barletta-trani.it":true,"andria-trani-barletta.it":true,"andriabarlettatrani.it":true,"andriatranibarletta.it":true,"ao.it":true,"aosta.it":true,"aoste.it":true,"ap.it":true,"aq.it":true,"aquila.it":true,"ar.it":true,"arezzo.it":true,"ascoli-piceno.it":true,"ascolipiceno.it":true,"asti.it":true,"at.it":true,"av.it":true,"avellino.it":true,"ba.it":true,"balsan.it":true,"bari.it":true,"barletta-trani-andria.it":true,"barlettatraniandria.it":true,"belluno.it":true,"benevento.it":true,"bergamo.it":true,"bg.it":true,"bi.it":true,"biella.it":true,"bl.it":true,"bn.it":true,"bo.it":true,"bologna.it":true,"bolzano.it":true,"bozen.it":true,"br.it":true,"brescia.it":true,"brindisi.it":true,"bs.it":true,"bt.it":true,"bz.it":true,"ca.it":true,"cagliari.it":true,"caltanissetta.it":true,"campidano-medio.it":true,"campidanomedio.it":true,"campobasso.it":true,"carbonia-iglesias.it":true,"carboniaiglesias.it":true,"carrara-massa.it":true,"carraramassa.it":true,"caserta.it":true,"catania.it":true,"catanzaro.it":true,"cb.it":true,"ce.it":true,"cesena-forli.it":true,"cesenaforli.it":true,"ch.it":true,"chieti.it":true,"ci.it":true,"cl.it":true,"cn.it":true,"co.it":true,"como.it":true,"cosenza.it":true,"cr.it":true,"cremona.it":true,"crotone.it":true,"cs.it":true,"ct.it":true,"cuneo.it":true,"cz.it":true,"dell-ogliastra.it":true,"dellogliastra.it":true,"en.it":true,"enna.it":true,"fc.it":true,"fe.it":true,"fermo.it":true,"ferrara.it":true,"fg.it":true,"fi.it":true,"firenze.it":true,"florence.it":true,"fm.it":true,"foggia.it":true,"forli-cesena.it":true,"forlicesena.it":true,"fr.it":true,"frosinone.it":true,"ge.it":true,"genoa.it":true,"genova.it":true,"go.it":true,"gorizia.it":true,"gr.it":true,"grosseto.it":true,"iglesias-carbonia.it":true,"iglesiascarbonia.it":true,"im.it":true,"imperia.it":true,"is.it":true,"isernia.it":true,"kr.it":true,"la-spezia.it":true,"laquila.it":true,"laspezia.it":true,"latina.it":true,"lc.it":true,"le.it":true,"lecce.it":true,"lecco.it":true,"li.it":true,"livorno.it":true,"lo.it":true,"lodi.it":true,"lt.it":true,"lu.it":true,"lucca.it":true,"macerata.it":true,"mantova.it":true,"massa-carrara.it":true,"massacarrara.it":true,"matera.it":true,"mb.it":true,"mc.it":true,"me.it":true,"medio-campidano.it":true,"mediocampidano.it":true,"messina.it":true,"mi.it":true,"milan.it":true,"milano.it":true,"mn.it":true,"mo.it":true,"modena.it":true,"monza-brianza.it":true,"monza-e-della-brianza.it":true,"monza.it":true,"monzabrianza.it":true,"monzaebrianza.it":true,"monzaedellabrianza.it":true,"ms.it":true,"mt.it":true,"na.it":true,"naples.it":true,"napoli.it":true,"no.it":true,"novara.it":true,"nu.it":true,"nuoro.it":true,"og.it":true,"ogliastra.it":true,"olbia-tempio.it":true,"olbiatempio.it":true,"or.it":true,"oristano.it":true,"ot.it":true,"pa.it":true,"padova.it":true,"padua.it":true,"palermo.it":true,"parma.it":true,"pavia.it":true,"pc.it":true,"pd.it":true,"pe.it":true,"perugia.it":true,"pesaro-urbino.it":true,"pesarourbino.it":true,"pescara.it":true,"pg.it":true,"pi.it":true,"piacenza.it":true,"pisa.it":true,"pistoia.it":true,"pn.it":true,"po.it":true,"pordenone.it":true,"potenza.it":true,"pr.it":true,"prato.it":true,"pt.it":true,"pu.it":true,"pv.it":true,"pz.it":true,"ra.it":true,"ragusa.it":true,"ravenna.it":true,"rc.it":true,"re.it":true,"reggio-calabria.it":true,"reggio-emilia.it":true,"reggiocalabria.it":true,"reggioemilia.it":true,"rg.it":true,"ri.it":true,"rieti.it":true,"rimini.it":true,"rm.it":true,"rn.it":true,"ro.it":true,"roma.it":true,"rome.it":true,"rovigo.it":true,"sa.it":true,"salerno.it":true,"sassari.it":true,"savona.it":true,"si.it":true,"siena.it":true,"siracusa.it":true,"so.it":true,"sondrio.it":true,"sp.it":true,"sr.it":true,"ss.it":true,"suedtirol.it":true,"sv.it":true,"ta.it":true,"taranto.it":true,"te.it":true,"tempio-olbia.it":true,"tempioolbia.it":true,"teramo.it":true,"terni.it":true,"tn.it":true,"to.it":true,"torino.it":true,"tp.it":true,"tr.it":true,"trani-andria-barletta.it":true,"trani-barletta-andria.it":true,"traniandriabarletta.it":true,"tranibarlettaandria.it":true,"trapani.it":true,"trentino.it":true,"trento.it":true,"treviso.it":true,"trieste.it":true,"ts.it":true,"turin.it":true,"tv.it":true,"ud.it":true,"udine.it":true,"urbino-pesaro.it":true,"urbinopesaro.it":true,"va.it":true,"varese.it":true,"vb.it":true,"vc.it":true,"ve.it":true,"venezia.it":true,"venice.it":true,"verbania.it":true,"vercelli.it":true,"verona.it":true,"vi.it":true,"vibo-valentia.it":true,"vibovalentia.it":true,"vicenza.it":true,"viterbo.it":true,"vr.it":true,"vs.it":true,"vt.it":true,"vv.it":true,"je":true,"co.je":true,"net.je":true,"org.je":true,"*.jm":true,"jo":true,"com.jo":true,"org.jo":true,"net.jo":true,"edu.jo":true,"sch.jo":true,"gov.jo":true,"mil.jo":true,"name.jo":true,"jobs":true,"jp":true,"ac.jp":true,"ad.jp":true,"co.jp":true,"ed.jp":true,"go.jp":true,"gr.jp":true,"lg.jp":true,"ne.jp":true,"or.jp":true,"aichi.jp":true,"akita.jp":true,"aomori.jp":true,"chiba.jp":true,"ehime.jp":true,"fukui.jp":true,"fukuoka.jp":true,"fukushima.jp":true,"gifu.jp":true,"gunma.jp":true,"hiroshima.jp":true,"hokkaido.jp":true,"hyogo.jp":true,"ibaraki.jp":true,"ishikawa.jp":true,"iwate.jp":true,"kagawa.jp":true,"kagoshima.jp":true,"kanagawa.jp":true,"kochi.jp":true,"kumamoto.jp":true,"kyoto.jp":true,"mie.jp":true,"miyagi.jp":true,"miyazaki.jp":true,"nagano.jp":true,"nagasaki.jp":true,"nara.jp":true,"niigata.jp":true,"oita.jp":true,"okayama.jp":true,"okinawa.jp":true,"osaka.jp":true,"saga.jp":true,"saitama.jp":true,"shiga.jp":true,"shimane.jp":true,"shizuoka.jp":true,"tochigi.jp":true,"tokushima.jp":true,"tokyo.jp":true,"tottori.jp":true,"toyama.jp":true,"wakayama.jp":true,"yamagata.jp":true,"yamaguchi.jp":true,"yamanashi.jp":true,"xn--4pvxs.jp":true,"xn--vgu402c.jp":true,"xn--c3s14m.jp":true,"xn--f6qx53a.jp":true,"xn--8pvr4u.jp":true,"xn--uist22h.jp":true,"xn--djrs72d6uy.jp":true,"xn--mkru45i.jp":true,"xn--0trq7p7nn.jp":true,"xn--8ltr62k.jp":true,"xn--2m4a15e.jp":true,"xn--efvn9s.jp":true,"xn--32vp30h.jp":true,"xn--4it797k.jp":true,"xn--1lqs71d.jp":true,"xn--5rtp49c.jp":true,"xn--5js045d.jp":true,"xn--ehqz56n.jp":true,"xn--1lqs03n.jp":true,"xn--qqqt11m.jp":true,"xn--kbrq7o.jp":true,"xn--pssu33l.jp":true,"xn--ntsq17g.jp":true,"xn--uisz3g.jp":true,"xn--6btw5a.jp":true,"xn--1ctwo.jp":true,"xn--6orx2r.jp":true,"xn--rht61e.jp":true,"xn--rht27z.jp":true,"xn--djty4k.jp":true,"xn--nit225k.jp":true,"xn--rht3d.jp":true,"xn--klty5x.jp":true,"xn--kltx9a.jp":true,"xn--kltp7d.jp":true,"xn--uuwu58a.jp":true,"xn--zbx025d.jp":true,"xn--ntso0iqx3a.jp":true,"xn--elqq16h.jp":true,"xn--4it168d.jp":true,"xn--klt787d.jp":true,"xn--rny31h.jp":true,"xn--7t0a264c.jp":true,"xn--5rtq34k.jp":true,"xn--k7yn95e.jp":true,"xn--tor131o.jp":true,"xn--d5qv7z876c.jp":true,"*.kawasaki.jp":true,"*.kitakyushu.jp":true,"*.kobe.jp":true,"*.nagoya.jp":true,"*.sapporo.jp":true,"*.sendai.jp":true,"*.yokohama.jp":true,"city.kawasaki.jp":false,"city.kitakyushu.jp":false,"city.kobe.jp":false,"city.nagoya.jp":false,"city.sapporo.jp":false,"city.sendai.jp":false,"city.yokohama.jp":false,"aisai.aichi.jp":true,"ama.aichi.jp":true,"anjo.aichi.jp":true,"asuke.aichi.jp":true,"chiryu.aichi.jp":true,"chita.aichi.jp":true,"fuso.aichi.jp":true,"gamagori.aichi.jp":true,"handa.aichi.jp":true,"hazu.aichi.jp":true,"hekinan.aichi.jp":true,"higashiura.aichi.jp":true,"ichinomiya.aichi.jp":true,"inazawa.aichi.jp":true,"inuyama.aichi.jp":true,"isshiki.aichi.jp":true,"iwakura.aichi.jp":true,"kanie.aichi.jp":true,"kariya.aichi.jp":true,"kasugai.aichi.jp":true,"kira.aichi.jp":true,"kiyosu.aichi.jp":true,"komaki.aichi.jp":true,"konan.aichi.jp":true,"kota.aichi.jp":true,"mihama.aichi.jp":true,"miyoshi.aichi.jp":true,"nishio.aichi.jp":true,"nisshin.aichi.jp":true,"obu.aichi.jp":true,"oguchi.aichi.jp":true,"oharu.aichi.jp":true,"okazaki.aichi.jp":true,"owariasahi.aichi.jp":true,"seto.aichi.jp":true,"shikatsu.aichi.jp":true,"shinshiro.aichi.jp":true,"shitara.aichi.jp":true,"tahara.aichi.jp":true,"takahama.aichi.jp":true,"tobishima.aichi.jp":true,"toei.aichi.jp":true,"togo.aichi.jp":true,"tokai.aichi.jp":true,"tokoname.aichi.jp":true,"toyoake.aichi.jp":true,"toyohashi.aichi.jp":true,"toyokawa.aichi.jp":true,"toyone.aichi.jp":true,"toyota.aichi.jp":true,"tsushima.aichi.jp":true,"yatomi.aichi.jp":true,"akita.akita.jp":true,"daisen.akita.jp":true,"fujisato.akita.jp":true,"gojome.akita.jp":true,"hachirogata.akita.jp":true,"happou.akita.jp":true,"higashinaruse.akita.jp":true,"honjo.akita.jp":true,"honjyo.akita.jp":true,"ikawa.akita.jp":true,"kamikoani.akita.jp":true,"kamioka.akita.jp":true,"katagami.akita.jp":true,"kazuno.akita.jp":true,"kitaakita.akita.jp":true,"kosaka.akita.jp":true,"kyowa.akita.jp":true,"misato.akita.jp":true,"mitane.akita.jp":true,"moriyoshi.akita.jp":true,"nikaho.akita.jp":true,"noshiro.akita.jp":true,"odate.akita.jp":true,"oga.akita.jp":true,"ogata.akita.jp":true,"semboku.akita.jp":true,"yokote.akita.jp":true,"yurihonjo.akita.jp":true,"aomori.aomori.jp":true,"gonohe.aomori.jp":true,"hachinohe.aomori.jp":true,"hashikami.aomori.jp":true,"hiranai.aomori.jp":true,"hirosaki.aomori.jp":true,"itayanagi.aomori.jp":true,"kuroishi.aomori.jp":true,"misawa.aomori.jp":true,"mutsu.aomori.jp":true,"nakadomari.aomori.jp":true,"noheji.aomori.jp":true,"oirase.aomori.jp":true,"owani.aomori.jp":true,"rokunohe.aomori.jp":true,"sannohe.aomori.jp":true,"shichinohe.aomori.jp":true,"shingo.aomori.jp":true,"takko.aomori.jp":true,"towada.aomori.jp":true,"tsugaru.aomori.jp":true,"tsuruta.aomori.jp":true,"abiko.chiba.jp":true,"asahi.chiba.jp":true,"chonan.chiba.jp":true,"chosei.chiba.jp":true,"choshi.chiba.jp":true,"chuo.chiba.jp":true,"funabashi.chiba.jp":true,"futtsu.chiba.jp":true,"hanamigawa.chiba.jp":true,"ichihara.chiba.jp":true,"ichikawa.chiba.jp":true,"ichinomiya.chiba.jp":true,"inzai.chiba.jp":true,"isumi.chiba.jp":true,"kamagaya.chiba.jp":true,"kamogawa.chiba.jp":true,"kashiwa.chiba.jp":true,"katori.chiba.jp":true,"katsuura.chiba.jp":true,"kimitsu.chiba.jp":true,"kisarazu.chiba.jp":true,"kozaki.chiba.jp":true,"kujukuri.chiba.jp":true,"kyonan.chiba.jp":true,"matsudo.chiba.jp":true,"midori.chiba.jp":true,"mihama.chiba.jp":true,"minamiboso.chiba.jp":true,"mobara.chiba.jp":true,"mutsuzawa.chiba.jp":true,"nagara.chiba.jp":true,"nagareyama.chiba.jp":true,"narashino.chiba.jp":true,"narita.chiba.jp":true,"noda.chiba.jp":true,"oamishirasato.chiba.jp":true,"omigawa.chiba.jp":true,"onjuku.chiba.jp":true,"otaki.chiba.jp":true,"sakae.chiba.jp":true,"sakura.chiba.jp":true,"shimofusa.chiba.jp":true,"shirako.chiba.jp":true,"shiroi.chiba.jp":true,"shisui.chiba.jp":true,"sodegaura.chiba.jp":true,"sosa.chiba.jp":true,"tako.chiba.jp":true,"tateyama.chiba.jp":true,"togane.chiba.jp":true,"tohnosho.chiba.jp":true,"tomisato.chiba.jp":true,"urayasu.chiba.jp":true,"yachimata.chiba.jp":true,"yachiyo.chiba.jp":true,"yokaichiba.chiba.jp":true,"yokoshibahikari.chiba.jp":true,"yotsukaido.chiba.jp":true,"ainan.ehime.jp":true,"honai.ehime.jp":true,"ikata.ehime.jp":true,"imabari.ehime.jp":true,"iyo.ehime.jp":true,"kamijima.ehime.jp":true,"kihoku.ehime.jp":true,"kumakogen.ehime.jp":true,"masaki.ehime.jp":true,"matsuno.ehime.jp":true,"matsuyama.ehime.jp":true,"namikata.ehime.jp":true,"niihama.ehime.jp":true,"ozu.ehime.jp":true,"saijo.ehime.jp":true,"seiyo.ehime.jp":true,"shikokuchuo.ehime.jp":true,"tobe.ehime.jp":true,"toon.ehime.jp":true,"uchiko.ehime.jp":true,"uwajima.ehime.jp":true,"yawatahama.ehime.jp":true,"echizen.fukui.jp":true,"eiheiji.fukui.jp":true,"fukui.fukui.jp":true,"ikeda.fukui.jp":true,"katsuyama.fukui.jp":true,"mihama.fukui.jp":true,"minamiechizen.fukui.jp":true,"obama.fukui.jp":true,"ohi.fukui.jp":true,"ono.fukui.jp":true,"sabae.fukui.jp":true,"sakai.fukui.jp":true,"takahama.fukui.jp":true,"tsuruga.fukui.jp":true,"wakasa.fukui.jp":true,"ashiya.fukuoka.jp":true,"buzen.fukuoka.jp":true,"chikugo.fukuoka.jp":true,"chikuho.fukuoka.jp":true,"chikujo.fukuoka.jp":true,"chikushino.fukuoka.jp":true,"chikuzen.fukuoka.jp":true,"chuo.fukuoka.jp":true,"dazaifu.fukuoka.jp":true,"fukuchi.fukuoka.jp":true,"hakata.fukuoka.jp":true,"higashi.fukuoka.jp":true,"hirokawa.fukuoka.jp":true,"hisayama.fukuoka.jp":true,"iizuka.fukuoka.jp":true,"inatsuki.fukuoka.jp":true,"kaho.fukuoka.jp":true,"kasuga.fukuoka.jp":true,"kasuya.fukuoka.jp":true,"kawara.fukuoka.jp":true,"keisen.fukuoka.jp":true,"koga.fukuoka.jp":true,"kurate.fukuoka.jp":true,"kurogi.fukuoka.jp":true,"kurume.fukuoka.jp":true,"minami.fukuoka.jp":true,"miyako.fukuoka.jp":true,"miyama.fukuoka.jp":true,"miyawaka.fukuoka.jp":true,"mizumaki.fukuoka.jp":true,"munakata.fukuoka.jp":true,"nakagawa.fukuoka.jp":true,"nakama.fukuoka.jp":true,"nishi.fukuoka.jp":true,"nogata.fukuoka.jp":true,"ogori.fukuoka.jp":true,"okagaki.fukuoka.jp":true,"okawa.fukuoka.jp":true,"oki.fukuoka.jp":true,"omuta.fukuoka.jp":true,"onga.fukuoka.jp":true,"onojo.fukuoka.jp":true,"oto.fukuoka.jp":true,"saigawa.fukuoka.jp":true,"sasaguri.fukuoka.jp":true,"shingu.fukuoka.jp":true,"shinyoshitomi.fukuoka.jp":true,"shonai.fukuoka.jp":true,"soeda.fukuoka.jp":true,"sue.fukuoka.jp":true,"tachiarai.fukuoka.jp":true,"tagawa.fukuoka.jp":true,"takata.fukuoka.jp":true,"toho.fukuoka.jp":true,"toyotsu.fukuoka.jp":true,"tsuiki.fukuoka.jp":true,"ukiha.fukuoka.jp":true,"umi.fukuoka.jp":true,"usui.fukuoka.jp":true,"yamada.fukuoka.jp":true,"yame.fukuoka.jp":true,"yanagawa.fukuoka.jp":true,"yukuhashi.fukuoka.jp":true,"aizubange.fukushima.jp":true,"aizumisato.fukushima.jp":true,"aizuwakamatsu.fukushima.jp":true,"asakawa.fukushima.jp":true,"bandai.fukushima.jp":true,"date.fukushima.jp":true,"fukushima.fukushima.jp":true,"furudono.fukushima.jp":true,"futaba.fukushima.jp":true,"hanawa.fukushima.jp":true,"higashi.fukushima.jp":true,"hirata.fukushima.jp":true,"hirono.fukushima.jp":true,"iitate.fukushima.jp":true,"inawashiro.fukushima.jp":true,"ishikawa.fukushima.jp":true,"iwaki.fukushima.jp":true,"izumizaki.fukushima.jp":true,"kagamiishi.fukushima.jp":true,"kaneyama.fukushima.jp":true,"kawamata.fukushima.jp":true,"kitakata.fukushima.jp":true,"kitashiobara.fukushima.jp":true,"koori.fukushima.jp":true,"koriyama.fukushima.jp":true,"kunimi.fukushima.jp":true,"miharu.fukushima.jp":true,"mishima.fukushima.jp":true,"namie.fukushima.jp":true,"nango.fukushima.jp":true,"nishiaizu.fukushima.jp":true,"nishigo.fukushima.jp":true,"okuma.fukushima.jp":true,"omotego.fukushima.jp":true,"ono.fukushima.jp":true,"otama.fukushima.jp":true,"samegawa.fukushima.jp":true,"shimogo.fukushima.jp":true,"shirakawa.fukushima.jp":true,"showa.fukushima.jp":true,"soma.fukushima.jp":true,"sukagawa.fukushima.jp":true,"taishin.fukushima.jp":true,"tamakawa.fukushima.jp":true,"tanagura.fukushima.jp":true,"tenei.fukushima.jp":true,"yabuki.fukushima.jp":true,"yamato.fukushima.jp":true,"yamatsuri.fukushima.jp":true,"yanaizu.fukushima.jp":true,"yugawa.fukushima.jp":true,"anpachi.gifu.jp":true,"ena.gifu.jp":true,"gifu.gifu.jp":true,"ginan.gifu.jp":true,"godo.gifu.jp":true,"gujo.gifu.jp":true,"hashima.gifu.jp":true,"hichiso.gifu.jp":true,"hida.gifu.jp":true,"higashishirakawa.gifu.jp":true,"ibigawa.gifu.jp":true,"ikeda.gifu.jp":true,"kakamigahara.gifu.jp":true,"kani.gifu.jp":true,"kasahara.gifu.jp":true,"kasamatsu.gifu.jp":true,"kawaue.gifu.jp":true,"kitagata.gifu.jp":true,"mino.gifu.jp":true,"minokamo.gifu.jp":true,"mitake.gifu.jp":true,"mizunami.gifu.jp":true,"motosu.gifu.jp":true,"nakatsugawa.gifu.jp":true,"ogaki.gifu.jp":true,"sakahogi.gifu.jp":true,"seki.gifu.jp":true,"sekigahara.gifu.jp":true,"shirakawa.gifu.jp":true,"tajimi.gifu.jp":true,"takayama.gifu.jp":true,"tarui.gifu.jp":true,"toki.gifu.jp":true,"tomika.gifu.jp":true,"wanouchi.gifu.jp":true,"yamagata.gifu.jp":true,"yaotsu.gifu.jp":true,"yoro.gifu.jp":true,"annaka.gunma.jp":true,"chiyoda.gunma.jp":true,"fujioka.gunma.jp":true,"higashiagatsuma.gunma.jp":true,"isesaki.gunma.jp":true,"itakura.gunma.jp":true,"kanna.gunma.jp":true,"kanra.gunma.jp":true,"katashina.gunma.jp":true,"kawaba.gunma.jp":true,"kiryu.gunma.jp":true,"kusatsu.gunma.jp":true,"maebashi.gunma.jp":true,"meiwa.gunma.jp":true,"midori.gunma.jp":true,"minakami.gunma.jp":true,"naganohara.gunma.jp":true,"nakanojo.gunma.jp":true,"nanmoku.gunma.jp":true,"numata.gunma.jp":true,"oizumi.gunma.jp":true,"ora.gunma.jp":true,"ota.gunma.jp":true,"shibukawa.gunma.jp":true,"shimonita.gunma.jp":true,"shinto.gunma.jp":true,"showa.gunma.jp":true,"takasaki.gunma.jp":true,"takayama.gunma.jp":true,"tamamura.gunma.jp":true,"tatebayashi.gunma.jp":true,"tomioka.gunma.jp":true,"tsukiyono.gunma.jp":true,"tsumagoi.gunma.jp":true,"ueno.gunma.jp":true,"yoshioka.gunma.jp":true,"asaminami.hiroshima.jp":true,"daiwa.hiroshima.jp":true,"etajima.hiroshima.jp":true,"fuchu.hiroshima.jp":true,"fukuyama.hiroshima.jp":true,"hatsukaichi.hiroshima.jp":true,"higashihiroshima.hiroshima.jp":true,"hongo.hiroshima.jp":true,"jinsekikogen.hiroshima.jp":true,"kaita.hiroshima.jp":true,"kui.hiroshima.jp":true,"kumano.hiroshima.jp":true,"kure.hiroshima.jp":true,"mihara.hiroshima.jp":true,"miyoshi.hiroshima.jp":true,"naka.hiroshima.jp":true,"onomichi.hiroshima.jp":true,"osakikamijima.hiroshima.jp":true,"otake.hiroshima.jp":true,"saka.hiroshima.jp":true,"sera.hiroshima.jp":true,"seranishi.hiroshima.jp":true,"shinichi.hiroshima.jp":true,"shobara.hiroshima.jp":true,"takehara.hiroshima.jp":true,"abashiri.hokkaido.jp":true,"abira.hokkaido.jp":true,"aibetsu.hokkaido.jp":true,"akabira.hokkaido.jp":true,"akkeshi.hokkaido.jp":true,"asahikawa.hokkaido.jp":true,"ashibetsu.hokkaido.jp":true,"ashoro.hokkaido.jp":true,"assabu.hokkaido.jp":true,"atsuma.hokkaido.jp":true,"bibai.hokkaido.jp":true,"biei.hokkaido.jp":true,"bifuka.hokkaido.jp":true,"bihoro.hokkaido.jp":true,"biratori.hokkaido.jp":true,"chippubetsu.hokkaido.jp":true,"chitose.hokkaido.jp":true,"date.hokkaido.jp":true,"ebetsu.hokkaido.jp":true,"embetsu.hokkaido.jp":true,"eniwa.hokkaido.jp":true,"erimo.hokkaido.jp":true,"esan.hokkaido.jp":true,"esashi.hokkaido.jp":true,"fukagawa.hokkaido.jp":true,"fukushima.hokkaido.jp":true,"furano.hokkaido.jp":true,"furubira.hokkaido.jp":true,"haboro.hokkaido.jp":true,"hakodate.hokkaido.jp":true,"hamatonbetsu.hokkaido.jp":true,"hidaka.hokkaido.jp":true,"higashikagura.hokkaido.jp":true,"higashikawa.hokkaido.jp":true,"hiroo.hokkaido.jp":true,"hokuryu.hokkaido.jp":true,"hokuto.hokkaido.jp":true,"honbetsu.hokkaido.jp":true,"horokanai.hokkaido.jp":true,"horonobe.hokkaido.jp":true,"ikeda.hokkaido.jp":true,"imakane.hokkaido.jp":true,"ishikari.hokkaido.jp":true,"iwamizawa.hokkaido.jp":true,"iwanai.hokkaido.jp":true,"kamifurano.hokkaido.jp":true,"kamikawa.hokkaido.jp":true,"kamishihoro.hokkaido.jp":true,"kamisunagawa.hokkaido.jp":true,"kamoenai.hokkaido.jp":true,"kayabe.hokkaido.jp":true,"kembuchi.hokkaido.jp":true,"kikonai.hokkaido.jp":true,"kimobetsu.hokkaido.jp":true,"kitahiroshima.hokkaido.jp":true,"kitami.hokkaido.jp":true,"kiyosato.hokkaido.jp":true,"koshimizu.hokkaido.jp":true,"kunneppu.hokkaido.jp":true,"kuriyama.hokkaido.jp":true,"kuromatsunai.hokkaido.jp":true,"kushiro.hokkaido.jp":true,"kutchan.hokkaido.jp":true,"kyowa.hokkaido.jp":true,"mashike.hokkaido.jp":true,"matsumae.hokkaido.jp":true,"mikasa.hokkaido.jp":true,"minamifurano.hokkaido.jp":true,"mombetsu.hokkaido.jp":true,"moseushi.hokkaido.jp":true,"mukawa.hokkaido.jp":true,"muroran.hokkaido.jp":true,"naie.hokkaido.jp":true,"nakagawa.hokkaido.jp":true,"nakasatsunai.hokkaido.jp":true,"nakatombetsu.hokkaido.jp":true,"nanae.hokkaido.jp":true,"nanporo.hokkaido.jp":true,"nayoro.hokkaido.jp":true,"nemuro.hokkaido.jp":true,"niikappu.hokkaido.jp":true,"niki.hokkaido.jp":true,"nishiokoppe.hokkaido.jp":true,"noboribetsu.hokkaido.jp":true,"numata.hokkaido.jp":true,"obihiro.hokkaido.jp":true,"obira.hokkaido.jp":true,"oketo.hokkaido.jp":true,"okoppe.hokkaido.jp":true,"otaru.hokkaido.jp":true,"otobe.hokkaido.jp":true,"otofuke.hokkaido.jp":true,"otoineppu.hokkaido.jp":true,"oumu.hokkaido.jp":true,"ozora.hokkaido.jp":true,"pippu.hokkaido.jp":true,"rankoshi.hokkaido.jp":true,"rebun.hokkaido.jp":true,"rikubetsu.hokkaido.jp":true,"rishiri.hokkaido.jp":true,"rishirifuji.hokkaido.jp":true,"saroma.hokkaido.jp":true,"sarufutsu.hokkaido.jp":true,"shakotan.hokkaido.jp":true,"shari.hokkaido.jp":true,"shibecha.hokkaido.jp":true,"shibetsu.hokkaido.jp":true,"shikabe.hokkaido.jp":true,"shikaoi.hokkaido.jp":true,"shimamaki.hokkaido.jp":true,"shimizu.hokkaido.jp":true,"shimokawa.hokkaido.jp":true,"shinshinotsu.hokkaido.jp":true,"shintoku.hokkaido.jp":true,"shiranuka.hokkaido.jp":true,"shiraoi.hokkaido.jp":true,"shiriuchi.hokkaido.jp":true,"sobetsu.hokkaido.jp":true,"sunagawa.hokkaido.jp":true,"taiki.hokkaido.jp":true,"takasu.hokkaido.jp":true,"takikawa.hokkaido.jp":true,"takinoue.hokkaido.jp":true,"teshikaga.hokkaido.jp":true,"tobetsu.hokkaido.jp":true,"tohma.hokkaido.jp":true,"tomakomai.hokkaido.jp":true,"tomari.hokkaido.jp":true,"toya.hokkaido.jp":true,"toyako.hokkaido.jp":true,"toyotomi.hokkaido.jp":true,"toyoura.hokkaido.jp":true,"tsubetsu.hokkaido.jp":true,"tsukigata.hokkaido.jp":true,"urakawa.hokkaido.jp":true,"urausu.hokkaido.jp":true,"uryu.hokkaido.jp":true,"utashinai.hokkaido.jp":true,"wakkanai.hokkaido.jp":true,"wassamu.hokkaido.jp":true,"yakumo.hokkaido.jp":true,"yoichi.hokkaido.jp":true,"aioi.hyogo.jp":true,"akashi.hyogo.jp":true,"ako.hyogo.jp":true,"amagasaki.hyogo.jp":true,"aogaki.hyogo.jp":true,"asago.hyogo.jp":true,"ashiya.hyogo.jp":true,"awaji.hyogo.jp":true,"fukusaki.hyogo.jp":true,"goshiki.hyogo.jp":true,"harima.hyogo.jp":true,"himeji.hyogo.jp":true,"ichikawa.hyogo.jp":true,"inagawa.hyogo.jp":true,"itami.hyogo.jp":true,"kakogawa.hyogo.jp":true,"kamigori.hyogo.jp":true,"kamikawa.hyogo.jp":true,"kasai.hyogo.jp":true,"kasuga.hyogo.jp":true,"kawanishi.hyogo.jp":true,"miki.hyogo.jp":true,"minamiawaji.hyogo.jp":true,"nishinomiya.hyogo.jp":true,"nishiwaki.hyogo.jp":true,"ono.hyogo.jp":true,"sanda.hyogo.jp":true,"sannan.hyogo.jp":true,"sasayama.hyogo.jp":true,"sayo.hyogo.jp":true,"shingu.hyogo.jp":true,"shinonsen.hyogo.jp":true,"shiso.hyogo.jp":true,"sumoto.hyogo.jp":true,"taishi.hyogo.jp":true,"taka.hyogo.jp":true,"takarazuka.hyogo.jp":true,"takasago.hyogo.jp":true,"takino.hyogo.jp":true,"tamba.hyogo.jp":true,"tatsuno.hyogo.jp":true,"toyooka.hyogo.jp":true,"yabu.hyogo.jp":true,"yashiro.hyogo.jp":true,"yoka.hyogo.jp":true,"yokawa.hyogo.jp":true,"ami.ibaraki.jp":true,"asahi.ibaraki.jp":true,"bando.ibaraki.jp":true,"chikusei.ibaraki.jp":true,"daigo.ibaraki.jp":true,"fujishiro.ibaraki.jp":true,"hitachi.ibaraki.jp":true,"hitachinaka.ibaraki.jp":true,"hitachiomiya.ibaraki.jp":true,"hitachiota.ibaraki.jp":true,"ibaraki.ibaraki.jp":true,"ina.ibaraki.jp":true,"inashiki.ibaraki.jp":true,"itako.ibaraki.jp":true,"iwama.ibaraki.jp":true,"joso.ibaraki.jp":true,"kamisu.ibaraki.jp":true,"kasama.ibaraki.jp":true,"kashima.ibaraki.jp":true,"kasumigaura.ibaraki.jp":true,"koga.ibaraki.jp":true,"miho.ibaraki.jp":true,"mito.ibaraki.jp":true,"moriya.ibaraki.jp":true,"naka.ibaraki.jp":true,"namegata.ibaraki.jp":true,"oarai.ibaraki.jp":true,"ogawa.ibaraki.jp":true,"omitama.ibaraki.jp":true,"ryugasaki.ibaraki.jp":true,"sakai.ibaraki.jp":true,"sakuragawa.ibaraki.jp":true,"shimodate.ibaraki.jp":true,"shimotsuma.ibaraki.jp":true,"shirosato.ibaraki.jp":true,"sowa.ibaraki.jp":true,"suifu.ibaraki.jp":true,"takahagi.ibaraki.jp":true,"tamatsukuri.ibaraki.jp":true,"tokai.ibaraki.jp":true,"tomobe.ibaraki.jp":true,"tone.ibaraki.jp":true,"toride.ibaraki.jp":true,"tsuchiura.ibaraki.jp":true,"tsukuba.ibaraki.jp":true,"uchihara.ibaraki.jp":true,"ushiku.ibaraki.jp":true,"yachiyo.ibaraki.jp":true,"yamagata.ibaraki.jp":true,"yawara.ibaraki.jp":true,"yuki.ibaraki.jp":true,"anamizu.ishikawa.jp":true,"hakui.ishikawa.jp":true,"hakusan.ishikawa.jp":true,"kaga.ishikawa.jp":true,"kahoku.ishikawa.jp":true,"kanazawa.ishikawa.jp":true,"kawakita.ishikawa.jp":true,"komatsu.ishikawa.jp":true,"nakanoto.ishikawa.jp":true,"nanao.ishikawa.jp":true,"nomi.ishikawa.jp":true,"nonoichi.ishikawa.jp":true,"noto.ishikawa.jp":true,"shika.ishikawa.jp":true,"suzu.ishikawa.jp":true,"tsubata.ishikawa.jp":true,"tsurugi.ishikawa.jp":true,"uchinada.ishikawa.jp":true,"wajima.ishikawa.jp":true,"fudai.iwate.jp":true,"fujisawa.iwate.jp":true,"hanamaki.iwate.jp":true,"hiraizumi.iwate.jp":true,"hirono.iwate.jp":true,"ichinohe.iwate.jp":true,"ichinoseki.iwate.jp":true,"iwaizumi.iwate.jp":true,"iwate.iwate.jp":true,"joboji.iwate.jp":true,"kamaishi.iwate.jp":true,"kanegasaki.iwate.jp":true,"karumai.iwate.jp":true,"kawai.iwate.jp":true,"kitakami.iwate.jp":true,"kuji.iwate.jp":true,"kunohe.iwate.jp":true,"kuzumaki.iwate.jp":true,"miyako.iwate.jp":true,"mizusawa.iwate.jp":true,"morioka.iwate.jp":true,"ninohe.iwate.jp":true,"noda.iwate.jp":true,"ofunato.iwate.jp":true,"oshu.iwate.jp":true,"otsuchi.iwate.jp":true,"rikuzentakata.iwate.jp":true,"shiwa.iwate.jp":true,"shizukuishi.iwate.jp":true,"sumita.iwate.jp":true,"tanohata.iwate.jp":true,"tono.iwate.jp":true,"yahaba.iwate.jp":true,"yamada.iwate.jp":true,"ayagawa.kagawa.jp":true,"higashikagawa.kagawa.jp":true,"kanonji.kagawa.jp":true,"kotohira.kagawa.jp":true,"manno.kagawa.jp":true,"marugame.kagawa.jp":true,"mitoyo.kagawa.jp":true,"naoshima.kagawa.jp":true,"sanuki.kagawa.jp":true,"tadotsu.kagawa.jp":true,"takamatsu.kagawa.jp":true,"tonosho.kagawa.jp":true,"uchinomi.kagawa.jp":true,"utazu.kagawa.jp":true,"zentsuji.kagawa.jp":true,"akune.kagoshima.jp":true,"amami.kagoshima.jp":true,"hioki.kagoshima.jp":true,"isa.kagoshima.jp":true,"isen.kagoshima.jp":true,"izumi.kagoshima.jp":true,"kagoshima.kagoshima.jp":true,"kanoya.kagoshima.jp":true,"kawanabe.kagoshima.jp":true,"kinko.kagoshima.jp":true,"kouyama.kagoshima.jp":true,"makurazaki.kagoshima.jp":true,"matsumoto.kagoshima.jp":true,"minamitane.kagoshima.jp":true,"nakatane.kagoshima.jp":true,"nishinoomote.kagoshima.jp":true,"satsumasendai.kagoshima.jp":true,"soo.kagoshima.jp":true,"tarumizu.kagoshima.jp":true,"yusui.kagoshima.jp":true,"aikawa.kanagawa.jp":true,"atsugi.kanagawa.jp":true,"ayase.kanagawa.jp":true,"chigasaki.kanagawa.jp":true,"ebina.kanagawa.jp":true,"fujisawa.kanagawa.jp":true,"hadano.kanagawa.jp":true,"hakone.kanagawa.jp":true,"hiratsuka.kanagawa.jp":true,"isehara.kanagawa.jp":true,"kaisei.kanagawa.jp":true,"kamakura.kanagawa.jp":true,"kiyokawa.kanagawa.jp":true,"matsuda.kanagawa.jp":true,"minamiashigara.kanagawa.jp":true,"miura.kanagawa.jp":true,"nakai.kanagawa.jp":true,"ninomiya.kanagawa.jp":true,"odawara.kanagawa.jp":true,"oi.kanagawa.jp":true,"oiso.kanagawa.jp":true,"sagamihara.kanagawa.jp":true,"samukawa.kanagawa.jp":true,"tsukui.kanagawa.jp":true,"yamakita.kanagawa.jp":true,"yamato.kanagawa.jp":true,"yokosuka.kanagawa.jp":true,"yugawara.kanagawa.jp":true,"zama.kanagawa.jp":true,"zushi.kanagawa.jp":true,"aki.kochi.jp":true,"geisei.kochi.jp":true,"hidaka.kochi.jp":true,"higashitsuno.kochi.jp":true,"ino.kochi.jp":true,"kagami.kochi.jp":true,"kami.kochi.jp":true,"kitagawa.kochi.jp":true,"kochi.kochi.jp":true,"mihara.kochi.jp":true,"motoyama.kochi.jp":true,"muroto.kochi.jp":true,"nahari.kochi.jp":true,"nakamura.kochi.jp":true,"nankoku.kochi.jp":true,"nishitosa.kochi.jp":true,"niyodogawa.kochi.jp":true,"ochi.kochi.jp":true,"okawa.kochi.jp":true,"otoyo.kochi.jp":true,"otsuki.kochi.jp":true,"sakawa.kochi.jp":true,"sukumo.kochi.jp":true,"susaki.kochi.jp":true,"tosa.kochi.jp":true,"tosashimizu.kochi.jp":true,"toyo.kochi.jp":true,"tsuno.kochi.jp":true,"umaji.kochi.jp":true,"yasuda.kochi.jp":true,"yusuhara.kochi.jp":true,"amakusa.kumamoto.jp":true,"arao.kumamoto.jp":true,"aso.kumamoto.jp":true,"choyo.kumamoto.jp":true,"gyokuto.kumamoto.jp":true,"hitoyoshi.kumamoto.jp":true,"kamiamakusa.kumamoto.jp":true,"kashima.kumamoto.jp":true,"kikuchi.kumamoto.jp":true,"kosa.kumamoto.jp":true,"kumamoto.kumamoto.jp":true,"mashiki.kumamoto.jp":true,"mifune.kumamoto.jp":true,"minamata.kumamoto.jp":true,"minamioguni.kumamoto.jp":true,"nagasu.kumamoto.jp":true,"nishihara.kumamoto.jp":true,"oguni.kumamoto.jp":true,"ozu.kumamoto.jp":true,"sumoto.kumamoto.jp":true,"takamori.kumamoto.jp":true,"uki.kumamoto.jp":true,"uto.kumamoto.jp":true,"yamaga.kumamoto.jp":true,"yamato.kumamoto.jp":true,"yatsushiro.kumamoto.jp":true,"ayabe.kyoto.jp":true,"fukuchiyama.kyoto.jp":true,"higashiyama.kyoto.jp":true,"ide.kyoto.jp":true,"ine.kyoto.jp":true,"joyo.kyoto.jp":true,"kameoka.kyoto.jp":true,"kamo.kyoto.jp":true,"kita.kyoto.jp":true,"kizu.kyoto.jp":true,"kumiyama.kyoto.jp":true,"kyotamba.kyoto.jp":true,"kyotanabe.kyoto.jp":true,"kyotango.kyoto.jp":true,"maizuru.kyoto.jp":true,"minami.kyoto.jp":true,"minamiyamashiro.kyoto.jp":true,"miyazu.kyoto.jp":true,"muko.kyoto.jp":true,"nagaokakyo.kyoto.jp":true,"nakagyo.kyoto.jp":true,"nantan.kyoto.jp":true,"oyamazaki.kyoto.jp":true,"sakyo.kyoto.jp":true,"seika.kyoto.jp":true,"tanabe.kyoto.jp":true,"uji.kyoto.jp":true,"ujitawara.kyoto.jp":true,"wazuka.kyoto.jp":true,"yamashina.kyoto.jp":true,"yawata.kyoto.jp":true,"asahi.mie.jp":true,"inabe.mie.jp":true,"ise.mie.jp":true,"kameyama.mie.jp":true,"kawagoe.mie.jp":true,"kiho.mie.jp":true,"kisosaki.mie.jp":true,"kiwa.mie.jp":true,"komono.mie.jp":true,"kumano.mie.jp":true,"kuwana.mie.jp":true,"matsusaka.mie.jp":true,"meiwa.mie.jp":true,"mihama.mie.jp":true,"minamiise.mie.jp":true,"misugi.mie.jp":true,"miyama.mie.jp":true,"nabari.mie.jp":true,"shima.mie.jp":true,"suzuka.mie.jp":true,"tado.mie.jp":true,"taiki.mie.jp":true,"taki.mie.jp":true,"tamaki.mie.jp":true,"toba.mie.jp":true,"tsu.mie.jp":true,"udono.mie.jp":true,"ureshino.mie.jp":true,"watarai.mie.jp":true,"yokkaichi.mie.jp":true,"furukawa.miyagi.jp":true,"higashimatsushima.miyagi.jp":true,"ishinomaki.miyagi.jp":true,"iwanuma.miyagi.jp":true,"kakuda.miyagi.jp":true,"kami.miyagi.jp":true,"kawasaki.miyagi.jp":true,"kesennuma.miyagi.jp":true,"marumori.miyagi.jp":true,"matsushima.miyagi.jp":true,"minamisanriku.miyagi.jp":true,"misato.miyagi.jp":true,"murata.miyagi.jp":true,"natori.miyagi.jp":true,"ogawara.miyagi.jp":true,"ohira.miyagi.jp":true,"onagawa.miyagi.jp":true,"osaki.miyagi.jp":true,"rifu.miyagi.jp":true,"semine.miyagi.jp":true,"shibata.miyagi.jp":true,"shichikashuku.miyagi.jp":true,"shikama.miyagi.jp":true,"shiogama.miyagi.jp":true,"shiroishi.miyagi.jp":true,"tagajo.miyagi.jp":true,"taiwa.miyagi.jp":true,"tome.miyagi.jp":true,"tomiya.miyagi.jp":true,"wakuya.miyagi.jp":true,"watari.miyagi.jp":true,"yamamoto.miyagi.jp":true,"zao.miyagi.jp":true,"aya.miyazaki.jp":true,"ebino.miyazaki.jp":true,"gokase.miyazaki.jp":true,"hyuga.miyazaki.jp":true,"kadogawa.miyazaki.jp":true,"kawaminami.miyazaki.jp":true,"kijo.miyazaki.jp":true,"kitagawa.miyazaki.jp":true,"kitakata.miyazaki.jp":true,"kitaura.miyazaki.jp":true,"kobayashi.miyazaki.jp":true,"kunitomi.miyazaki.jp":true,"kushima.miyazaki.jp":true,"mimata.miyazaki.jp":true,"miyakonojo.miyazaki.jp":true,"miyazaki.miyazaki.jp":true,"morotsuka.miyazaki.jp":true,"nichinan.miyazaki.jp":true,"nishimera.miyazaki.jp":true,"nobeoka.miyazaki.jp":true,"saito.miyazaki.jp":true,"shiiba.miyazaki.jp":true,"shintomi.miyazaki.jp":true,"takaharu.miyazaki.jp":true,"takanabe.miyazaki.jp":true,"takazaki.miyazaki.jp":true,"tsuno.miyazaki.jp":true,"achi.nagano.jp":true,"agematsu.nagano.jp":true,"anan.nagano.jp":true,"aoki.nagano.jp":true,"asahi.nagano.jp":true,"azumino.nagano.jp":true,"chikuhoku.nagano.jp":true,"chikuma.nagano.jp":true,"chino.nagano.jp":true,"fujimi.nagano.jp":true,"hakuba.nagano.jp":true,"hara.nagano.jp":true,"hiraya.nagano.jp":true,"iida.nagano.jp":true,"iijima.nagano.jp":true,"iiyama.nagano.jp":true,"iizuna.nagano.jp":true,"ikeda.nagano.jp":true,"ikusaka.nagano.jp":true,"ina.nagano.jp":true,"karuizawa.nagano.jp":true,"kawakami.nagano.jp":true,"kiso.nagano.jp":true,"kisofukushima.nagano.jp":true,"kitaaiki.nagano.jp":true,"komagane.nagano.jp":true,"komoro.nagano.jp":true,"matsukawa.nagano.jp":true,"matsumoto.nagano.jp":true,"miasa.nagano.jp":true,"minamiaiki.nagano.jp":true,"minamimaki.nagano.jp":true,"minamiminowa.nagano.jp":true,"minowa.nagano.jp":true,"miyada.nagano.jp":true,"miyota.nagano.jp":true,"mochizuki.nagano.jp":true,"nagano.nagano.jp":true,"nagawa.nagano.jp":true,"nagiso.nagano.jp":true,"nakagawa.nagano.jp":true,"nakano.nagano.jp":true,"nozawaonsen.nagano.jp":true,"obuse.nagano.jp":true,"ogawa.nagano.jp":true,"okaya.nagano.jp":true,"omachi.nagano.jp":true,"omi.nagano.jp":true,"ookuwa.nagano.jp":true,"ooshika.nagano.jp":true,"otaki.nagano.jp":true,"otari.nagano.jp":true,"sakae.nagano.jp":true,"sakaki.nagano.jp":true,"saku.nagano.jp":true,"sakuho.nagano.jp":true,"shimosuwa.nagano.jp":true,"shinanomachi.nagano.jp":true,"shiojiri.nagano.jp":true,"suwa.nagano.jp":true,"suzaka.nagano.jp":true,"takagi.nagano.jp":true,"takamori.nagano.jp":true,"takayama.nagano.jp":true,"tateshina.nagano.jp":true,"tatsuno.nagano.jp":true,"togakushi.nagano.jp":true,"togura.nagano.jp":true,"tomi.nagano.jp":true,"ueda.nagano.jp":true,"wada.nagano.jp":true,"yamagata.nagano.jp":true,"yamanouchi.nagano.jp":true,"yasaka.nagano.jp":true,"yasuoka.nagano.jp":true,"chijiwa.nagasaki.jp":true,"futsu.nagasaki.jp":true,"goto.nagasaki.jp":true,"hasami.nagasaki.jp":true,"hirado.nagasaki.jp":true,"iki.nagasaki.jp":true,"isahaya.nagasaki.jp":true,"kawatana.nagasaki.jp":true,"kuchinotsu.nagasaki.jp":true,"matsuura.nagasaki.jp":true,"nagasaki.nagasaki.jp":true,"obama.nagasaki.jp":true,"omura.nagasaki.jp":true,"oseto.nagasaki.jp":true,"saikai.nagasaki.jp":true,"sasebo.nagasaki.jp":true,"seihi.nagasaki.jp":true,"shimabara.nagasaki.jp":true,"shinkamigoto.nagasaki.jp":true,"togitsu.nagasaki.jp":true,"tsushima.nagasaki.jp":true,"unzen.nagasaki.jp":true,"ando.nara.jp":true,"gose.nara.jp":true,"heguri.nara.jp":true,"higashiyoshino.nara.jp":true,"ikaruga.nara.jp":true,"ikoma.nara.jp":true,"kamikitayama.nara.jp":true,"kanmaki.nara.jp":true,"kashiba.nara.jp":true,"kashihara.nara.jp":true,"katsuragi.nara.jp":true,"kawai.nara.jp":true,"kawakami.nara.jp":true,"kawanishi.nara.jp":true,"koryo.nara.jp":true,"kurotaki.nara.jp":true,"mitsue.nara.jp":true,"miyake.nara.jp":true,"nara.nara.jp":true,"nosegawa.nara.jp":true,"oji.nara.jp":true,"ouda.nara.jp":true,"oyodo.nara.jp":true,"sakurai.nara.jp":true,"sango.nara.jp":true,"shimoichi.nara.jp":true,"shimokitayama.nara.jp":true,"shinjo.nara.jp":true,"soni.nara.jp":true,"takatori.nara.jp":true,"tawaramoto.nara.jp":true,"tenkawa.nara.jp":true,"tenri.nara.jp":true,"uda.nara.jp":true,"yamatokoriyama.nara.jp":true,"yamatotakada.nara.jp":true,"yamazoe.nara.jp":true,"yoshino.nara.jp":true,"aga.niigata.jp":true,"agano.niigata.jp":true,"gosen.niigata.jp":true,"itoigawa.niigata.jp":true,"izumozaki.niigata.jp":true,"joetsu.niigata.jp":true,"kamo.niigata.jp":true,"kariwa.niigata.jp":true,"kashiwazaki.niigata.jp":true,"minamiuonuma.niigata.jp":true,"mitsuke.niigata.jp":true,"muika.niigata.jp":true,"murakami.niigata.jp":true,"myoko.niigata.jp":true,"nagaoka.niigata.jp":true,"niigata.niigata.jp":true,"ojiya.niigata.jp":true,"omi.niigata.jp":true,"sado.niigata.jp":true,"sanjo.niigata.jp":true,"seiro.niigata.jp":true,"seirou.niigata.jp":true,"sekikawa.niigata.jp":true,"shibata.niigata.jp":true,"tagami.niigata.jp":true,"tainai.niigata.jp":true,"tochio.niigata.jp":true,"tokamachi.niigata.jp":true,"tsubame.niigata.jp":true,"tsunan.niigata.jp":true,"uonuma.niigata.jp":true,"yahiko.niigata.jp":true,"yoita.niigata.jp":true,"yuzawa.niigata.jp":true,"beppu.oita.jp":true,"bungoono.oita.jp":true,"bungotakada.oita.jp":true,"hasama.oita.jp":true,"hiji.oita.jp":true,"himeshima.oita.jp":true,"hita.oita.jp":true,"kamitsue.oita.jp":true,"kokonoe.oita.jp":true,"kuju.oita.jp":true,"kunisaki.oita.jp":true,"kusu.oita.jp":true,"oita.oita.jp":true,"saiki.oita.jp":true,"taketa.oita.jp":true,"tsukumi.oita.jp":true,"usa.oita.jp":true,"usuki.oita.jp":true,"yufu.oita.jp":true,"akaiwa.okayama.jp":true,"asakuchi.okayama.jp":true,"bizen.okayama.jp":true,"hayashima.okayama.jp":true,"ibara.okayama.jp":true,"kagamino.okayama.jp":true,"kasaoka.okayama.jp":true,"kibichuo.okayama.jp":true,"kumenan.okayama.jp":true,"kurashiki.okayama.jp":true,"maniwa.okayama.jp":true,"misaki.okayama.jp":true,"nagi.okayama.jp":true,"niimi.okayama.jp":true,"nishiawakura.okayama.jp":true,"okayama.okayama.jp":true,"satosho.okayama.jp":true,"setouchi.okayama.jp":true,"shinjo.okayama.jp":true,"shoo.okayama.jp":true,"soja.okayama.jp":true,"takahashi.okayama.jp":true,"tamano.okayama.jp":true,"tsuyama.okayama.jp":true,"wake.okayama.jp":true,"yakage.okayama.jp":true,"aguni.okinawa.jp":true,"ginowan.okinawa.jp":true,"ginoza.okinawa.jp":true,"gushikami.okinawa.jp":true,"haebaru.okinawa.jp":true,"higashi.okinawa.jp":true,"hirara.okinawa.jp":true,"iheya.okinawa.jp":true,"ishigaki.okinawa.jp":true,"ishikawa.okinawa.jp":true,"itoman.okinawa.jp":true,"izena.okinawa.jp":true,"kadena.okinawa.jp":true,"kin.okinawa.jp":true,"kitadaito.okinawa.jp":true,"kitanakagusuku.okinawa.jp":true,"kumejima.okinawa.jp":true,"kunigami.okinawa.jp":true,"minamidaito.okinawa.jp":true,"motobu.okinawa.jp":true,"nago.okinawa.jp":true,"naha.okinawa.jp":true,"nakagusuku.okinawa.jp":true,"nakijin.okinawa.jp":true,"nanjo.okinawa.jp":true,"nishihara.okinawa.jp":true,"ogimi.okinawa.jp":true,"okinawa.okinawa.jp":true,"onna.okinawa.jp":true,"shimoji.okinawa.jp":true,"taketomi.okinawa.jp":true,"tarama.okinawa.jp":true,"tokashiki.okinawa.jp":true,"tomigusuku.okinawa.jp":true,"tonaki.okinawa.jp":true,"urasoe.okinawa.jp":true,"uruma.okinawa.jp":true,"yaese.okinawa.jp":true,"yomitan.okinawa.jp":true,"yonabaru.okinawa.jp":true,"yonaguni.okinawa.jp":true,"zamami.okinawa.jp":true,"abeno.osaka.jp":true,"chihayaakasaka.osaka.jp":true,"chuo.osaka.jp":true,"daito.osaka.jp":true,"fujiidera.osaka.jp":true,"habikino.osaka.jp":true,"hannan.osaka.jp":true,"higashiosaka.osaka.jp":true,"higashisumiyoshi.osaka.jp":true,"higashiyodogawa.osaka.jp":true,"hirakata.osaka.jp":true,"ibaraki.osaka.jp":true,"ikeda.osaka.jp":true,"izumi.osaka.jp":true,"izumiotsu.osaka.jp":true,"izumisano.osaka.jp":true,"kadoma.osaka.jp":true,"kaizuka.osaka.jp":true,"kanan.osaka.jp":true,"kashiwara.osaka.jp":true,"katano.osaka.jp":true,"kawachinagano.osaka.jp":true,"kishiwada.osaka.jp":true,"kita.osaka.jp":true,"kumatori.osaka.jp":true,"matsubara.osaka.jp":true,"minato.osaka.jp":true,"minoh.osaka.jp":true,"misaki.osaka.jp":true,"moriguchi.osaka.jp":true,"neyagawa.osaka.jp":true,"nishi.osaka.jp":true,"nose.osaka.jp":true,"osakasayama.osaka.jp":true,"sakai.osaka.jp":true,"sayama.osaka.jp":true,"sennan.osaka.jp":true,"settsu.osaka.jp":true,"shijonawate.osaka.jp":true,"shimamoto.osaka.jp":true,"suita.osaka.jp":true,"tadaoka.osaka.jp":true,"taishi.osaka.jp":true,"tajiri.osaka.jp":true,"takaishi.osaka.jp":true,"takatsuki.osaka.jp":true,"tondabayashi.osaka.jp":true,"toyonaka.osaka.jp":true,"toyono.osaka.jp":true,"yao.osaka.jp":true,"ariake.saga.jp":true,"arita.saga.jp":true,"fukudomi.saga.jp":true,"genkai.saga.jp":true,"hamatama.saga.jp":true,"hizen.saga.jp":true,"imari.saga.jp":true,"kamimine.saga.jp":true,"kanzaki.saga.jp":true,"karatsu.saga.jp":true,"kashima.saga.jp":true,"kitagata.saga.jp":true,"kitahata.saga.jp":true,"kiyama.saga.jp":true,"kouhoku.saga.jp":true,"kyuragi.saga.jp":true,"nishiarita.saga.jp":true,"ogi.saga.jp":true,"omachi.saga.jp":true,"ouchi.saga.jp":true,"saga.saga.jp":true,"shiroishi.saga.jp":true,"taku.saga.jp":true,"tara.saga.jp":true,"tosu.saga.jp":true,"yoshinogari.saga.jp":true,"arakawa.saitama.jp":true,"asaka.saitama.jp":true,"chichibu.saitama.jp":true,"fujimi.saitama.jp":true,"fujimino.saitama.jp":true,"fukaya.saitama.jp":true,"hanno.saitama.jp":true,"hanyu.saitama.jp":true,"hasuda.saitama.jp":true,"hatogaya.saitama.jp":true,"hatoyama.saitama.jp":true,"hidaka.saitama.jp":true,"higashichichibu.saitama.jp":true,"higashimatsuyama.saitama.jp":true,"honjo.saitama.jp":true,"ina.saitama.jp":true,"iruma.saitama.jp":true,"iwatsuki.saitama.jp":true,"kamiizumi.saitama.jp":true,"kamikawa.saitama.jp":true,"kamisato.saitama.jp":true,"kasukabe.saitama.jp":true,"kawagoe.saitama.jp":true,"kawaguchi.saitama.jp":true,"kawajima.saitama.jp":true,"kazo.saitama.jp":true,"kitamoto.saitama.jp":true,"koshigaya.saitama.jp":true,"kounosu.saitama.jp":true,"kuki.saitama.jp":true,"kumagaya.saitama.jp":true,"matsubushi.saitama.jp":true,"minano.saitama.jp":true,"misato.saitama.jp":true,"miyashiro.saitama.jp":true,"miyoshi.saitama.jp":true,"moroyama.saitama.jp":true,"nagatoro.saitama.jp":true,"namegawa.saitama.jp":true,"niiza.saitama.jp":true,"ogano.saitama.jp":true,"ogawa.saitama.jp":true,"ogose.saitama.jp":true,"okegawa.saitama.jp":true,"omiya.saitama.jp":true,"otaki.saitama.jp":true,"ranzan.saitama.jp":true,"ryokami.saitama.jp":true,"saitama.saitama.jp":true,"sakado.saitama.jp":true,"satte.saitama.jp":true,"sayama.saitama.jp":true,"shiki.saitama.jp":true,"shiraoka.saitama.jp":true,"soka.saitama.jp":true,"sugito.saitama.jp":true,"toda.saitama.jp":true,"tokigawa.saitama.jp":true,"tokorozawa.saitama.jp":true,"tsurugashima.saitama.jp":true,"urawa.saitama.jp":true,"warabi.saitama.jp":true,"yashio.saitama.jp":true,"yokoze.saitama.jp":true,"yono.saitama.jp":true,"yorii.saitama.jp":true,"yoshida.saitama.jp":true,"yoshikawa.saitama.jp":true,"yoshimi.saitama.jp":true,"aisho.shiga.jp":true,"gamo.shiga.jp":true,"higashiomi.shiga.jp":true,"hikone.shiga.jp":true,"koka.shiga.jp":true,"konan.shiga.jp":true,"kosei.shiga.jp":true,"koto.shiga.jp":true,"kusatsu.shiga.jp":true,"maibara.shiga.jp":true,"moriyama.shiga.jp":true,"nagahama.shiga.jp":true,"nishiazai.shiga.jp":true,"notogawa.shiga.jp":true,"omihachiman.shiga.jp":true,"otsu.shiga.jp":true,"ritto.shiga.jp":true,"ryuoh.shiga.jp":true,"takashima.shiga.jp":true,"takatsuki.shiga.jp":true,"torahime.shiga.jp":true,"toyosato.shiga.jp":true,"yasu.shiga.jp":true,"akagi.shimane.jp":true,"ama.shimane.jp":true,"gotsu.shimane.jp":true,"hamada.shimane.jp":true,"higashiizumo.shimane.jp":true,"hikawa.shimane.jp":true,"hikimi.shimane.jp":true,"izumo.shimane.jp":true,"kakinoki.shimane.jp":true,"masuda.shimane.jp":true,"matsue.shimane.jp":true,"misato.shimane.jp":true,"nishinoshima.shimane.jp":true,"ohda.shimane.jp":true,"okinoshima.shimane.jp":true,"okuizumo.shimane.jp":true,"shimane.shimane.jp":true,"tamayu.shimane.jp":true,"tsuwano.shimane.jp":true,"unnan.shimane.jp":true,"yakumo.shimane.jp":true,"yasugi.shimane.jp":true,"yatsuka.shimane.jp":true,"arai.shizuoka.jp":true,"atami.shizuoka.jp":true,"fuji.shizuoka.jp":true,"fujieda.shizuoka.jp":true,"fujikawa.shizuoka.jp":true,"fujinomiya.shizuoka.jp":true,"fukuroi.shizuoka.jp":true,"gotemba.shizuoka.jp":true,"haibara.shizuoka.jp":true,"hamamatsu.shizuoka.jp":true,"higashiizu.shizuoka.jp":true,"ito.shizuoka.jp":true,"iwata.shizuoka.jp":true,"izu.shizuoka.jp":true,"izunokuni.shizuoka.jp":true,"kakegawa.shizuoka.jp":true,"kannami.shizuoka.jp":true,"kawanehon.shizuoka.jp":true,"kawazu.shizuoka.jp":true,"kikugawa.shizuoka.jp":true,"kosai.shizuoka.jp":true,"makinohara.shizuoka.jp":true,"matsuzaki.shizuoka.jp":true,"minamiizu.shizuoka.jp":true,"mishima.shizuoka.jp":true,"morimachi.shizuoka.jp":true,"nishiizu.shizuoka.jp":true,"numazu.shizuoka.jp":true,"omaezaki.shizuoka.jp":true,"shimada.shizuoka.jp":true,"shimizu.shizuoka.jp":true,"shimoda.shizuoka.jp":true,"shizuoka.shizuoka.jp":true,"susono.shizuoka.jp":true,"yaizu.shizuoka.jp":true,"yoshida.shizuoka.jp":true,"ashikaga.tochigi.jp":true,"bato.tochigi.jp":true,"haga.tochigi.jp":true,"ichikai.tochigi.jp":true,"iwafune.tochigi.jp":true,"kaminokawa.tochigi.jp":true,"kanuma.tochigi.jp":true,"karasuyama.tochigi.jp":true,"kuroiso.tochigi.jp":true,"mashiko.tochigi.jp":true,"mibu.tochigi.jp":true,"moka.tochigi.jp":true,"motegi.tochigi.jp":true,"nasu.tochigi.jp":true,"nasushiobara.tochigi.jp":true,"nikko.tochigi.jp":true,"nishikata.tochigi.jp":true,"nogi.tochigi.jp":true,"ohira.tochigi.jp":true,"ohtawara.tochigi.jp":true,"oyama.tochigi.jp":true,"sakura.tochigi.jp":true,"sano.tochigi.jp":true,"shimotsuke.tochigi.jp":true,"shioya.tochigi.jp":true,"takanezawa.tochigi.jp":true,"tochigi.tochigi.jp":true,"tsuga.tochigi.jp":true,"ujiie.tochigi.jp":true,"utsunomiya.tochigi.jp":true,"yaita.tochigi.jp":true,"aizumi.tokushima.jp":true,"anan.tokushima.jp":true,"ichiba.tokushima.jp":true,"itano.tokushima.jp":true,"kainan.tokushima.jp":true,"komatsushima.tokushima.jp":true,"matsushige.tokushima.jp":true,"mima.tokushima.jp":true,"minami.tokushima.jp":true,"miyoshi.tokushima.jp":true,"mugi.tokushima.jp":true,"nakagawa.tokushima.jp":true,"naruto.tokushima.jp":true,"sanagochi.tokushima.jp":true,"shishikui.tokushima.jp":true,"tokushima.tokushima.jp":true,"wajiki.tokushima.jp":true,"adachi.tokyo.jp":true,"akiruno.tokyo.jp":true,"akishima.tokyo.jp":true,"aogashima.tokyo.jp":true,"arakawa.tokyo.jp":true,"bunkyo.tokyo.jp":true,"chiyoda.tokyo.jp":true,"chofu.tokyo.jp":true,"chuo.tokyo.jp":true,"edogawa.tokyo.jp":true,"fuchu.tokyo.jp":true,"fussa.tokyo.jp":true,"hachijo.tokyo.jp":true,"hachioji.tokyo.jp":true,"hamura.tokyo.jp":true,"higashikurume.tokyo.jp":true,"higashimurayama.tokyo.jp":true,"higashiyamato.tokyo.jp":true,"hino.tokyo.jp":true,"hinode.tokyo.jp":true,"hinohara.tokyo.jp":true,"inagi.tokyo.jp":true,"itabashi.tokyo.jp":true,"katsushika.tokyo.jp":true,"kita.tokyo.jp":true,"kiyose.tokyo.jp":true,"kodaira.tokyo.jp":true,"koganei.tokyo.jp":true,"kokubunji.tokyo.jp":true,"komae.tokyo.jp":true,"koto.tokyo.jp":true,"kouzushima.tokyo.jp":true,"kunitachi.tokyo.jp":true,"machida.tokyo.jp":true,"meguro.tokyo.jp":true,"minato.tokyo.jp":true,"mitaka.tokyo.jp":true,"mizuho.tokyo.jp":true,"musashimurayama.tokyo.jp":true,"musashino.tokyo.jp":true,"nakano.tokyo.jp":true,"nerima.tokyo.jp":true,"ogasawara.tokyo.jp":true,"okutama.tokyo.jp":true,"ome.tokyo.jp":true,"oshima.tokyo.jp":true,"ota.tokyo.jp":true,"setagaya.tokyo.jp":true,"shibuya.tokyo.jp":true,"shinagawa.tokyo.jp":true,"shinjuku.tokyo.jp":true,"suginami.tokyo.jp":true,"sumida.tokyo.jp":true,"tachikawa.tokyo.jp":true,"taito.tokyo.jp":true,"tama.tokyo.jp":true,"toshima.tokyo.jp":true,"chizu.tottori.jp":true,"hino.tottori.jp":true,"kawahara.tottori.jp":true,"koge.tottori.jp":true,"kotoura.tottori.jp":true,"misasa.tottori.jp":true,"nanbu.tottori.jp":true,"nichinan.tottori.jp":true,"sakaiminato.tottori.jp":true,"tottori.tottori.jp":true,"wakasa.tottori.jp":true,"yazu.tottori.jp":true,"yonago.tottori.jp":true,"asahi.toyama.jp":true,"fuchu.toyama.jp":true,"fukumitsu.toyama.jp":true,"funahashi.toyama.jp":true,"himi.toyama.jp":true,"imizu.toyama.jp":true,"inami.toyama.jp":true,"johana.toyama.jp":true,"kamiichi.toyama.jp":true,"kurobe.toyama.jp":true,"nakaniikawa.toyama.jp":true,"namerikawa.toyama.jp":true,"nanto.toyama.jp":true,"nyuzen.toyama.jp":true,"oyabe.toyama.jp":true,"taira.toyama.jp":true,"takaoka.toyama.jp":true,"tateyama.toyama.jp":true,"toga.toyama.jp":true,"tonami.toyama.jp":true,"toyama.toyama.jp":true,"unazuki.toyama.jp":true,"uozu.toyama.jp":true,"yamada.toyama.jp":true,"arida.wakayama.jp":true,"aridagawa.wakayama.jp":true,"gobo.wakayama.jp":true,"hashimoto.wakayama.jp":true,"hidaka.wakayama.jp":true,"hirogawa.wakayama.jp":true,"inami.wakayama.jp":true,"iwade.wakayama.jp":true,"kainan.wakayama.jp":true,"kamitonda.wakayama.jp":true,"katsuragi.wakayama.jp":true,"kimino.wakayama.jp":true,"kinokawa.wakayama.jp":true,"kitayama.wakayama.jp":true,"koya.wakayama.jp":true,"koza.wakayama.jp":true,"kozagawa.wakayama.jp":true,"kudoyama.wakayama.jp":true,"kushimoto.wakayama.jp":true,"mihama.wakayama.jp":true,"misato.wakayama.jp":true,"nachikatsuura.wakayama.jp":true,"shingu.wakayama.jp":true,"shirahama.wakayama.jp":true,"taiji.wakayama.jp":true,"tanabe.wakayama.jp":true,"wakayama.wakayama.jp":true,"yuasa.wakayama.jp":true,"yura.wakayama.jp":true,"asahi.yamagata.jp":true,"funagata.yamagata.jp":true,"higashine.yamagata.jp":true,"iide.yamagata.jp":true,"kahoku.yamagata.jp":true,"kaminoyama.yamagata.jp":true,"kaneyama.yamagata.jp":true,"kawanishi.yamagata.jp":true,"mamurogawa.yamagata.jp":true,"mikawa.yamagata.jp":true,"murayama.yamagata.jp":true,"nagai.yamagata.jp":true,"nakayama.yamagata.jp":true,"nanyo.yamagata.jp":true,"nishikawa.yamagata.jp":true,"obanazawa.yamagata.jp":true,"oe.yamagata.jp":true,"oguni.yamagata.jp":true,"ohkura.yamagata.jp":true,"oishida.yamagata.jp":true,"sagae.yamagata.jp":true,"sakata.yamagata.jp":true,"sakegawa.yamagata.jp":true,"shinjo.yamagata.jp":true,"shirataka.yamagata.jp":true,"shonai.yamagata.jp":true,"takahata.yamagata.jp":true,"tendo.yamagata.jp":true,"tozawa.yamagata.jp":true,"tsuruoka.yamagata.jp":true,"yamagata.yamagata.jp":true,"yamanobe.yamagata.jp":true,"yonezawa.yamagata.jp":true,"yuza.yamagata.jp":true,"abu.yamaguchi.jp":true,"hagi.yamaguchi.jp":true,"hikari.yamaguchi.jp":true,"hofu.yamaguchi.jp":true,"iwakuni.yamaguchi.jp":true,"kudamatsu.yamaguchi.jp":true,"mitou.yamaguchi.jp":true,"nagato.yamaguchi.jp":true,"oshima.yamaguchi.jp":true,"shimonoseki.yamaguchi.jp":true,"shunan.yamaguchi.jp":true,"tabuse.yamaguchi.jp":true,"tokuyama.yamaguchi.jp":true,"toyota.yamaguchi.jp":true,"ube.yamaguchi.jp":true,"yuu.yamaguchi.jp":true,"chuo.yamanashi.jp":true,"doshi.yamanashi.jp":true,"fuefuki.yamanashi.jp":true,"fujikawa.yamanashi.jp":true,"fujikawaguchiko.yamanashi.jp":true,"fujiyoshida.yamanashi.jp":true,"hayakawa.yamanashi.jp":true,"hokuto.yamanashi.jp":true,"ichikawamisato.yamanashi.jp":true,"kai.yamanashi.jp":true,"kofu.yamanashi.jp":true,"koshu.yamanashi.jp":true,"kosuge.yamanashi.jp":true,"minami-alps.yamanashi.jp":true,"minobu.yamanashi.jp":true,"nakamichi.yamanashi.jp":true,"nanbu.yamanashi.jp":true,"narusawa.yamanashi.jp":true,"nirasaki.yamanashi.jp":true,"nishikatsura.yamanashi.jp":true,"oshino.yamanashi.jp":true,"otsuki.yamanashi.jp":true,"showa.yamanashi.jp":true,"tabayama.yamanashi.jp":true,"tsuru.yamanashi.jp":true,"uenohara.yamanashi.jp":true,"yamanakako.yamanashi.jp":true,"yamanashi.yamanashi.jp":true,"*.ke":true,"kg":true,"org.kg":true,"net.kg":true,"com.kg":true,"edu.kg":true,"gov.kg":true,"mil.kg":true,"*.kh":true,"ki":true,"edu.ki":true,"biz.ki":true,"net.ki":true,"org.ki":true,"gov.ki":true,"info.ki":true,"com.ki":true,"km":true,"org.km":true,"nom.km":true,"gov.km":true,"prd.km":true,"tm.km":true,"edu.km":true,"mil.km":true,"ass.km":true,"com.km":true,"coop.km":true,"asso.km":true,"presse.km":true,"medecin.km":true,"notaires.km":true,"pharmaciens.km":true,"veterinaire.km":true,"gouv.km":true,"kn":true,"net.kn":true,"org.kn":true,"edu.kn":true,"gov.kn":true,"kp":true,"com.kp":true,"edu.kp":true,"gov.kp":true,"org.kp":true,"rep.kp":true,"tra.kp":true,"kr":true,"ac.kr":true,"co.kr":true,"es.kr":true,"go.kr":true,"hs.kr":true,"kg.kr":true,"mil.kr":true,"ms.kr":true,"ne.kr":true,"or.kr":true,"pe.kr":true,"re.kr":true,"sc.kr":true,"busan.kr":true,"chungbuk.kr":true,"chungnam.kr":true,"daegu.kr":true,"daejeon.kr":true,"gangwon.kr":true,"gwangju.kr":true,"gyeongbuk.kr":true,"gyeonggi.kr":true,"gyeongnam.kr":true,"incheon.kr":true,"jeju.kr":true,"jeonbuk.kr":true,"jeonnam.kr":true,"seoul.kr":true,"ulsan.kr":true,"*.kw":true,"ky":true,"edu.ky":true,"gov.ky":true,"com.ky":true,"org.ky":true,"net.ky":true,"kz":true,"org.kz":true,"edu.kz":true,"net.kz":true,"gov.kz":true,"mil.kz":true,"com.kz":true,"la":true,"int.la":true,"net.la":true,"info.la":true,"edu.la":true,"gov.la":true,"per.la":true,"com.la":true,"org.la":true,"lb":true,"com.lb":true,"edu.lb":true,"gov.lb":true,"net.lb":true,"org.lb":true,"lc":true,"com.lc":true,"net.lc":true,"co.lc":true,"org.lc":true,"edu.lc":true,"gov.lc":true,"li":true,"lk":true,"gov.lk":true,"sch.lk":true,"net.lk":true,"int.lk":true,"com.lk":true,"org.lk":true,"edu.lk":true,"ngo.lk":true,"soc.lk":true,"web.lk":true,"ltd.lk":true,"assn.lk":true,"grp.lk":true,"hotel.lk":true,"lr":true,"com.lr":true,"edu.lr":true,"gov.lr":true,"org.lr":true,"net.lr":true,"ls":true,"co.ls":true,"org.ls":true,"lt":true,"gov.lt":true,"lu":true,"lv":true,"com.lv":true,"edu.lv":true,"gov.lv":true,"org.lv":true,"mil.lv":true,"id.lv":true,"net.lv":true,"asn.lv":true,"conf.lv":true,"ly":true,"com.ly":true,"net.ly":true,"gov.ly":true,"plc.ly":true,"edu.ly":true,"sch.ly":true,"med.ly":true,"org.ly":true,"id.ly":true,"ma":true,"co.ma":true,"net.ma":true,"gov.ma":true,"org.ma":true,"ac.ma":true,"press.ma":true,"mc":true,"tm.mc":true,"asso.mc":true,"md":true,"me":true,"co.me":true,"net.me":true,"org.me":true,"edu.me":true,"ac.me":true,"gov.me":true,"its.me":true,"priv.me":true,"mg":true,"org.mg":true,"nom.mg":true,"gov.mg":true,"prd.mg":true,"tm.mg":true,"edu.mg":true,"mil.mg":true,"com.mg":true,"mh":true,"mil":true,"mk":true,"com.mk":true,"org.mk":true,"net.mk":true,"edu.mk":true,"gov.mk":true,"inf.mk":true,"name.mk":true,"ml":true,"com.ml":true,"edu.ml":true,"gouv.ml":true,"gov.ml":true,"net.ml":true,"org.ml":true,"presse.ml":true,"*.mm":true,"mn":true,"gov.mn":true,"edu.mn":true,"org.mn":true,"mo":true,"com.mo":true,"net.mo":true,"org.mo":true,"edu.mo":true,"gov.mo":true,"mobi":true,"mp":true,"mq":true,"mr":true,"gov.mr":true,"ms":true,"com.ms":true,"edu.ms":true,"gov.ms":true,"net.ms":true,"org.ms":true,"mt":true,"com.mt":true,"edu.mt":true,"net.mt":true,"org.mt":true,"mu":true,"com.mu":true,"net.mu":true,"org.mu":true,"gov.mu":true,"ac.mu":true,"co.mu":true,"or.mu":true,"museum":true,"academy.museum":true,"agriculture.museum":true,"air.museum":true,"airguard.museum":true,"alabama.museum":true,"alaska.museum":true,"amber.museum":true,"ambulance.museum":true,"american.museum":true,"americana.museum":true,"americanantiques.museum":true,"americanart.museum":true,"amsterdam.museum":true,"and.museum":true,"annefrank.museum":true,"anthro.museum":true,"anthropology.museum":true,"antiques.museum":true,"aquarium.museum":true,"arboretum.museum":true,"archaeological.museum":true,"archaeology.museum":true,"architecture.museum":true,"art.museum":true,"artanddesign.museum":true,"artcenter.museum":true,"artdeco.museum":true,"arteducation.museum":true,"artgallery.museum":true,"arts.museum":true,"artsandcrafts.museum":true,"asmatart.museum":true,"assassination.museum":true,"assisi.museum":true,"association.museum":true,"astronomy.museum":true,"atlanta.museum":true,"austin.museum":true,"australia.museum":true,"automotive.museum":true,"aviation.museum":true,"axis.museum":true,"badajoz.museum":true,"baghdad.museum":true,"bahn.museum":true,"bale.museum":true,"baltimore.museum":true,"barcelona.museum":true,"baseball.museum":true,"basel.museum":true,"baths.museum":true,"bauern.museum":true,"beauxarts.museum":true,"beeldengeluid.museum":true,"bellevue.museum":true,"bergbau.museum":true,"berkeley.museum":true,"berlin.museum":true,"bern.museum":true,"bible.museum":true,"bilbao.museum":true,"bill.museum":true,"birdart.museum":true,"birthplace.museum":true,"bonn.museum":true,"boston.museum":true,"botanical.museum":true,"botanicalgarden.museum":true,"botanicgarden.museum":true,"botany.museum":true,"brandywinevalley.museum":true,"brasil.museum":true,"bristol.museum":true,"british.museum":true,"britishcolumbia.museum":true,"broadcast.museum":true,"brunel.museum":true,"brussel.museum":true,"brussels.museum":true,"bruxelles.museum":true,"building.museum":true,"burghof.museum":true,"bus.museum":true,"bushey.museum":true,"cadaques.museum":true,"california.museum":true,"cambridge.museum":true,"can.museum":true,"canada.museum":true,"capebreton.museum":true,"carrier.museum":true,"cartoonart.museum":true,"casadelamoneda.museum":true,"castle.museum":true,"castres.museum":true,"celtic.museum":true,"center.museum":true,"chattanooga.museum":true,"cheltenham.museum":true,"chesapeakebay.museum":true,"chicago.museum":true,"children.museum":true,"childrens.museum":true,"childrensgarden.museum":true,"chiropractic.museum":true,"chocolate.museum":true,"christiansburg.museum":true,"cincinnati.museum":true,"cinema.museum":true,"circus.museum":true,"civilisation.museum":true,"civilization.museum":true,"civilwar.museum":true,"clinton.museum":true,"clock.museum":true,"coal.museum":true,"coastaldefence.museum":true,"cody.museum":true,"coldwar.museum":true,"collection.museum":true,"colonialwilliamsburg.museum":true,"coloradoplateau.museum":true,"columbia.museum":true,"columbus.museum":true,"communication.museum":true,"communications.museum":true,"community.museum":true,"computer.museum":true,"computerhistory.museum":true,"xn--comunicaes-v6a2o.museum":true,"contemporary.museum":true,"contemporaryart.museum":true,"convent.museum":true,"copenhagen.museum":true,"corporation.museum":true,"xn--correios-e-telecomunicaes-ghc29a.museum":true,"corvette.museum":true,"costume.museum":true,"countryestate.museum":true,"county.museum":true,"crafts.museum":true,"cranbrook.museum":true,"creation.museum":true,"cultural.museum":true,"culturalcenter.museum":true,"culture.museum":true,"cyber.museum":true,"cymru.museum":true,"dali.museum":true,"dallas.museum":true,"database.museum":true,"ddr.museum":true,"decorativearts.museum":true,"delaware.museum":true,"delmenhorst.museum":true,"denmark.museum":true,"depot.museum":true,"design.museum":true,"detroit.museum":true,"dinosaur.museum":true,"discovery.museum":true,"dolls.museum":true,"donostia.museum":true,"durham.museum":true,"eastafrica.museum":true,"eastcoast.museum":true,"education.museum":true,"educational.museum":true,"egyptian.museum":true,"eisenbahn.museum":true,"elburg.museum":true,"elvendrell.museum":true,"embroidery.museum":true,"encyclopedic.museum":true,"england.museum":true,"entomology.museum":true,"environment.museum":true,"environmentalconservation.museum":true,"epilepsy.museum":true,"essex.museum":true,"estate.museum":true,"ethnology.museum":true,"exeter.museum":true,"exhibition.museum":true,"family.museum":true,"farm.museum":true,"farmequipment.museum":true,"farmers.museum":true,"farmstead.museum":true,"field.museum":true,"figueres.museum":true,"filatelia.museum":true,"film.museum":true,"fineart.museum":true,"finearts.museum":true,"finland.museum":true,"flanders.museum":true,"florida.museum":true,"force.museum":true,"fortmissoula.museum":true,"fortworth.museum":true,"foundation.museum":true,"francaise.museum":true,"frankfurt.museum":true,"franziskaner.museum":true,"freemasonry.museum":true,"freiburg.museum":true,"fribourg.museum":true,"frog.museum":true,"fundacio.museum":true,"furniture.museum":true,"gallery.museum":true,"garden.museum":true,"gateway.museum":true,"geelvinck.museum":true,"gemological.museum":true,"geology.museum":true,"georgia.museum":true,"giessen.museum":true,"glas.museum":true,"glass.museum":true,"gorge.museum":true,"grandrapids.museum":true,"graz.museum":true,"guernsey.museum":true,"halloffame.museum":true,"hamburg.museum":true,"handson.museum":true,"harvestcelebration.museum":true,"hawaii.museum":true,"health.museum":true,"heimatunduhren.museum":true,"hellas.museum":true,"helsinki.museum":true,"hembygdsforbund.museum":true,"heritage.museum":true,"histoire.museum":true,"historical.museum":true,"historicalsociety.museum":true,"historichouses.museum":true,"historisch.museum":true,"historisches.museum":true,"history.museum":true,"historyofscience.museum":true,"horology.museum":true,"house.museum":true,"humanities.museum":true,"illustration.museum":true,"imageandsound.museum":true,"indian.museum":true,"indiana.museum":true,"indianapolis.museum":true,"indianmarket.museum":true,"intelligence.museum":true,"interactive.museum":true,"iraq.museum":true,"iron.museum":true,"isleofman.museum":true,"jamison.museum":true,"jefferson.museum":true,"jerusalem.museum":true,"jewelry.museum":true,"jewish.museum":true,"jewishart.museum":true,"jfk.museum":true,"journalism.museum":true,"judaica.museum":true,"judygarland.museum":true,"juedisches.museum":true,"juif.museum":true,"karate.museum":true,"karikatur.museum":true,"kids.museum":true,"koebenhavn.museum":true,"koeln.museum":true,"kunst.museum":true,"kunstsammlung.museum":true,"kunstunddesign.museum":true,"labor.museum":true,"labour.museum":true,"lajolla.museum":true,"lancashire.museum":true,"landes.museum":true,"lans.museum":true,"xn--lns-qla.museum":true,"larsson.museum":true,"lewismiller.museum":true,"lincoln.museum":true,"linz.museum":true,"living.museum":true,"livinghistory.museum":true,"localhistory.museum":true,"london.museum":true,"losangeles.museum":true,"louvre.museum":true,"loyalist.museum":true,"lucerne.museum":true,"luxembourg.museum":true,"luzern.museum":true,"mad.museum":true,"madrid.museum":true,"mallorca.museum":true,"manchester.museum":true,"mansion.museum":true,"mansions.museum":true,"manx.museum":true,"marburg.museum":true,"maritime.museum":true,"maritimo.museum":true,"maryland.museum":true,"marylhurst.museum":true,"media.museum":true,"medical.museum":true,"medizinhistorisches.museum":true,"meeres.museum":true,"memorial.museum":true,"mesaverde.museum":true,"michigan.museum":true,"midatlantic.museum":true,"military.museum":true,"mill.museum":true,"miners.museum":true,"mining.museum":true,"minnesota.museum":true,"missile.museum":true,"missoula.museum":true,"modern.museum":true,"moma.museum":true,"money.museum":true,"monmouth.museum":true,"monticello.museum":true,"montreal.museum":true,"moscow.museum":true,"motorcycle.museum":true,"muenchen.museum":true,"muenster.museum":true,"mulhouse.museum":true,"muncie.museum":true,"museet.museum":true,"museumcenter.museum":true,"museumvereniging.museum":true,"music.museum":true,"national.museum":true,"nationalfirearms.museum":true,"nationalheritage.museum":true,"nativeamerican.museum":true,"naturalhistory.museum":true,"naturalhistorymuseum.museum":true,"naturalsciences.museum":true,"nature.museum":true,"naturhistorisches.museum":true,"natuurwetenschappen.museum":true,"naumburg.museum":true,"naval.museum":true,"nebraska.museum":true,"neues.museum":true,"newhampshire.museum":true,"newjersey.museum":true,"newmexico.museum":true,"newport.museum":true,"newspaper.museum":true,"newyork.museum":true,"niepce.museum":true,"norfolk.museum":true,"north.museum":true,"nrw.museum":true,"nuernberg.museum":true,"nuremberg.museum":true,"nyc.museum":true,"nyny.museum":true,"oceanographic.museum":true,"oceanographique.museum":true,"omaha.museum":true,"online.museum":true,"ontario.museum":true,"openair.museum":true,"oregon.museum":true,"oregontrail.museum":true,"otago.museum":true,"oxford.museum":true,"pacific.museum":true,"paderborn.museum":true,"palace.museum":true,"paleo.museum":true,"palmsprings.museum":true,"panama.museum":true,"paris.museum":true,"pasadena.museum":true,"pharmacy.museum":true,"philadelphia.museum":true,"philadelphiaarea.museum":true,"philately.museum":true,"phoenix.museum":true,"photography.museum":true,"pilots.museum":true,"pittsburgh.museum":true,"planetarium.museum":true,"plantation.museum":true,"plants.museum":true,"plaza.museum":true,"portal.museum":true,"portland.museum":true,"portlligat.museum":true,"posts-and-telecommunications.museum":true,"preservation.museum":true,"presidio.museum":true,"press.museum":true,"project.museum":true,"public.museum":true,"pubol.museum":true,"quebec.museum":true,"railroad.museum":true,"railway.museum":true,"research.museum":true,"resistance.museum":true,"riodejaneiro.museum":true,"rochester.museum":true,"rockart.museum":true,"roma.museum":true,"russia.museum":true,"saintlouis.museum":true,"salem.museum":true,"salvadordali.museum":true,"salzburg.museum":true,"sandiego.museum":true,"sanfrancisco.museum":true,"santabarbara.museum":true,"santacruz.museum":true,"santafe.museum":true,"saskatchewan.museum":true,"satx.museum":true,"savannahga.museum":true,"schlesisches.museum":true,"schoenbrunn.museum":true,"schokoladen.museum":true,"school.museum":true,"schweiz.museum":true,"science.museum":true,"scienceandhistory.museum":true,"scienceandindustry.museum":true,"sciencecenter.museum":true,"sciencecenters.museum":true,"science-fiction.museum":true,"sciencehistory.museum":true,"sciences.museum":true,"sciencesnaturelles.museum":true,"scotland.museum":true,"seaport.museum":true,"settlement.museum":true,"settlers.museum":true,"shell.museum":true,"sherbrooke.museum":true,"sibenik.museum":true,"silk.museum":true,"ski.museum":true,"skole.museum":true,"society.museum":true,"sologne.museum":true,"soundandvision.museum":true,"southcarolina.museum":true,"southwest.museum":true,"space.museum":true,"spy.museum":true,"square.museum":true,"stadt.museum":true,"stalbans.museum":true,"starnberg.museum":true,"state.museum":true,"stateofdelaware.museum":true,"station.museum":true,"steam.museum":true,"steiermark.museum":true,"stjohn.museum":true,"stockholm.museum":true,"stpetersburg.museum":true,"stuttgart.museum":true,"suisse.museum":true,"surgeonshall.museum":true,"surrey.museum":true,"svizzera.museum":true,"sweden.museum":true,"sydney.museum":true,"tank.museum":true,"tcm.museum":true,"technology.museum":true,"telekommunikation.museum":true,"television.museum":true,"texas.museum":true,"textile.museum":true,"theater.museum":true,"time.museum":true,"timekeeping.museum":true,"topology.museum":true,"torino.museum":true,"touch.museum":true,"town.museum":true,"transport.museum":true,"tree.museum":true,"trolley.museum":true,"trust.museum":true,"trustee.museum":true,"uhren.museum":true,"ulm.museum":true,"undersea.museum":true,"university.museum":true,"usa.museum":true,"usantiques.museum":true,"usarts.museum":true,"uscountryestate.museum":true,"usculture.museum":true,"usdecorativearts.museum":true,"usgarden.museum":true,"ushistory.museum":true,"ushuaia.museum":true,"uslivinghistory.museum":true,"utah.museum":true,"uvic.museum":true,"valley.museum":true,"vantaa.museum":true,"versailles.museum":true,"viking.museum":true,"village.museum":true,"virginia.museum":true,"virtual.museum":true,"virtuel.museum":true,"vlaanderen.museum":true,"volkenkunde.museum":true,"wales.museum":true,"wallonie.museum":true,"war.museum":true,"washingtondc.museum":true,"watchandclock.museum":true,"watch-and-clock.museum":true,"western.museum":true,"westfalen.museum":true,"whaling.museum":true,"wildlife.museum":true,"williamsburg.museum":true,"windmill.museum":true,"workshop.museum":true,"york.museum":true,"yorkshire.museum":true,"yosemite.museum":true,"youth.museum":true,"zoological.museum":true,"zoology.museum":true,"xn--9dbhblg6di.museum":true,"xn--h1aegh.museum":true,"mv":true,"aero.mv":true,"biz.mv":true,"com.mv":true,"coop.mv":true,"edu.mv":true,"gov.mv":true,"info.mv":true,"int.mv":true,"mil.mv":true,"museum.mv":true,"name.mv":true,"net.mv":true,"org.mv":true,"pro.mv":true,"mw":true,"ac.mw":true,"biz.mw":true,"co.mw":true,"com.mw":true,"coop.mw":true,"edu.mw":true,"gov.mw":true,"int.mw":true,"museum.mw":true,"net.mw":true,"org.mw":true,"mx":true,"com.mx":true,"org.mx":true,"gob.mx":true,"edu.mx":true,"net.mx":true,"my":true,"com.my":true,"net.my":true,"org.my":true,"gov.my":true,"edu.my":true,"mil.my":true,"name.my":true,"*.mz":true,"teledata.mz":false,"na":true,"info.na":true,"pro.na":true,"name.na":true,"school.na":true,"or.na":true,"dr.na":true,"us.na":true,"mx.na":true,"ca.na":true,"in.na":true,"cc.na":true,"tv.na":true,"ws.na":true,"mobi.na":true,"co.na":true,"com.na":true,"org.na":true,"name":true,"nc":true,"asso.nc":true,"ne":true,"net":true,"nf":true,"com.nf":true,"net.nf":true,"per.nf":true,"rec.nf":true,"web.nf":true,"arts.nf":true,"firm.nf":true,"info.nf":true,"other.nf":true,"store.nf":true,"ng":true,"com.ng":true,"edu.ng":true,"name.ng":true,"net.ng":true,"org.ng":true,"sch.ng":true,"gov.ng":true,"mil.ng":true,"mobi.ng":true,"*.ni":true,"nl":true,"bv.nl":true,"no":true,"fhs.no":true,"vgs.no":true,"fylkesbibl.no":true,"folkebibl.no":true,"museum.no":true,"idrett.no":true,"priv.no":true,"mil.no":true,"stat.no":true,"dep.no":true,"kommune.no":true,"herad.no":true,"aa.no":true,"ah.no":true,"bu.no":true,"fm.no":true,"hl.no":true,"hm.no":true,"jan-mayen.no":true,"mr.no":true,"nl.no":true,"nt.no":true,"of.no":true,"ol.no":true,"oslo.no":true,"rl.no":true,"sf.no":true,"st.no":true,"svalbard.no":true,"tm.no":true,"tr.no":true,"va.no":true,"vf.no":true,"gs.aa.no":true,"gs.ah.no":true,"gs.bu.no":true,"gs.fm.no":true,"gs.hl.no":true,"gs.hm.no":true,"gs.jan-mayen.no":true,"gs.mr.no":true,"gs.nl.no":true,"gs.nt.no":true,"gs.of.no":true,"gs.ol.no":true,"gs.oslo.no":true,"gs.rl.no":true,"gs.sf.no":true,"gs.st.no":true,"gs.svalbard.no":true,"gs.tm.no":true,"gs.tr.no":true,"gs.va.no":true,"gs.vf.no":true,"akrehamn.no":true,"xn--krehamn-dxa.no":true,"algard.no":true,"xn--lgrd-poac.no":true,"arna.no":true,"brumunddal.no":true,"bryne.no":true,"bronnoysund.no":true,"xn--brnnysund-m8ac.no":true,"drobak.no":true,"xn--drbak-wua.no":true,"egersund.no":true,"fetsund.no":true,"floro.no":true,"xn--flor-jra.no":true,"fredrikstad.no":true,"hokksund.no":true,"honefoss.no":true,"xn--hnefoss-q1a.no":true,"jessheim.no":true,"jorpeland.no":true,"xn--jrpeland-54a.no":true,"kirkenes.no":true,"kopervik.no":true,"krokstadelva.no":true,"langevag.no":true,"xn--langevg-jxa.no":true,"leirvik.no":true,"mjondalen.no":true,"xn--mjndalen-64a.no":true,"mo-i-rana.no":true,"mosjoen.no":true,"xn--mosjen-eya.no":true,"nesoddtangen.no":true,"orkanger.no":true,"osoyro.no":true,"xn--osyro-wua.no":true,"raholt.no":true,"xn--rholt-mra.no":true,"sandnessjoen.no":true,"xn--sandnessjen-ogb.no":true,"skedsmokorset.no":true,"slattum.no":true,"spjelkavik.no":true,"stathelle.no":true,"stavern.no":true,"stjordalshalsen.no":true,"xn--stjrdalshalsen-sqb.no":true,"tananger.no":true,"tranby.no":true,"vossevangen.no":true,"afjord.no":true,"xn--fjord-lra.no":true,"agdenes.no":true,"al.no":true,"xn--l-1fa.no":true,"alesund.no":true,"xn--lesund-hua.no":true,"alstahaug.no":true,"alta.no":true,"xn--lt-liac.no":true,"alaheadju.no":true,"xn--laheadju-7ya.no":true,"alvdal.no":true,"amli.no":true,"xn--mli-tla.no":true,"amot.no":true,"xn--mot-tla.no":true,"andebu.no":true,"andoy.no":true,"xn--andy-ira.no":true,"andasuolo.no":true,"ardal.no":true,"xn--rdal-poa.no":true,"aremark.no":true,"arendal.no":true,"xn--s-1fa.no":true,"aseral.no":true,"xn--seral-lra.no":true,"asker.no":true,"askim.no":true,"askvoll.no":true,"askoy.no":true,"xn--asky-ira.no":true,"asnes.no":true,"xn--snes-poa.no":true,"audnedaln.no":true,"aukra.no":true,"aure.no":true,"aurland.no":true,"aurskog-holand.no":true,"xn--aurskog-hland-jnb.no":true,"austevoll.no":true,"austrheim.no":true,"averoy.no":true,"xn--avery-yua.no":true,"balestrand.no":true,"ballangen.no":true,"balat.no":true,"xn--blt-elab.no":true,"balsfjord.no":true,"bahccavuotna.no":true,"xn--bhccavuotna-k7a.no":true,"bamble.no":true,"bardu.no":true,"beardu.no":true,"beiarn.no":true,"bajddar.no":true,"xn--bjddar-pta.no":true,"baidar.no":true,"xn--bidr-5nac.no":true,"berg.no":true,"bergen.no":true,"berlevag.no":true,"xn--berlevg-jxa.no":true,"bearalvahki.no":true,"xn--bearalvhki-y4a.no":true,"bindal.no":true,"birkenes.no":true,"bjarkoy.no":true,"xn--bjarky-fya.no":true,"bjerkreim.no":true,"bjugn.no":true,"bodo.no":true,"xn--bod-2na.no":true,"badaddja.no":true,"xn--bdddj-mrabd.no":true,"budejju.no":true,"bokn.no":true,"bremanger.no":true,"bronnoy.no":true,"xn--brnny-wuac.no":true,"bygland.no":true,"bykle.no":true,"barum.no":true,"xn--brum-voa.no":true,"bo.telemark.no":true,"xn--b-5ga.telemark.no":true,"bo.nordland.no":true,"xn--b-5ga.nordland.no":true,"bievat.no":true,"xn--bievt-0qa.no":true,"bomlo.no":true,"xn--bmlo-gra.no":true,"batsfjord.no":true,"xn--btsfjord-9za.no":true,"bahcavuotna.no":true,"xn--bhcavuotna-s4a.no":true,"dovre.no":true,"drammen.no":true,"drangedal.no":true,"dyroy.no":true,"xn--dyry-ira.no":true,"donna.no":true,"xn--dnna-gra.no":true,"eid.no":true,"eidfjord.no":true,"eidsberg.no":true,"eidskog.no":true,"eidsvoll.no":true,"eigersund.no":true,"elverum.no":true,"enebakk.no":true,"engerdal.no":true,"etne.no":true,"etnedal.no":true,"evenes.no":true,"evenassi.no":true,"xn--eveni-0qa01ga.no":true,"evje-og-hornnes.no":true,"farsund.no":true,"fauske.no":true,"fuossko.no":true,"fuoisku.no":true,"fedje.no":true,"fet.no":true,"finnoy.no":true,"xn--finny-yua.no":true,"fitjar.no":true,"fjaler.no":true,"fjell.no":true,"flakstad.no":true,"flatanger.no":true,"flekkefjord.no":true,"flesberg.no":true,"flora.no":true,"fla.no":true,"xn--fl-zia.no":true,"folldal.no":true,"forsand.no":true,"fosnes.no":true,"frei.no":true,"frogn.no":true,"froland.no":true,"frosta.no":true,"frana.no":true,"xn--frna-woa.no":true,"froya.no":true,"xn--frya-hra.no":true,"fusa.no":true,"fyresdal.no":true,"forde.no":true,"xn--frde-gra.no":true,"gamvik.no":true,"gangaviika.no":true,"xn--ggaviika-8ya47h.no":true,"gaular.no":true,"gausdal.no":true,"gildeskal.no":true,"xn--gildeskl-g0a.no":true,"giske.no":true,"gjemnes.no":true,"gjerdrum.no":true,"gjerstad.no":true,"gjesdal.no":true,"gjovik.no":true,"xn--gjvik-wua.no":true,"gloppen.no":true,"gol.no":true,"gran.no":true,"grane.no":true,"granvin.no":true,"gratangen.no":true,"grimstad.no":true,"grong.no":true,"kraanghke.no":true,"xn--kranghke-b0a.no":true,"grue.no":true,"gulen.no":true,"hadsel.no":true,"halden.no":true,"halsa.no":true,"hamar.no":true,"hamaroy.no":true,"habmer.no":true,"xn--hbmer-xqa.no":true,"hapmir.no":true,"xn--hpmir-xqa.no":true,"hammerfest.no":true,"hammarfeasta.no":true,"xn--hmmrfeasta-s4ac.no":true,"haram.no":true,"hareid.no":true,"harstad.no":true,"hasvik.no":true,"aknoluokta.no":true,"xn--koluokta-7ya57h.no":true,"hattfjelldal.no":true,"aarborte.no":true,"haugesund.no":true,"hemne.no":true,"hemnes.no":true,"hemsedal.no":true,"heroy.more-og-romsdal.no":true,"xn--hery-ira.xn--mre-og-romsdal-qqb.no":true,"heroy.nordland.no":true,"xn--hery-ira.nordland.no":true,"hitra.no":true,"hjartdal.no":true,"hjelmeland.no":true,"hobol.no":true,"xn--hobl-ira.no":true,"hof.no":true,"hol.no":true,"hole.no":true,"holmestrand.no":true,"holtalen.no":true,"xn--holtlen-hxa.no":true,"hornindal.no":true,"horten.no":true,"hurdal.no":true,"hurum.no":true,"hvaler.no":true,"hyllestad.no":true,"hagebostad.no":true,"xn--hgebostad-g3a.no":true,"hoyanger.no":true,"xn--hyanger-q1a.no":true,"hoylandet.no":true,"xn--hylandet-54a.no":true,"ha.no":true,"xn--h-2fa.no":true,"ibestad.no":true,"inderoy.no":true,"xn--indery-fya.no":true,"iveland.no":true,"jevnaker.no":true,"jondal.no":true,"jolster.no":true,"xn--jlster-bya.no":true,"karasjok.no":true,"karasjohka.no":true,"xn--krjohka-hwab49j.no":true,"karlsoy.no":true,"galsa.no":true,"xn--gls-elac.no":true,"karmoy.no":true,"xn--karmy-yua.no":true,"kautokeino.no":true,"guovdageaidnu.no":true,"klepp.no":true,"klabu.no":true,"xn--klbu-woa.no":true,"kongsberg.no":true,"kongsvinger.no":true,"kragero.no":true,"xn--krager-gya.no":true,"kristiansand.no":true,"kristiansund.no":true,"krodsherad.no":true,"xn--krdsherad-m8a.no":true,"kvalsund.no":true,"rahkkeravju.no":true,"xn--rhkkervju-01af.no":true,"kvam.no":true,"kvinesdal.no":true,"kvinnherad.no":true,"kviteseid.no":true,"kvitsoy.no":true,"xn--kvitsy-fya.no":true,"kvafjord.no":true,"xn--kvfjord-nxa.no":true,"giehtavuoatna.no":true,"kvanangen.no":true,"xn--kvnangen-k0a.no":true,"navuotna.no":true,"xn--nvuotna-hwa.no":true,"kafjord.no":true,"xn--kfjord-iua.no":true,"gaivuotna.no":true,"xn--givuotna-8ya.no":true,"larvik.no":true,"lavangen.no":true,"lavagis.no":true,"loabat.no":true,"xn--loabt-0qa.no":true,"lebesby.no":true,"davvesiida.no":true,"leikanger.no":true,"leirfjord.no":true,"leka.no":true,"leksvik.no":true,"lenvik.no":true,"leangaviika.no":true,"xn--leagaviika-52b.no":true,"lesja.no":true,"levanger.no":true,"lier.no":true,"lierne.no":true,"lillehammer.no":true,"lillesand.no":true,"lindesnes.no":true,"lindas.no":true,"xn--linds-pra.no":true,"lom.no":true,"loppa.no":true,"lahppi.no":true,"xn--lhppi-xqa.no":true,"lund.no":true,"lunner.no":true,"luroy.no":true,"xn--lury-ira.no":true,"luster.no":true,"lyngdal.no":true,"lyngen.no":true,"ivgu.no":true,"lardal.no":true,"lerdal.no":true,"xn--lrdal-sra.no":true,"lodingen.no":true,"xn--ldingen-q1a.no":true,"lorenskog.no":true,"xn--lrenskog-54a.no":true,"loten.no":true,"xn--lten-gra.no":true,"malvik.no":true,"masoy.no":true,"xn--msy-ula0h.no":true,"muosat.no":true,"xn--muost-0qa.no":true,"mandal.no":true,"marker.no":true,"marnardal.no":true,"masfjorden.no":true,"meland.no":true,"meldal.no":true,"melhus.no":true,"meloy.no":true,"xn--mely-ira.no":true,"meraker.no":true,"xn--merker-kua.no":true,"moareke.no":true,"xn--moreke-jua.no":true,"midsund.no":true,"midtre-gauldal.no":true,"modalen.no":true,"modum.no":true,"molde.no":true,"moskenes.no":true,"moss.no":true,"mosvik.no":true,"malselv.no":true,"xn--mlselv-iua.no":true,"malatvuopmi.no":true,"xn--mlatvuopmi-s4a.no":true,"namdalseid.no":true,"aejrie.no":true,"namsos.no":true,"namsskogan.no":true,"naamesjevuemie.no":true,"xn--nmesjevuemie-tcba.no":true,"laakesvuemie.no":true,"nannestad.no":true,"narvik.no":true,"narviika.no":true,"naustdal.no":true,"nedre-eiker.no":true,"nes.akershus.no":true,"nes.buskerud.no":true,"nesna.no":true,"nesodden.no":true,"nesseby.no":true,"unjarga.no":true,"xn--unjrga-rta.no":true,"nesset.no":true,"nissedal.no":true,"nittedal.no":true,"nord-aurdal.no":true,"nord-fron.no":true,"nord-odal.no":true,"norddal.no":true,"nordkapp.no":true,"davvenjarga.no":true,"xn--davvenjrga-y4a.no":true,"nordre-land.no":true,"nordreisa.no":true,"raisa.no":true,"xn--risa-5na.no":true,"nore-og-uvdal.no":true,"notodden.no":true,"naroy.no":true,"xn--nry-yla5g.no":true,"notteroy.no":true,"xn--nttery-byae.no":true,"odda.no":true,"oksnes.no":true,"xn--ksnes-uua.no":true,"oppdal.no":true,"oppegard.no":true,"xn--oppegrd-ixa.no":true,"orkdal.no":true,"orland.no":true,"xn--rland-uua.no":true,"orskog.no":true,"xn--rskog-uua.no":true,"orsta.no":true,"xn--rsta-fra.no":true,"os.hedmark.no":true,"os.hordaland.no":true,"osen.no":true,"osteroy.no":true,"xn--ostery-fya.no":true,"ostre-toten.no":true,"xn--stre-toten-zcb.no":true,"overhalla.no":true,"ovre-eiker.no":true,"xn--vre-eiker-k8a.no":true,"oyer.no":true,"xn--yer-zna.no":true,"oygarden.no":true,"xn--ygarden-p1a.no":true,"oystre-slidre.no":true,"xn--ystre-slidre-ujb.no":true,"porsanger.no":true,"porsangu.no":true,"xn--porsgu-sta26f.no":true,"porsgrunn.no":true,"radoy.no":true,"xn--rady-ira.no":true,"rakkestad.no":true,"rana.no":true,"ruovat.no":true,"randaberg.no":true,"rauma.no":true,"rendalen.no":true,"rennebu.no":true,"rennesoy.no":true,"xn--rennesy-v1a.no":true,"rindal.no":true,"ringebu.no":true,"ringerike.no":true,"ringsaker.no":true,"rissa.no":true,"risor.no":true,"xn--risr-ira.no":true,"roan.no":true,"rollag.no":true,"rygge.no":true,"ralingen.no":true,"xn--rlingen-mxa.no":true,"rodoy.no":true,"xn--rdy-0nab.no":true,"romskog.no":true,"xn--rmskog-bya.no":true,"roros.no":true,"xn--rros-gra.no":true,"rost.no":true,"xn--rst-0na.no":true,"royken.no":true,"xn--ryken-vua.no":true,"royrvik.no":true,"xn--ryrvik-bya.no":true,"rade.no":true,"xn--rde-ula.no":true,"salangen.no":true,"siellak.no":true,"saltdal.no":true,"salat.no":true,"xn--slt-elab.no":true,"xn--slat-5na.no":true,"samnanger.no":true,"sande.more-og-romsdal.no":true,"sande.xn--mre-og-romsdal-qqb.no":true,"sande.vestfold.no":true,"sandefjord.no":true,"sandnes.no":true,"sandoy.no":true,"xn--sandy-yua.no":true,"sarpsborg.no":true,"sauda.no":true,"sauherad.no":true,"sel.no":true,"selbu.no":true,"selje.no":true,"seljord.no":true,"sigdal.no":true,"siljan.no":true,"sirdal.no":true,"skaun.no":true,"skedsmo.no":true,"ski.no":true,"skien.no":true,"skiptvet.no":true,"skjervoy.no":true,"xn--skjervy-v1a.no":true,"skierva.no":true,"xn--skierv-uta.no":true,"skjak.no":true,"xn--skjk-soa.no":true,"skodje.no":true,"skanland.no":true,"xn--sknland-fxa.no":true,"skanit.no":true,"xn--sknit-yqa.no":true,"smola.no":true,"xn--smla-hra.no":true,"snillfjord.no":true,"snasa.no":true,"xn--snsa-roa.no":true,"snoasa.no":true,"snaase.no":true,"xn--snase-nra.no":true,"sogndal.no":true,"sokndal.no":true,"sola.no":true,"solund.no":true,"songdalen.no":true,"sortland.no":true,"spydeberg.no":true,"stange.no":true,"stavanger.no":true,"steigen.no":true,"steinkjer.no":true,"stjordal.no":true,"xn--stjrdal-s1a.no":true,"stokke.no":true,"stor-elvdal.no":true,"stord.no":true,"stordal.no":true,"storfjord.no":true,"omasvuotna.no":true,"strand.no":true,"stranda.no":true,"stryn.no":true,"sula.no":true,"suldal.no":true,"sund.no":true,"sunndal.no":true,"surnadal.no":true,"sveio.no":true,"svelvik.no":true,"sykkylven.no":true,"sogne.no":true,"xn--sgne-gra.no":true,"somna.no":true,"xn--smna-gra.no":true,"sondre-land.no":true,"xn--sndre-land-0cb.no":true,"sor-aurdal.no":true,"xn--sr-aurdal-l8a.no":true,"sor-fron.no":true,"xn--sr-fron-q1a.no":true,"sor-odal.no":true,"xn--sr-odal-q1a.no":true,"sor-varanger.no":true,"xn--sr-varanger-ggb.no":true,"matta-varjjat.no":true,"xn--mtta-vrjjat-k7af.no":true,"sorfold.no":true,"xn--srfold-bya.no":true,"sorreisa.no":true,"xn--srreisa-q1a.no":true,"sorum.no":true,"xn--srum-gra.no":true,"tana.no":true,"deatnu.no":true,"time.no":true,"tingvoll.no":true,"tinn.no":true,"tjeldsund.no":true,"dielddanuorri.no":true,"tjome.no":true,"xn--tjme-hra.no":true,"tokke.no":true,"tolga.no":true,"torsken.no":true,"tranoy.no":true,"xn--trany-yua.no":true,"tromso.no":true,"xn--troms-zua.no":true,"tromsa.no":true,"romsa.no":true,"trondheim.no":true,"troandin.no":true,"trysil.no":true,"trana.no":true,"xn--trna-woa.no":true,"trogstad.no":true,"xn--trgstad-r1a.no":true,"tvedestrand.no":true,"tydal.no":true,"tynset.no":true,"tysfjord.no":true,"divtasvuodna.no":true,"divttasvuotna.no":true,"tysnes.no":true,"tysvar.no":true,"xn--tysvr-vra.no":true,"tonsberg.no":true,"xn--tnsberg-q1a.no":true,"ullensaker.no":true,"ullensvang.no":true,"ulvik.no":true,"utsira.no":true,"vadso.no":true,"xn--vads-jra.no":true,"cahcesuolo.no":true,"xn--hcesuolo-7ya35b.no":true,"vaksdal.no":true,"valle.no":true,"vang.no":true,"vanylven.no":true,"vardo.no":true,"xn--vard-jra.no":true,"varggat.no":true,"xn--vrggt-xqad.no":true,"vefsn.no":true,"vaapste.no":true,"vega.no":true,"vegarshei.no":true,"xn--vegrshei-c0a.no":true,"vennesla.no":true,"verdal.no":true,"verran.no":true,"vestby.no":true,"vestnes.no":true,"vestre-slidre.no":true,"vestre-toten.no":true,"vestvagoy.no":true,"xn--vestvgy-ixa6o.no":true,"vevelstad.no":true,"vik.no":true,"vikna.no":true,"vindafjord.no":true,"volda.no":true,"voss.no":true,"varoy.no":true,"xn--vry-yla5g.no":true,"vagan.no":true,"xn--vgan-qoa.no":true,"voagat.no":true,"vagsoy.no":true,"xn--vgsy-qoa0j.no":true,"vaga.no":true,"xn--vg-yiab.no":true,"valer.ostfold.no":true,"xn--vler-qoa.xn--stfold-9xa.no":true,"valer.hedmark.no":true,"xn--vler-qoa.hedmark.no":true,"*.np":true,"nr":true,"biz.nr":true,"info.nr":true,"gov.nr":true,"edu.nr":true,"org.nr":true,"net.nr":true,"com.nr":true,"nu":true,"nz":true,"ac.nz":true,"co.nz":true,"cri.nz":true,"geek.nz":true,"gen.nz":true,"govt.nz":true,"health.nz":true,"iwi.nz":true,"kiwi.nz":true,"maori.nz":true,"mil.nz":true,"xn--mori-qsa.nz":true,"net.nz":true,"org.nz":true,"parliament.nz":true,"school.nz":true,"om":true,"co.om":true,"com.om":true,"edu.om":true,"gov.om":true,"med.om":true,"museum.om":true,"net.om":true,"org.om":true,"pro.om":true,"org":true,"pa":true,"ac.pa":true,"gob.pa":true,"com.pa":true,"org.pa":true,"sld.pa":true,"edu.pa":true,"net.pa":true,"ing.pa":true,"abo.pa":true,"med.pa":true,"nom.pa":true,"pe":true,"edu.pe":true,"gob.pe":true,"nom.pe":true,"mil.pe":true,"org.pe":true,"com.pe":true,"net.pe":true,"pf":true,"com.pf":true,"org.pf":true,"edu.pf":true,"*.pg":true,"ph":true,"com.ph":true,"net.ph":true,"org.ph":true,"gov.ph":true,"edu.ph":true,"ngo.ph":true,"mil.ph":true,"i.ph":true,"pk":true,"com.pk":true,"net.pk":true,"edu.pk":true,"org.pk":true,"fam.pk":true,"biz.pk":true,"web.pk":true,"gov.pk":true,"gob.pk":true,"gok.pk":true,"gon.pk":true,"gop.pk":true,"gos.pk":true,"info.pk":true,"pl":true,"com.pl":true,"net.pl":true,"org.pl":true,"info.pl":true,"waw.pl":true,"gov.pl":true,"aid.pl":true,"agro.pl":true,"atm.pl":true,"auto.pl":true,"biz.pl":true,"edu.pl":true,"gmina.pl":true,"gsm.pl":true,"mail.pl":true,"miasta.pl":true,"media.pl":true,"mil.pl":true,"nieruchomosci.pl":true,"nom.pl":true,"pc.pl":true,"powiat.pl":true,"priv.pl":true,"realestate.pl":true,"rel.pl":true,"sex.pl":true,"shop.pl":true,"sklep.pl":true,"sos.pl":true,"szkola.pl":true,"targi.pl":true,"tm.pl":true,"tourism.pl":true,"travel.pl":true,"turystyka.pl":true,"uw.gov.pl":true,"um.gov.pl":true,"ug.gov.pl":true,"upow.gov.pl":true,"starostwo.gov.pl":true,"so.gov.pl":true,"sr.gov.pl":true,"po.gov.pl":true,"pa.gov.pl":true,"augustow.pl":true,"babia-gora.pl":true,"bedzin.pl":true,"beskidy.pl":true,"bialowieza.pl":true,"bialystok.pl":true,"bielawa.pl":true,"bieszczady.pl":true,"boleslawiec.pl":true,"bydgoszcz.pl":true,"bytom.pl":true,"cieszyn.pl":true,"czeladz.pl":true,"czest.pl":true,"dlugoleka.pl":true,"elblag.pl":true,"elk.pl":true,"glogow.pl":true,"gniezno.pl":true,"gorlice.pl":true,"grajewo.pl":true,"ilawa.pl":true,"jaworzno.pl":true,"jelenia-gora.pl":true,"jgora.pl":true,"kalisz.pl":true,"kazimierz-dolny.pl":true,"karpacz.pl":true,"kartuzy.pl":true,"kaszuby.pl":true,"katowice.pl":true,"kepno.pl":true,"ketrzyn.pl":true,"klodzko.pl":true,"kobierzyce.pl":true,"kolobrzeg.pl":true,"konin.pl":true,"konskowola.pl":true,"kutno.pl":true,"lapy.pl":true,"lebork.pl":true,"legnica.pl":true,"lezajsk.pl":true,"limanowa.pl":true,"lomza.pl":true,"lowicz.pl":true,"lubin.pl":true,"lukow.pl":true,"malbork.pl":true,"malopolska.pl":true,"mazowsze.pl":true,"mazury.pl":true,"mielec.pl":true,"mielno.pl":true,"mragowo.pl":true,"naklo.pl":true,"nowaruda.pl":true,"nysa.pl":true,"olawa.pl":true,"olecko.pl":true,"olkusz.pl":true,"olsztyn.pl":true,"opoczno.pl":true,"opole.pl":true,"ostroda.pl":true,"ostroleka.pl":true,"ostrowiec.pl":true,"ostrowwlkp.pl":true,"pila.pl":true,"pisz.pl":true,"podhale.pl":true,"podlasie.pl":true,"polkowice.pl":true,"pomorze.pl":true,"pomorskie.pl":true,"prochowice.pl":true,"pruszkow.pl":true,"przeworsk.pl":true,"pulawy.pl":true,"radom.pl":true,"rawa-maz.pl":true,"rybnik.pl":true,"rzeszow.pl":true,"sanok.pl":true,"sejny.pl":true,"slask.pl":true,"slupsk.pl":true,"sosnowiec.pl":true,"stalowa-wola.pl":true,"skoczow.pl":true,"starachowice.pl":true,"stargard.pl":true,"suwalki.pl":true,"swidnica.pl":true,"swiebodzin.pl":true,"swinoujscie.pl":true,"szczecin.pl":true,"szczytno.pl":true,"tarnobrzeg.pl":true,"tgory.pl":true,"turek.pl":true,"tychy.pl":true,"ustka.pl":true,"walbrzych.pl":true,"warmia.pl":true,"warszawa.pl":true,"wegrow.pl":true,"wielun.pl":true,"wlocl.pl":true,"wloclawek.pl":true,"wodzislaw.pl":true,"wolomin.pl":true,"wroclaw.pl":true,"zachpomor.pl":true,"zagan.pl":true,"zarow.pl":true,"zgora.pl":true,"zgorzelec.pl":true,"pm":true,"pn":true,"gov.pn":true,"co.pn":true,"org.pn":true,"edu.pn":true,"net.pn":true,"post":true,"pr":true,"com.pr":true,"net.pr":true,"org.pr":true,"gov.pr":true,"edu.pr":true,"isla.pr":true,"pro.pr":true,"biz.pr":true,"info.pr":true,"name.pr":true,"est.pr":true,"prof.pr":true,"ac.pr":true,"pro":true,"aca.pro":true,"bar.pro":true,"cpa.pro":true,"jur.pro":true,"law.pro":true,"med.pro":true,"eng.pro":true,"ps":true,"edu.ps":true,"gov.ps":true,"sec.ps":true,"plo.ps":true,"com.ps":true,"org.ps":true,"net.ps":true,"pt":true,"net.pt":true,"gov.pt":true,"org.pt":true,"edu.pt":true,"int.pt":true,"publ.pt":true,"com.pt":true,"nome.pt":true,"pw":true,"co.pw":true,"ne.pw":true,"or.pw":true,"ed.pw":true,"go.pw":true,"belau.pw":true,"py":true,"com.py":true,"coop.py":true,"edu.py":true,"gov.py":true,"mil.py":true,"net.py":true,"org.py":true,"qa":true,"com.qa":true,"edu.qa":true,"gov.qa":true,"mil.qa":true,"name.qa":true,"net.qa":true,"org.qa":true,"sch.qa":true,"re":true,"com.re":true,"asso.re":true,"nom.re":true,"ro":true,"com.ro":true,"org.ro":true,"tm.ro":true,"nt.ro":true,"nom.ro":true,"info.ro":true,"rec.ro":true,"arts.ro":true,"firm.ro":true,"store.ro":true,"www.ro":true,"rs":true,"co.rs":true,"org.rs":true,"edu.rs":true,"ac.rs":true,"gov.rs":true,"in.rs":true,"ru":true,"ac.ru":true,"com.ru":true,"edu.ru":true,"int.ru":true,"net.ru":true,"org.ru":true,"pp.ru":true,"adygeya.ru":true,"altai.ru":true,"amur.ru":true,"arkhangelsk.ru":true,"astrakhan.ru":true,"bashkiria.ru":true,"belgorod.ru":true,"bir.ru":true,"bryansk.ru":true,"buryatia.ru":true,"cbg.ru":true,"chel.ru":true,"chelyabinsk.ru":true,"chita.ru":true,"chukotka.ru":true,"chuvashia.ru":true,"dagestan.ru":true,"dudinka.ru":true,"e-burg.ru":true,"grozny.ru":true,"irkutsk.ru":true,"ivanovo.ru":true,"izhevsk.ru":true,"jar.ru":true,"joshkar-ola.ru":true,"kalmykia.ru":true,"kaluga.ru":true,"kamchatka.ru":true,"karelia.ru":true,"kazan.ru":true,"kchr.ru":true,"kemerovo.ru":true,"khabarovsk.ru":true,"khakassia.ru":true,"khv.ru":true,"kirov.ru":true,"koenig.ru":true,"komi.ru":true,"kostroma.ru":true,"krasnoyarsk.ru":true,"kuban.ru":true,"kurgan.ru":true,"kursk.ru":true,"lipetsk.ru":true,"magadan.ru":true,"mari.ru":true,"mari-el.ru":true,"marine.ru":true,"mordovia.ru":true,"msk.ru":true,"murmansk.ru":true,"nalchik.ru":true,"nnov.ru":true,"nov.ru":true,"novosibirsk.ru":true,"nsk.ru":true,"omsk.ru":true,"orenburg.ru":true,"oryol.ru":true,"palana.ru":true,"penza.ru":true,"perm.ru":true,"ptz.ru":true,"rnd.ru":true,"ryazan.ru":true,"sakhalin.ru":true,"samara.ru":true,"saratov.ru":true,"simbirsk.ru":true,"smolensk.ru":true,"spb.ru":true,"stavropol.ru":true,"stv.ru":true,"surgut.ru":true,"tambov.ru":true,"tatarstan.ru":true,"tom.ru":true,"tomsk.ru":true,"tsaritsyn.ru":true,"tsk.ru":true,"tula.ru":true,"tuva.ru":true,"tver.ru":true,"tyumen.ru":true,"udm.ru":true,"udmurtia.ru":true,"ulan-ude.ru":true,"vladikavkaz.ru":true,"vladimir.ru":true,"vladivostok.ru":true,"volgograd.ru":true,"vologda.ru":true,"voronezh.ru":true,"vrn.ru":true,"vyatka.ru":true,"yakutia.ru":true,"yamal.ru":true,"yaroslavl.ru":true,"yekaterinburg.ru":true,"yuzhno-sakhalinsk.ru":true,"amursk.ru":true,"baikal.ru":true,"cmw.ru":true,"fareast.ru":true,"jamal.ru":true,"kms.ru":true,"k-uralsk.ru":true,"kustanai.ru":true,"kuzbass.ru":true,"magnitka.ru":true,"mytis.ru":true,"nakhodka.ru":true,"nkz.ru":true,"norilsk.ru":true,"oskol.ru":true,"pyatigorsk.ru":true,"rubtsovsk.ru":true,"snz.ru":true,"syzran.ru":true,"vdonsk.ru":true,"zgrad.ru":true,"gov.ru":true,"mil.ru":true,"test.ru":true,"rw":true,"gov.rw":true,"net.rw":true,"edu.rw":true,"ac.rw":true,"com.rw":true,"co.rw":true,"int.rw":true,"mil.rw":true,"gouv.rw":true,"sa":true,"com.sa":true,"net.sa":true,"org.sa":true,"gov.sa":true,"med.sa":true,"pub.sa":true,"edu.sa":true,"sch.sa":true,"sb":true,"com.sb":true,"edu.sb":true,"gov.sb":true,"net.sb":true,"org.sb":true,"sc":true,"com.sc":true,"gov.sc":true,"net.sc":true,"org.sc":true,"edu.sc":true,"sd":true,"com.sd":true,"net.sd":true,"org.sd":true,"edu.sd":true,"med.sd":true,"tv.sd":true,"gov.sd":true,"info.sd":true,"se":true,"a.se":true,"ac.se":true,"b.se":true,"bd.se":true,"brand.se":true,"c.se":true,"d.se":true,"e.se":true,"f.se":true,"fh.se":true,"fhsk.se":true,"fhv.se":true,"g.se":true,"h.se":true,"i.se":true,"k.se":true,"komforb.se":true,"kommunalforbund.se":true,"komvux.se":true,"l.se":true,"lanbib.se":true,"m.se":true,"n.se":true,"naturbruksgymn.se":true,"o.se":true,"org.se":true,"p.se":true,"parti.se":true,"pp.se":true,"press.se":true,"r.se":true,"s.se":true,"t.se":true,"tm.se":true,"u.se":true,"w.se":true,"x.se":true,"y.se":true,"z.se":true,"sg":true,"com.sg":true,"net.sg":true,"org.sg":true,"gov.sg":true,"edu.sg":true,"per.sg":true,"sh":true,"com.sh":true,"net.sh":true,"gov.sh":true,"org.sh":true,"mil.sh":true,"si":true,"sj":true,"sk":true,"sl":true,"com.sl":true,"net.sl":true,"edu.sl":true,"gov.sl":true,"org.sl":true,"sm":true,"sn":true,"art.sn":true,"com.sn":true,"edu.sn":true,"gouv.sn":true,"org.sn":true,"perso.sn":true,"univ.sn":true,"so":true,"com.so":true,"net.so":true,"org.so":true,"sr":true,"st":true,"co.st":true,"com.st":true,"consulado.st":true,"edu.st":true,"embaixada.st":true,"gov.st":true,"mil.st":true,"net.st":true,"org.st":true,"principe.st":true,"saotome.st":true,"store.st":true,"su":true,"adygeya.su":true,"arkhangelsk.su":true,"balashov.su":true,"bashkiria.su":true,"bryansk.su":true,"dagestan.su":true,"grozny.su":true,"ivanovo.su":true,"kalmykia.su":true,"kaluga.su":true,"karelia.su":true,"khakassia.su":true,"krasnodar.su":true,"kurgan.su":true,"lenug.su":true,"mordovia.su":true,"msk.su":true,"murmansk.su":true,"nalchik.su":true,"nov.su":true,"obninsk.su":true,"penza.su":true,"pokrovsk.su":true,"sochi.su":true,"spb.su":true,"togliatti.su":true,"troitsk.su":true,"tula.su":true,"tuva.su":true,"vladikavkaz.su":true,"vladimir.su":true,"vologda.su":true,"sv":true,"com.sv":true,"edu.sv":true,"gob.sv":true,"org.sv":true,"red.sv":true,"sx":true,"gov.sx":true,"sy":true,"edu.sy":true,"gov.sy":true,"net.sy":true,"mil.sy":true,"com.sy":true,"org.sy":true,"sz":true,"co.sz":true,"ac.sz":true,"org.sz":true,"tc":true,"td":true,"tel":true,"tf":true,"tg":true,"th":true,"ac.th":true,"co.th":true,"go.th":true,"in.th":true,"mi.th":true,"net.th":true,"or.th":true,"tj":true,"ac.tj":true,"biz.tj":true,"co.tj":true,"com.tj":true,"edu.tj":true,"go.tj":true,"gov.tj":true,"int.tj":true,"mil.tj":true,"name.tj":true,"net.tj":true,"nic.tj":true,"org.tj":true,"test.tj":true,"web.tj":true,"tk":true,"tl":true,"gov.tl":true,"tm":true,"com.tm":true,"co.tm":true,"org.tm":true,"net.tm":true,"nom.tm":true,"gov.tm":true,"mil.tm":true,"edu.tm":true,"tn":true,"com.tn":true,"ens.tn":true,"fin.tn":true,"gov.tn":true,"ind.tn":true,"intl.tn":true,"nat.tn":true,"net.tn":true,"org.tn":true,"info.tn":true,"perso.tn":true,"tourism.tn":true,"edunet.tn":true,"rnrt.tn":true,"rns.tn":true,"rnu.tn":true,"mincom.tn":true,"agrinet.tn":true,"defense.tn":true,"turen.tn":true,"to":true,"com.to":true,"gov.to":true,"net.to":true,"org.to":true,"edu.to":true,"mil.to":true,"tp":true,"tr":true,"com.tr":true,"info.tr":true,"biz.tr":true,"net.tr":true,"org.tr":true,"web.tr":true,"gen.tr":true,"tv.tr":true,"av.tr":true,"dr.tr":true,"bbs.tr":true,"name.tr":true,"tel.tr":true,"gov.tr":true,"bel.tr":true,"pol.tr":true,"mil.tr":true,"k12.tr":true,"edu.tr":true,"kep.tr":true,"nc.tr":true,"gov.nc.tr":true,"travel":true,"tt":true,"co.tt":true,"com.tt":true,"org.tt":true,"net.tt":true,"biz.tt":true,"info.tt":true,"pro.tt":true,"int.tt":true,"coop.tt":true,"jobs.tt":true,"mobi.tt":true,"travel.tt":true,"museum.tt":true,"aero.tt":true,"name.tt":true,"gov.tt":true,"edu.tt":true,"tv":true,"tw":true,"edu.tw":true,"gov.tw":true,"mil.tw":true,"com.tw":true,"net.tw":true,"org.tw":true,"idv.tw":true,"game.tw":true,"ebiz.tw":true,"club.tw":true,"xn--zf0ao64a.tw":true,"xn--uc0atv.tw":true,"xn--czrw28b.tw":true,"tz":true,"ac.tz":true,"co.tz":true,"go.tz":true,"hotel.tz":true,"info.tz":true,"me.tz":true,"mil.tz":true,"mobi.tz":true,"ne.tz":true,"or.tz":true,"sc.tz":true,"tv.tz":true,"ua":true,"com.ua":true,"edu.ua":true,"gov.ua":true,"in.ua":true,"net.ua":true,"org.ua":true,"cherkassy.ua":true,"cherkasy.ua":true,"chernigov.ua":true,"chernihiv.ua":true,"chernivtsi.ua":true,"chernovtsy.ua":true,"ck.ua":true,"cn.ua":true,"cr.ua":true,"crimea.ua":true,"cv.ua":true,"dn.ua":true,"dnepropetrovsk.ua":true,"dnipropetrovsk.ua":true,"dominic.ua":true,"donetsk.ua":true,"dp.ua":true,"if.ua":true,"ivano-frankivsk.ua":true,"kh.ua":true,"kharkiv.ua":true,"kharkov.ua":true,"kherson.ua":true,"khmelnitskiy.ua":true,"khmelnytskyi.ua":true,"kiev.ua":true,"kirovograd.ua":true,"km.ua":true,"kr.ua":true,"krym.ua":true,"ks.ua":true,"kv.ua":true,"kyiv.ua":true,"lg.ua":true,"lt.ua":true,"lugansk.ua":true,"lutsk.ua":true,"lv.ua":true,"lviv.ua":true,"mk.ua":true,"mykolaiv.ua":true,"nikolaev.ua":true,"od.ua":true,"odesa.ua":true,"odessa.ua":true,"pl.ua":true,"poltava.ua":true,"rivne.ua":true,"rovno.ua":true,"rv.ua":true,"sb.ua":true,"sebastopol.ua":true,"sevastopol.ua":true,"sm.ua":true,"sumy.ua":true,"te.ua":true,"ternopil.ua":true,"uz.ua":true,"uzhgorod.ua":true,"vinnica.ua":true,"vinnytsia.ua":true,"vn.ua":true,"volyn.ua":true,"yalta.ua":true,"zaporizhzhe.ua":true,"zaporizhzhia.ua":true,"zhitomir.ua":true,"zhytomyr.ua":true,"zp.ua":true,"zt.ua":true,"co.ua":true,"pp.ua":true,"ug":true,"co.ug":true,"or.ug":true,"ac.ug":true,"sc.ug":true,"go.ug":true,"ne.ug":true,"com.ug":true,"org.ug":true,"uk":true,"ac.uk":true,"co.uk":true,"gov.uk":true,"ltd.uk":true,"me.uk":true,"net.uk":true,"nhs.uk":true,"org.uk":true,"plc.uk":true,"police.uk":true,"*.sch.uk":true,"us":true,"dni.us":true,"fed.us":true,"isa.us":true,"kids.us":true,"nsn.us":true,"ak.us":true,"al.us":true,"ar.us":true,"as.us":true,"az.us":true,"ca.us":true,"co.us":true,"ct.us":true,"dc.us":true,"de.us":true,"fl.us":true,"ga.us":true,"gu.us":true,"hi.us":true,"ia.us":true,"id.us":true,"il.us":true,"in.us":true,"ks.us":true,"ky.us":true,"la.us":true,"ma.us":true,"md.us":true,"me.us":true,"mi.us":true,"mn.us":true,"mo.us":true,"ms.us":true,"mt.us":true,"nc.us":true,"nd.us":true,"ne.us":true,"nh.us":true,"nj.us":true,"nm.us":true,"nv.us":true,"ny.us":true,"oh.us":true,"ok.us":true,"or.us":true,"pa.us":true,"pr.us":true,"ri.us":true,"sc.us":true,"sd.us":true,"tn.us":true,"tx.us":true,"ut.us":true,"vi.us":true,"vt.us":true,"va.us":true,"wa.us":true,"wi.us":true,"wv.us":true,"wy.us":true,"k12.ak.us":true,"k12.al.us":true,"k12.ar.us":true,"k12.as.us":true,"k12.az.us":true,"k12.ca.us":true,"k12.co.us":true,"k12.ct.us":true,"k12.dc.us":true,"k12.de.us":true,"k12.fl.us":true,"k12.ga.us":true,"k12.gu.us":true,"k12.ia.us":true,"k12.id.us":true,"k12.il.us":true,"k12.in.us":true,"k12.ks.us":true,"k12.ky.us":true,"k12.la.us":true,"k12.ma.us":true,"k12.md.us":true,"k12.me.us":true,"k12.mi.us":true,"k12.mn.us":true,"k12.mo.us":true,"k12.ms.us":true,"k12.mt.us":true,"k12.nc.us":true,"k12.ne.us":true,"k12.nh.us":true,"k12.nj.us":true,"k12.nm.us":true,"k12.nv.us":true,"k12.ny.us":true,"k12.oh.us":true,"k12.ok.us":true,"k12.or.us":true,"k12.pa.us":true,"k12.pr.us":true,"k12.ri.us":true,"k12.sc.us":true,"k12.tn.us":true,"k12.tx.us":true,"k12.ut.us":true,"k12.vi.us":true,"k12.vt.us":true,"k12.va.us":true,"k12.wa.us":true,"k12.wi.us":true,"k12.wy.us":true,"cc.ak.us":true,"cc.al.us":true,"cc.ar.us":true,"cc.as.us":true,"cc.az.us":true,"cc.ca.us":true,"cc.co.us":true,"cc.ct.us":true,"cc.dc.us":true,"cc.de.us":true,"cc.fl.us":true,"cc.ga.us":true,"cc.gu.us":true,"cc.hi.us":true,"cc.ia.us":true,"cc.id.us":true,"cc.il.us":true,"cc.in.us":true,"cc.ks.us":true,"cc.ky.us":true,"cc.la.us":true,"cc.ma.us":true,"cc.md.us":true,"cc.me.us":true,"cc.mi.us":true,"cc.mn.us":true,"cc.mo.us":true,"cc.ms.us":true,"cc.mt.us":true,"cc.nc.us":true,"cc.nd.us":true,"cc.ne.us":true,"cc.nh.us":true,"cc.nj.us":true,"cc.nm.us":true,"cc.nv.us":true,"cc.ny.us":true,"cc.oh.us":true,"cc.ok.us":true,"cc.or.us":true,"cc.pa.us":true,"cc.pr.us":true,"cc.ri.us":true,"cc.sc.us":true,"cc.sd.us":true,"cc.tn.us":true,"cc.tx.us":true,"cc.ut.us":true,"cc.vi.us":true,"cc.vt.us":true,"cc.va.us":true,"cc.wa.us":true,"cc.wi.us":true,"cc.wv.us":true,"cc.wy.us":true,"lib.ak.us":true,"lib.al.us":true,"lib.ar.us":true,"lib.as.us":true,"lib.az.us":true,"lib.ca.us":true,"lib.co.us":true,"lib.ct.us":true,"lib.dc.us":true,"lib.de.us":true,"lib.fl.us":true,"lib.ga.us":true,"lib.gu.us":true,"lib.hi.us":true,"lib.ia.us":true,"lib.id.us":true,"lib.il.us":true,"lib.in.us":true,"lib.ks.us":true,"lib.ky.us":true,"lib.la.us":true,"lib.ma.us":true,"lib.md.us":true,"lib.me.us":true,"lib.mi.us":true,"lib.mn.us":true,"lib.mo.us":true,"lib.ms.us":true,"lib.mt.us":true,"lib.nc.us":true,"lib.nd.us":true,"lib.ne.us":true,"lib.nh.us":true,"lib.nj.us":true,"lib.nm.us":true,"lib.nv.us":true,"lib.ny.us":true,"lib.oh.us":true,"lib.ok.us":true,"lib.or.us":true,"lib.pa.us":true,"lib.pr.us":true,"lib.ri.us":true,"lib.sc.us":true,"lib.sd.us":true,"lib.tn.us":true,"lib.tx.us":true,"lib.ut.us":true,"lib.vi.us":true,"lib.vt.us":true,"lib.va.us":true,"lib.wa.us":true,"lib.wi.us":true,"lib.wy.us":true,"pvt.k12.ma.us":true,"chtr.k12.ma.us":true,"paroch.k12.ma.us":true,"uy":true,"com.uy":true,"edu.uy":true,"gub.uy":true,"mil.uy":true,"net.uy":true,"org.uy":true,"uz":true,"co.uz":true,"com.uz":true,"net.uz":true,"org.uz":true,"va":true,"vc":true,"com.vc":true,"net.vc":true,"org.vc":true,"gov.vc":true,"mil.vc":true,"edu.vc":true,"ve":true,"arts.ve":true,"co.ve":true,"com.ve":true,"e12.ve":true,"edu.ve":true,"firm.ve":true,"gob.ve":true,"gov.ve":true,"info.ve":true,"int.ve":true,"mil.ve":true,"net.ve":true,"org.ve":true,"rec.ve":true,"store.ve":true,"tec.ve":true,"web.ve":true,"vg":true,"vi":true,"co.vi":true,"com.vi":true,"k12.vi":true,"net.vi":true,"org.vi":true,"vn":true,"com.vn":true,"net.vn":true,"org.vn":true,"edu.vn":true,"gov.vn":true,"int.vn":true,"ac.vn":true,"biz.vn":true,"info.vn":true,"name.vn":true,"pro.vn":true,"health.vn":true,"vu":true,"com.vu":true,"edu.vu":true,"net.vu":true,"org.vu":true,"wf":true,"ws":true,"com.ws":true,"net.ws":true,"org.ws":true,"gov.ws":true,"edu.ws":true,"yt":true,"xn--mgbaam7a8h":true,"xn--54b7fta0cc":true,"xn--fiqs8s":true,"xn--fiqz9s":true,"xn--lgbbat1ad8j":true,"xn--wgbh1c":true,"xn--node":true,"xn--j6w193g":true,"xn--h2brj9c":true,"xn--mgbbh1a71e":true,"xn--fpcrj9c3d":true,"xn--gecrj9c":true,"xn--s9brj9c":true,"xn--45brj9c":true,"xn--xkc2dl3a5ee0h":true,"xn--mgba3a4f16a":true,"xn--mgba3a4fra":true,"xn--mgbayh7gpa":true,"xn--3e0b707e":true,"xn--80ao21a":true,"xn--fzc2c9e2c":true,"xn--xkc2al3hye2a":true,"xn--mgbc0a9azcg":true,"xn--l1acc":true,"xn--mgbx4cd0ab":true,"xn--mgb9awbf":true,"xn--ygbi2ammx":true,"xn--90a3ac":true,"xn--o1ac.xn--90a3ac":true,"xn--c1avg.xn--90a3ac":true,"xn--90azh.xn--90a3ac":true,"xn--d1at.xn--90a3ac":true,"xn--o1ach.xn--90a3ac":true,"xn--80au.xn--90a3ac":true,"xn--p1ai":true,"xn--wgbl6a":true,"xn--mgberp4a5d4ar":true,"xn--mgberp4a5d4a87g":true,"xn--mgbqly7c0a67fbc":true,"xn--mgbqly7cvafr":true,"xn--ogbpf8fl":true,"xn--mgbtf8fl":true,"xn--yfro4i67o":true,"xn--clchc0ea0b2g2a9gcd":true,"xn--o3cw4h":true,"xn--pgbs0dh":true,"xn--kpry57d":true,"xn--kprw13d":true,"xn--nnx388a":true,"xn--j1amh":true,"xn--mgb2ddes":true,"xxx":true,"*.ye":true,"*.za":true,"*.zm":true,"*.zw":true,"aaa":true,"abb":true,"abbott":true,"abogado":true,"academy":true,"accenture":true,"accountant":true,"accountants":true,"aco":true,"active":true,"actor":true,"ads":true,"adult":true,"aeg":true,"afl":true,"africa":true,"africamagic":true,"agency":true,"aig":true,"airforce":true,"airtel":true,"alibaba":true,"alipay":true,"allfinanz":true,"alsace":true,"amsterdam":true,"analytics":true,"android":true,"anquan":true,"apartments":true,"aquarelle":true,"aramco":true,"archi":true,"army":true,"arte":true,"associates":true,"attorney":true,"auction":true,"audio":true,"author":true,"auto":true,"autos":true,"avianca":true,"axa":true,"azure":true,"baidu":true,"band":true,"bank":true,"bar":true,"barcelona":true,"barclaycard":true,"barclays":true,"bargains":true,"bauhaus":true,"bayern":true,"bbc":true,"bbva":true,"bcg":true,"bcn":true,"beer":true,"bentley":true,"berlin":true,"best":true,"bharti":true,"bible":true,"bid":true,"bike":true,"bing":true,"bingo":true,"bio":true,"black":true,"blackfriday":true,"bloomberg":true,"blue":true,"bms":true,"bmw":true,"bnl":true,"bnpparibas":true,"boats":true,"bom":true,"bond":true,"boo":true,"boots":true,"bot":true,"boutique":true,"bradesco":true,"bridgestone":true,"broadway":true,"broker":true,"brother":true,"brussels":true,"budapest":true,"build":true,"builders":true,"business":true,"buy":true,"buzz":true,"bzh":true,"cab":true,"cafe":true,"cal":true,"call":true,"camera":true,"camp":true,"cancerresearch":true,"canon":true,"capetown":true,"capital":true,"car":true,"caravan":true,"cards":true,"care":true,"career":true,"careers":true,"cars":true,"cartier":true,"casa":true,"cash":true,"casino":true,"catering":true,"cba":true,"cbn":true,"center":true,"ceo":true,"cern":true,"cfa":true,"cfd":true,"channel":true,"chat":true,"cheap":true,"chloe":true,"christmas":true,"chrome":true,"church":true,"cipriani":true,"circle":true,"cisco":true,"citic":true,"city":true,"cityeats":true,"claims":true,"cleaning":true,"click":true,"clinic":true,"clothing":true,"club":true,"coach":true,"codes":true,"coffee":true,"college":true,"cologne":true,"commbank":true,"community":true,"company":true,"computer":true,"comsec":true,"condos":true,"construction":true,"consulting":true,"contact":true,"contractors":true,"cooking":true,"cool":true,"corsica":true,"country":true,"coupon":true,"coupons":true,"courses":true,"credit":true,"creditcard":true,"creditunion":true,"cricket":true,"crown":true,"crs":true,"cruises":true,"csc":true,"cuisinella":true,"cymru":true,"cyou":true,"dabur":true,"dad":true,"dance":true,"date":true,"dating":true,"datsun":true,"day":true,"dclk":true,"dealer":true,"deals":true,"degree":true,"delivery":true,"dell":true,"delta":true,"democrat":true,"dental":true,"dentist":true,"desi":true,"design":true,"dev":true,"diamonds":true,"diet":true,"digital":true,"direct":true,"directory":true,"discount":true,"dnp":true,"docs":true,"dog":true,"doha":true,"domains":true,"doosan":true,"download":true,"drive":true,"dstv":true,"dubai":true,"durban":true,"dvag":true,"earth":true,"eat":true,"edeka":true,"education":true,"email":true,"emerck":true,"energy":true,"engineer":true,"engineering":true,"enterprises":true,"epson":true,"equipment":true,"erni":true,"esq":true,"estate":true,"eurovision":true,"eus":true,"events":true,"everbank":true,"exchange":true,"expert":true,"exposed":true,"express":true,"fage":true,"fail":true,"fairwinds":true,"faith":true,"family":true,"fan":true,"fans":true,"farm":true,"fashion":true,"fast":true,"feedback":true,"ferrero":true,"film":true,"final":true,"finance":true,"financial":true,"firestone":true,"firmdale":true,"fish":true,"fishing":true,"fit":true,"fitness":true,"flickr":true,"flights":true,"florist":true,"flowers":true,"flsmidth":true,"fly":true,"foo":true,"football":true,"ford":true,"forex":true,"forsale":true,"forum":true,"foundation":true,"frl":true,"frogans":true,"frontier":true,"fund":true,"furniture":true,"futbol":true,"fyi":true,"gal":true,"gallery":true,"gallup":true,"garden":true,"gbiz":true,"gdn":true,"gea":true,"gent":true,"genting":true,"ggee":true,"gift":true,"gifts":true,"gives":true,"giving":true,"glass":true,"gle":true,"global":true,"globo":true,"gmail":true,"gmo":true,"gmx":true,"gold":true,"goldpoint":true,"golf":true,"goo":true,"goog":true,"google":true,"gop":true,"got":true,"gotv":true,"graphics":true,"gratis":true,"green":true,"gripe":true,"group":true,"gucci":true,"guge":true,"guide":true,"guitars":true,"guru":true,"hamburg":true,"hangout":true,"haus":true,"hdfcbank":true,"health":true,"healthcare":true,"help":true,"helsinki":true,"here":true,"hermes":true,"hiphop":true,"hitachi":true,"hiv":true,"hockey":true,"holdings":true,"holiday":true,"homedepot":true,"homes":true,"honda":true,"horse":true,"host":true,"hosting":true,"hoteles":true,"hotmail":true,"house":true,"how":true,"hsbc":true,"htc":true,"ibm":true,"icbc":true,"ice":true,"icu":true,"ifm":true,"iinet":true,"immo":true,"immobilien":true,"industries":true,"infiniti":true,"ing":true,"ink":true,"institute":true,"insurance":true,"insure":true,"international":true,"investments":true,"ipiranga":true,"irish":true,"iselect":true,"ist":true,"istanbul":true,"itau":true,"iwc":true,"jaguar":true,"java":true,"jcb":true,"jetzt":true,"jewelry":true,"jio":true,"jlc":true,"jll":true,"jmp":true,"joburg":true,"jot":true,"joy":true,"jprs":true,"juegos":true,"kaufen":true,"kddi":true,"kfh":true,"kim":true,"kinder":true,"kitchen":true,"kiwi":true,"koeln":true,"komatsu":true,"kpn":true,"krd":true,"kred":true,"kyknet":true,"kyoto":true,"lacaixa":true,"lancaster":true,"land":true,"landrover":true,"lasalle":true,"lat":true,"latrobe":true,"law":true,"lawyer":true,"lds":true,"lease":true,"leclerc":true,"legal":true,"lgbt":true,"liaison":true,"lidl":true,"life":true,"lifeinsurance":true,"lifestyle":true,"lighting":true,"like":true,"limited":true,"limo":true,"lincoln":true,"linde":true,"link":true,"live":true,"lixil":true,"loan":true,"loans":true,"lol":true,"london":true,"lotte":true,"lotto":true,"love":true,"ltd":true,"ltda":true,"lupin":true,"luxe":true,"luxury":true,"madrid":true,"maif":true,"maison":true,"makeup":true,"man":true,"management":true,"mango":true,"market":true,"marketing":true,"markets":true,"marriott":true,"mba":true,"media":true,"meet":true,"melbourne":true,"meme":true,"memorial":true,"men":true,"menu":true,"meo":true,"miami":true,"microsoft":true,"mini":true,"mma":true,"mnet":true,"mobily":true,"moda":true,"moe":true,"moi":true,"monash":true,"money":true,"montblanc":true,"mormon":true,"mortgage":true,"moscow":true,"motorcycles":true,"mov":true,"movie":true,"movistar":true,"mtn":true,"mtpc":true,"mtr":true,"multichoice":true,"mutual":true,"mzansimagic":true,"nadex":true,"nagoya":true,"naspers":true,"natura":true,"navy":true,"nec":true,"netbank":true,"network":true,"neustar":true,"new":true,"news":true,"nexus":true,"ngo":true,"nhk":true,"nico":true,"ninja":true,"nissan":true,"nokia":true,"norton":true,"nowruz":true,"nra":true,"nrw":true,"ntt":true,"nyc":true,"obi":true,"office":true,"okinawa":true,"omega":true,"one":true,"ong":true,"onl":true,"online":true,"ooo":true,"oracle":true,"orange":true,"organic":true,"orientexpress":true,"osaka":true,"otsuka":true,"ovh":true,"page":true,"pamperedchef":true,"panerai":true,"paris":true,"pars":true,"partners":true,"parts":true,"party":true,"passagens":true,"payu":true,"pharmacy":true,"philips":true,"photo":true,"photography":true,"photos":true,"physio":true,"piaget":true,"pics":true,"pictet":true,"pictures":true,"pid":true,"pin":true,"pink":true,"pizza":true,"place":true,"play":true,"plumbing":true,"plus":true,"pohl":true,"poker":true,"porn":true,"praxi":true,"press":true,"prod":true,"productions":true,"prof":true,"promo":true,"properties":true,"property":true,"pub":true,"qpon":true,"quebec":true,"quest":true,"racing":true,"read":true,"realtor":true,"realty":true,"recipes":true,"red":true,"redstone":true,"redumbrella":true,"rehab":true,"reise":true,"reisen":true,"reit":true,"reliance":true,"ren":true,"rent":true,"rentals":true,"repair":true,"report":true,"republican":true,"rest":true,"restaurant":true,"review":true,"reviews":true,"rich":true,"ricoh":true,"ril":true,"rio":true,"rip":true,"rocher":true,"rocks":true,"rodeo":true,"room":true,"rsvp":true,"ruhr":true,"run":true,"rwe":true,"ryukyu":true,"saarland":true,"safe":true,"safety":true,"sakura":true,"sale":true,"salon":true,"samsung":true,"sandvik":true,"sandvikcoromant":true,"sanofi":true,"sap":true,"sapo":true,"sarl":true,"sas":true,"saxo":true,"sbi":true,"sbs":true,"sca":true,"scb":true,"schmidt":true,"scholarships":true,"school":true,"schule":true,"schwarz":true,"science":true,"scor":true,"scot":true,"seat":true,"seek":true,"sener":true,"services":true,"sew":true,"sex":true,"sexy":true,"sharp":true,"shia":true,"shiksha":true,"shoes":true,"shouji":true,"show":true,"shriram":true,"sina":true,"singles":true,"site":true,"skin":true,"sky":true,"skype":true,"smile":true,"sncf":true,"soccer":true,"social":true,"software":true,"sohu":true,"solar":true,"solutions":true,"song":true,"sony":true,"soy":true,"space":true,"spiegel":true,"spot":true,"spreadbetting":true,"stada":true,"star":true,"starhub":true,"statebank":true,"statoil":true,"stc":true,"stcgroup":true,"stockholm":true,"storage":true,"studio":true,"study":true,"style":true,"sucks":true,"supersport":true,"supplies":true,"supply":true,"support":true,"surf":true,"surgery":true,"suzuki":true,"swatch":true,"swiss":true,"sydney":true,"symantec":true,"systems":true,"tab":true,"taipei":true,"taobao":true,"tatamotors":true,"tatar":true,"tattoo":true,"tax":true,"taxi":true,"tci":true,"team":true,"tech":true,"technology":true,"telecity":true,"telefonica":true,"temasek":true,"tennis":true,"thd":true,"theater":true,"tickets":true,"tienda":true,"tiffany":true,"tips":true,"tires":true,"tirol":true,"tmall":true,"today":true,"tokyo":true,"tools":true,"top":true,"toray":true,"toshiba":true,"tours":true,"town":true,"toys":true,"trade":true,"trading":true,"training":true,"travelers":true,"travelersinsurance":true,"trust":true,"trv":true,"tui":true,"tunes":true,"tushu":true,"tvs":true,"ubs":true,"university":true,"uno":true,"uol":true,"vacations":true,"vana":true,"vegas":true,"ventures":true,"versicherung":true,"vet":true,"viajes":true,"video":true,"viking":true,"villas":true,"vip":true,"virgin":true,"vision":true,"vista":true,"vistaprint":true,"viva":true,"vlaanderen":true,"vodka":true,"vote":true,"voting":true,"voto":true,"voyage":true,"vuelos":true,"wales":true,"walter":true,"wang":true,"wanggou":true,"watch":true,"watches":true,"weather":true,"weatherchannel":true,"webcam":true,"website":true,"wed":true,"wedding":true,"weibo":true,"weir":true,"whoswho":true,"wien":true,"wiki":true,"williamhill":true,"win":true,"windows":true,"wme":true,"work":true,"works":true,"world":true,"wtc":true,"wtf":true,"xbox":true,"xerox":true,"xihuan":true,"xin":true,"xn--11b4c3d":true,"xn--1ck2e1b":true,"xn--1qqw23a":true,"xn--30rr7y":true,"xn--3bst00m":true,"xn--3ds443g":true,"xn--3pxu8k":true,"xn--42c2d9a":true,"xn--45q11c":true,"xn--4gbrim":true,"xn--55qw42g":true,"xn--55qx5d":true,"xn--5tzm5g":true,"xn--6frz82g":true,"xn--6qq986b3xl":true,"xn--80adxhks":true,"xn--80asehdb":true,"xn--80aswg":true,"xn--8y0a063a":true,"xn--9dbq2a":true,"xn--9et52u":true,"xn--9krt00a":true,"xn--b4w605ferd":true,"xn--bck1b9a5dre4c":true,"xn--c1avg":true,"xn--c2br7g":true,"xn--cck2b3b":true,"xn--cg4bki":true,"xn--czr694b":true,"xn--czrs0t":true,"xn--czru2d":true,"xn--d1acj3b":true,"xn--eckvdtc9d":true,"xn--efvy88h":true,"xn--estv75g":true,"xn--fhbei":true,"xn--fiq228c5hs":true,"xn--fiq64b":true,"xn--fjq720a":true,"xn--flw351e":true,"xn--g2xx48c":true,"xn--gckr3f0f":true,"xn--hxt814e":true,"xn--i1b6b1a6a2e":true,"xn--imr513n":true,"xn--io0a7i":true,"xn--j1aef":true,"xn--jlq61u9w7b":true,"xn--jvr189m":true,"xn--kcrx77d1x4a":true,"xn--kpu716f":true,"xn--kput3i":true,"xn--mgba3a3ejt":true,"xn--mgbab2bd":true,"xn--mgbb9fbpob":true,"xn--mgbt3dhd":true,"xn--mk1bu44c":true,"xn--mxtq1m":true,"xn--ngbc5azd":true,"xn--ngbe9e0a":true,"xn--nqv7f":true,"xn--nqv7fs00ema":true,"xn--nyqy26a":true,"xn--p1acf":true,"xn--pbt977c":true,"xn--pssy2u":true,"xn--q9jyb4c":true,"xn--qcka1pmc":true,"xn--rhqv96g":true,"xn--rovu88b":true,"xn--ses554g":true,"xn--t60b56a":true,"xn--tckwe":true,"xn--unup4y":true,"xn--vermgensberater-ctb":true,"xn--vermgensberatung-pwb":true,"xn--vhquv":true,"xn--vuq861b":true,"xn--xhq521b":true,"xn--zfr164b":true,"xyz":true,"yachts":true,"yahoo":true,"yamaxun":true,"yandex":true,"yodobashi":true,"yoga":true,"yokohama":true,"youtube":true,"yun":true,"zara":true,"zero":true,"zip":true,"zone":true,"zuerich":true,"cloudfront.net":true,"ap-northeast-1.compute.amazonaws.com":true,"ap-southeast-1.compute.amazonaws.com":true,"ap-southeast-2.compute.amazonaws.com":true,"cn-north-1.compute.amazonaws.cn":true,"compute.amazonaws.cn":true,"compute.amazonaws.com":true,"compute-1.amazonaws.com":true,"eu-west-1.compute.amazonaws.com":true,"eu-central-1.compute.amazonaws.com":true,"sa-east-1.compute.amazonaws.com":true,"us-east-1.amazonaws.com":true,"us-gov-west-1.compute.amazonaws.com":true,"us-west-1.compute.amazonaws.com":true,"us-west-2.compute.amazonaws.com":true,"z-1.compute-1.amazonaws.com":true,"z-2.compute-1.amazonaws.com":true,"elasticbeanstalk.com":true,"elb.amazonaws.com":true,"s3.amazonaws.com":true,"s3-us-west-2.amazonaws.com":true,"s3-us-west-1.amazonaws.com":true,"s3-eu-west-1.amazonaws.com":true,"s3-ap-southeast-1.amazonaws.com":true,"s3-ap-southeast-2.amazonaws.com":true,"s3-ap-northeast-1.amazonaws.com":true,"s3-sa-east-1.amazonaws.com":true,"s3-us-gov-west-1.amazonaws.com":true,"s3-fips-us-gov-west-1.amazonaws.com":true,"s3-website-us-east-1.amazonaws.com":true,"s3-website-us-west-2.amazonaws.com":true,"s3-website-us-west-1.amazonaws.com":true,"s3-website-eu-west-1.amazonaws.com":true,"s3-website-ap-southeast-1.amazonaws.com":true,"s3-website-ap-southeast-2.amazonaws.com":true,"s3-website-ap-northeast-1.amazonaws.com":true,"s3-website-sa-east-1.amazonaws.com":true,"s3-website-us-gov-west-1.amazonaws.com":true,"betainabox.com":true,"ae.org":true,"ar.com":true,"br.com":true,"cn.com":true,"com.de":true,"com.se":true,"de.com":true,"eu.com":true,"gb.com":true,"gb.net":true,"hu.com":true,"hu.net":true,"jp.net":true,"jpn.com":true,"kr.com":true,"mex.com":true,"no.com":true,"qc.com":true,"ru.com":true,"sa.com":true,"se.com":true,"se.net":true,"uk.com":true,"uk.net":true,"us.com":true,"uy.com":true,"za.bz":true,"za.com":true,"africa.com":true,"gr.com":true,"in.net":true,"us.org":true,"co.com":true,"c.la":true,"cloudcontrolled.com":true,"cloudcontrolapp.com":true,"co.ca":true,"co.nl":true,"co.no":true,"*.platform.sh":true,"cupcake.is":true,"dreamhosters.com":true,"dyndns-at-home.com":true,"dyndns-at-work.com":true,"dyndns-blog.com":true,"dyndns-free.com":true,"dyndns-home.com":true,"dyndns-ip.com":true,"dyndns-mail.com":true,"dyndns-office.com":true,"dyndns-pics.com":true,"dyndns-remote.com":true,"dyndns-server.com":true,"dyndns-web.com":true,"dyndns-wiki.com":true,"dyndns-work.com":true,"dyndns.biz":true,"dyndns.info":true,"dyndns.org":true,"dyndns.tv":true,"at-band-camp.net":true,"ath.cx":true,"barrel-of-knowledge.info":true,"barrell-of-knowledge.info":true,"better-than.tv":true,"blogdns.com":true,"blogdns.net":true,"blogdns.org":true,"blogsite.org":true,"boldlygoingnowhere.org":true,"broke-it.net":true,"buyshouses.net":true,"cechire.com":true,"dnsalias.com":true,"dnsalias.net":true,"dnsalias.org":true,"dnsdojo.com":true,"dnsdojo.net":true,"dnsdojo.org":true,"does-it.net":true,"doesntexist.com":true,"doesntexist.org":true,"dontexist.com":true,"dontexist.net":true,"dontexist.org":true,"doomdns.com":true,"doomdns.org":true,"dvrdns.org":true,"dyn-o-saur.com":true,"dynalias.com":true,"dynalias.net":true,"dynalias.org":true,"dynathome.net":true,"dyndns.ws":true,"endofinternet.net":true,"endofinternet.org":true,"endoftheinternet.org":true,"est-a-la-maison.com":true,"est-a-la-masion.com":true,"est-le-patron.com":true,"est-mon-blogueur.com":true,"for-better.biz":true,"for-more.biz":true,"for-our.info":true,"for-some.biz":true,"for-the.biz":true,"forgot.her.name":true,"forgot.his.name":true,"from-ak.com":true,"from-al.com":true,"from-ar.com":true,"from-az.net":true,"from-ca.com":true,"from-co.net":true,"from-ct.com":true,"from-dc.com":true,"from-de.com":true,"from-fl.com":true,"from-ga.com":true,"from-hi.com":true,"from-ia.com":true,"from-id.com":true,"from-il.com":true,"from-in.com":true,"from-ks.com":true,"from-ky.com":true,"from-la.net":true,"from-ma.com":true,"from-md.com":true,"from-me.org":true,"from-mi.com":true,"from-mn.com":true,"from-mo.com":true,"from-ms.com":true,"from-mt.com":true,"from-nc.com":true,"from-nd.com":true,"from-ne.com":true,"from-nh.com":true,"from-nj.com":true,"from-nm.com":true,"from-nv.com":true,"from-ny.net":true,"from-oh.com":true,"from-ok.com":true,"from-or.com":true,"from-pa.com":true,"from-pr.com":true,"from-ri.com":true,"from-sc.com":true,"from-sd.com":true,"from-tn.com":true,"from-tx.com":true,"from-ut.com":true,"from-va.com":true,"from-vt.com":true,"from-wa.com":true,"from-wi.com":true,"from-wv.com":true,"from-wy.com":true,"ftpaccess.cc":true,"fuettertdasnetz.de":true,"game-host.org":true,"game-server.cc":true,"getmyip.com":true,"gets-it.net":true,"go.dyndns.org":true,"gotdns.com":true,"gotdns.org":true,"groks-the.info":true,"groks-this.info":true,"ham-radio-op.net":true,"here-for-more.info":true,"hobby-site.com":true,"hobby-site.org":true,"home.dyndns.org":true,"homedns.org":true,"homeftp.net":true,"homeftp.org":true,"homeip.net":true,"homelinux.com":true,"homelinux.net":true,"homelinux.org":true,"homeunix.com":true,"homeunix.net":true,"homeunix.org":true,"iamallama.com":true,"in-the-band.net":true,"is-a-anarchist.com":true,"is-a-blogger.com":true,"is-a-bookkeeper.com":true,"is-a-bruinsfan.org":true,"is-a-bulls-fan.com":true,"is-a-candidate.org":true,"is-a-caterer.com":true,"is-a-celticsfan.org":true,"is-a-chef.com":true,"is-a-chef.net":true,"is-a-chef.org":true,"is-a-conservative.com":true,"is-a-cpa.com":true,"is-a-cubicle-slave.com":true,"is-a-democrat.com":true,"is-a-designer.com":true,"is-a-doctor.com":true,"is-a-financialadvisor.com":true,"is-a-geek.com":true,"is-a-geek.net":true,"is-a-geek.org":true,"is-a-green.com":true,"is-a-guru.com":true,"is-a-hard-worker.com":true,"is-a-hunter.com":true,"is-a-knight.org":true,"is-a-landscaper.com":true,"is-a-lawyer.com":true,"is-a-liberal.com":true,"is-a-libertarian.com":true,"is-a-linux-user.org":true,"is-a-llama.com":true,"is-a-musician.com":true,"is-a-nascarfan.com":true,"is-a-nurse.com":true,"is-a-painter.com":true,"is-a-patsfan.org":true,"is-a-personaltrainer.com":true,"is-a-photographer.com":true,"is-a-player.com":true,"is-a-republican.com":true,"is-a-rockstar.com":true,"is-a-socialist.com":true,"is-a-soxfan.org":true,"is-a-student.com":true,"is-a-teacher.com":true,"is-a-techie.com":true,"is-a-therapist.com":true,"is-an-accountant.com":true,"is-an-actor.com":true,"is-an-actress.com":true,"is-an-anarchist.com":true,"is-an-artist.com":true,"is-an-engineer.com":true,"is-an-entertainer.com":true,"is-by.us":true,"is-certified.com":true,"is-found.org":true,"is-gone.com":true,"is-into-anime.com":true,"is-into-cars.com":true,"is-into-cartoons.com":true,"is-into-games.com":true,"is-leet.com":true,"is-lost.org":true,"is-not-certified.com":true,"is-saved.org":true,"is-slick.com":true,"is-uberleet.com":true,"is-very-bad.org":true,"is-very-evil.org":true,"is-very-good.org":true,"is-very-nice.org":true,"is-very-sweet.org":true,"is-with-theband.com":true,"isa-geek.com":true,"isa-geek.net":true,"isa-geek.org":true,"isa-hockeynut.com":true,"issmarterthanyou.com":true,"isteingeek.de":true,"istmein.de":true,"kicks-ass.net":true,"kicks-ass.org":true,"knowsitall.info":true,"land-4-sale.us":true,"lebtimnetz.de":true,"leitungsen.de":true,"likes-pie.com":true,"likescandy.com":true,"merseine.nu":true,"mine.nu":true,"misconfused.org":true,"mypets.ws":true,"myphotos.cc":true,"neat-url.com":true,"office-on-the.net":true,"on-the-web.tv":true,"podzone.net":true,"podzone.org":true,"readmyblog.org":true,"saves-the-whales.com":true,"scrapper-site.net":true,"scrapping.cc":true,"selfip.biz":true,"selfip.com":true,"selfip.info":true,"selfip.net":true,"selfip.org":true,"sells-for-less.com":true,"sells-for-u.com":true,"sells-it.net":true,"sellsyourhome.org":true,"servebbs.com":true,"servebbs.net":true,"servebbs.org":true,"serveftp.net":true,"serveftp.org":true,"servegame.org":true,"shacknet.nu":true,"simple-url.com":true,"space-to-rent.com":true,"stuff-4-sale.org":true,"stuff-4-sale.us":true,"teaches-yoga.com":true,"thruhere.net":true,"traeumtgerade.de":true,"webhop.biz":true,"webhop.info":true,"webhop.net":true,"webhop.org":true,"worse-than.tv":true,"writesthisblog.com":true,"a.ssl.fastly.net":true,"b.ssl.fastly.net":true,"global.ssl.fastly.net":true,"a.prod.fastly.net":true,"global.prod.fastly.net":true,"firebaseapp.com":true,"flynnhub.com":true,"service.gov.uk":true,"github.io":true,"githubusercontent.com":true,"ro.com":true,"appspot.com":true,"blogspot.ae":true,"blogspot.be":true,"blogspot.bj":true,"blogspot.ca":true,"blogspot.cf":true,"blogspot.ch":true,"blogspot.co.at":true,"blogspot.co.il":true,"blogspot.co.nz":true,"blogspot.co.uk":true,"blogspot.com":true,"blogspot.com.ar":true,"blogspot.com.au":true,"blogspot.com.br":true,"blogspot.com.es":true,"blogspot.com.tr":true,"blogspot.cv":true,"blogspot.cz":true,"blogspot.de":true,"blogspot.dk":true,"blogspot.fi":true,"blogspot.fr":true,"blogspot.gr":true,"blogspot.hk":true,"blogspot.hu":true,"blogspot.ie":true,"blogspot.in":true,"blogspot.it":true,"blogspot.jp":true,"blogspot.kr":true,"blogspot.mr":true,"blogspot.mx":true,"blogspot.nl":true,"blogspot.no":true,"blogspot.pt":true,"blogspot.re":true,"blogspot.ro":true,"blogspot.ru":true,"blogspot.se":true,"blogspot.sg":true,"blogspot.sk":true,"blogspot.td":true,"blogspot.tw":true,"codespot.com":true,"googleapis.com":true,"googlecode.com":true,"pagespeedmobilizer.com":true,"withgoogle.com":true,"herokuapp.com":true,"herokussl.com":true,"iki.fi":true,"biz.at":true,"info.at":true,"co.pl":true,"azurewebsites.net":true,"azure-mobile.net":true,"cloudapp.net":true,"nfshost.com":true,"nyc.mn":true,"nid.io":true,"operaunite.com":true,"outsystemscloud.com":true,"art.pl":true,"gliwice.pl":true,"krakow.pl":true,"poznan.pl":true,"wroc.pl":true,"zakopane.pl":true,"priv.at":true,"rhcloud.com":true,"sinaapp.com":true,"vipsinaapp.com":true,"1kapp.com":true,"gda.pl":true,"gdansk.pl":true,"gdynia.pl":true,"med.pl":true,"sopot.pl":true,"hk.com":true,"hk.org":true,"ltd.hk":true,"inc.hk":true,"yolasite.com":true,"za.net":true,"za.org":true}); + +// END of automatically generated file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/store.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/store.js new file mode 100644 index 0000000..ad69c14 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/lib/store.js @@ -0,0 +1,67 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +/*jshint unused:false */ + +function Store() { +} +exports.Store = Store; + +// Stores may be synchronous, but are still required to use a +// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" +// API that converts from synchronous-callbacks to imperative style. +Store.prototype.synchronous = false; + +Store.prototype.findCookie = function(domain, path, key, cb) { + throw new Error('findCookie is not implemented'); +}; + +Store.prototype.findCookies = function(domain, path, cb) { + throw new Error('findCookies is not implemented'); +}; + +Store.prototype.putCookie = function(cookie, cb) { + throw new Error('putCookie is not implemented'); +}; + +Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error('updateCookie is not implemented'); +}; + +Store.prototype.removeCookie = function(domain, path, key, cb) { + throw new Error('removeCookie is not implemented'); +}; + +Store.prototype.removeCookies = function removeCookies(domain, path, cb) { + throw new Error('removeCookies is not implemented'); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/package.json new file mode 100644 index 0000000..1264cc4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/package.json @@ -0,0 +1,65 @@ +{ + "author": { + "name": "Jeremy Stashewsky", + "email": "jstashewsky@salesforce.com" + }, + "license": "BSD-3-Clause", + "name": "tough-cookie", + "description": "RFC6265 Cookies and Cookie Jar for node.js", + "keywords": [ + "HTTP", + "cookie", + "cookies", + "set-cookie", + "cookiejar", + "jar", + "RFC6265", + "RFC2965" + ], + "version": "1.2.0", + "homepage": "https://github.com/SalesforceEng/tough-cookie", + "repository": { + "type": "git", + "url": "git://github.com/SalesforceEng/tough-cookie.git" + }, + "bugs": { + "url": "https://github.com/SalesforceEng/tough-cookie/issues" + }, + "main": "./lib/cookie", + "scripts": { + "test": "vows test/*_test.js" + }, + "engines": { + "node": ">=0.10.0" + }, + "devDependencies": { + "vows": "0.7.0", + "async": ">=0.1.12" + }, + "gitHead": "74e59de50b719bb9a1b01c8c9db57fa31401ed1a", + "_id": "tough-cookie@1.2.0", + "_shasum": "9b7e9d98e769e80b5aa899d944fe44e02ebf82ad", + "_from": "tough-cookie@>=0.12.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "jstash", + "email": "jstash@gmail.com" + }, + "dist": { + "shasum": "9b7e9d98e769e80b5aa899d944fe44e02ebf82ad", + "tarball": "http://registry.npmjs.org/tough-cookie/-/tough-cookie-1.2.0.tgz" + }, + "maintainers": [ + { + "name": "jstash", + "email": "jeremy@goinstant.com" + }, + { + "name": "goinstant", + "email": "services@goinstant.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-1.2.0.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/public-suffix.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/public-suffix.txt new file mode 100644 index 0000000..f8941f7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/public-suffix.txt @@ -0,0 +1,10079 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// ===BEGIN ICANN DOMAINS=== + +// ac : http://en.wikipedia.org/wiki/.ac +ac +com.ac +edu.ac +gov.ac +net.ac +mil.ac +org.ac + +// ad : http://en.wikipedia.org/wiki/.ad +ad +nom.ad + +// ae : http://en.wikipedia.org/wiki/.ae +// see also: "Domain Name Eligibility Policy" at http://www.aeda.ae/eng/aepolicy.php +ae +co.ae +net.ae +org.ae +sch.ae +ac.ae +gov.ae +mil.ae + +// aero : see http://www.information.aero/index.php?id=66 +aero +accident-investigation.aero +accident-prevention.aero +aerobatic.aero +aeroclub.aero +aerodrome.aero +agents.aero +aircraft.aero +airline.aero +airport.aero +air-surveillance.aero +airtraffic.aero +air-traffic-control.aero +ambulance.aero +amusement.aero +association.aero +author.aero +ballooning.aero +broker.aero +caa.aero +cargo.aero +catering.aero +certification.aero +championship.aero +charter.aero +civilaviation.aero +club.aero +conference.aero +consultant.aero +consulting.aero +control.aero +council.aero +crew.aero +design.aero +dgca.aero +educator.aero +emergency.aero +engine.aero +engineer.aero +entertainment.aero +equipment.aero +exchange.aero +express.aero +federation.aero +flight.aero +freight.aero +fuel.aero +gliding.aero +government.aero +groundhandling.aero +group.aero +hanggliding.aero +homebuilt.aero +insurance.aero +journal.aero +journalist.aero +leasing.aero +logistics.aero +magazine.aero +maintenance.aero +marketplace.aero +media.aero +microlight.aero +modelling.aero +navigation.aero +parachuting.aero +paragliding.aero +passenger-association.aero +pilot.aero +press.aero +production.aero +recreation.aero +repbody.aero +res.aero +research.aero +rotorcraft.aero +safety.aero +scientist.aero +services.aero +show.aero +skydiving.aero +software.aero +student.aero +taxi.aero +trader.aero +trading.aero +trainer.aero +union.aero +workinggroup.aero +works.aero + +// af : http://www.nic.af/help.jsp +af +gov.af +com.af +org.af +net.af +edu.af + +// ag : http://www.nic.ag/prices.htm +ag +com.ag +org.ag +net.ag +co.ag +nom.ag + +// ai : http://nic.com.ai/ +ai +off.ai +com.ai +net.ai +org.ai + +// al : http://www.ert.gov.al/ert_alb/faq_det.html?Id=31 +al +com.al +edu.al +gov.al +mil.al +net.al +org.al + +// am : http://en.wikipedia.org/wiki/.am +am + +// an : http://www.una.an/an_domreg/default.asp +an +com.an +net.an +org.an +edu.an + +// ao : http://en.wikipedia.org/wiki/.ao +// http://www.dns.ao/REGISTR.DOC +ao +ed.ao +gv.ao +og.ao +co.ao +pb.ao +it.ao + +// aq : http://en.wikipedia.org/wiki/.aq +aq + +// ar : https://nic.ar/normativa-vigente.xhtml +ar +com.ar +edu.ar +gob.ar +gov.ar +int.ar +mil.ar +net.ar +org.ar +tur.ar + +// arpa : http://en.wikipedia.org/wiki/.arpa +// Confirmed by registry 2008-06-18 +arpa +e164.arpa +in-addr.arpa +ip6.arpa +iris.arpa +uri.arpa +urn.arpa + +// as : http://en.wikipedia.org/wiki/.as +as +gov.as + +// asia : http://en.wikipedia.org/wiki/.asia +asia + +// at : http://en.wikipedia.org/wiki/.at +// Confirmed by registry 2008-06-17 +at +ac.at +co.at +gv.at +or.at + +// au : http://en.wikipedia.org/wiki/.au +// http://www.auda.org.au/ +au +// 2LDs +com.au +net.au +org.au +edu.au +gov.au +asn.au +id.au +// Historic 2LDs (closed to new registration, but sites still exist) +info.au +conf.au +oz.au +// CGDNs - http://www.cgdn.org.au/ +act.au +nsw.au +nt.au +qld.au +sa.au +tas.au +vic.au +wa.au +// 3LDs +act.edu.au +nsw.edu.au +nt.edu.au +qld.edu.au +sa.edu.au +tas.edu.au +vic.edu.au +wa.edu.au +// act.gov.au Bug 984824 - Removed at request of Greg Tankard +// nsw.gov.au Bug 547985 - Removed at request of +// nt.gov.au Bug 940478 - Removed at request of Greg Connors +qld.gov.au +sa.gov.au +tas.gov.au +vic.gov.au +wa.gov.au + +// aw : http://en.wikipedia.org/wiki/.aw +aw +com.aw + +// ax : http://en.wikipedia.org/wiki/.ax +ax + +// az : http://en.wikipedia.org/wiki/.az +az +com.az +net.az +int.az +gov.az +org.az +edu.az +info.az +pp.az +mil.az +name.az +pro.az +biz.az + +// ba : http://en.wikipedia.org/wiki/.ba +ba +org.ba +net.ba +edu.ba +gov.ba +mil.ba +unsa.ba +unbi.ba +co.ba +com.ba +rs.ba + +// bb : http://en.wikipedia.org/wiki/.bb +bb +biz.bb +co.bb +com.bb +edu.bb +gov.bb +info.bb +net.bb +org.bb +store.bb +tv.bb + +// bd : http://en.wikipedia.org/wiki/.bd +*.bd + +// be : http://en.wikipedia.org/wiki/.be +// Confirmed by registry 2008-06-08 +be +ac.be + +// bf : http://en.wikipedia.org/wiki/.bf +bf +gov.bf + +// bg : http://en.wikipedia.org/wiki/.bg +// https://www.register.bg/user/static/rules/en/index.html +bg +a.bg +b.bg +c.bg +d.bg +e.bg +f.bg +g.bg +h.bg +i.bg +j.bg +k.bg +l.bg +m.bg +n.bg +o.bg +p.bg +q.bg +r.bg +s.bg +t.bg +u.bg +v.bg +w.bg +x.bg +y.bg +z.bg +0.bg +1.bg +2.bg +3.bg +4.bg +5.bg +6.bg +7.bg +8.bg +9.bg + +// bh : http://en.wikipedia.org/wiki/.bh +bh +com.bh +edu.bh +net.bh +org.bh +gov.bh + +// bi : http://en.wikipedia.org/wiki/.bi +// http://whois.nic.bi/ +bi +co.bi +com.bi +edu.bi +or.bi +org.bi + +// biz : http://en.wikipedia.org/wiki/.biz +biz + +// bj : http://en.wikipedia.org/wiki/.bj +bj +asso.bj +barreau.bj +gouv.bj + +// bm : http://www.bermudanic.bm/dnr-text.txt +bm +com.bm +edu.bm +gov.bm +net.bm +org.bm + +// bn : http://en.wikipedia.org/wiki/.bn +*.bn + +// bo : http://www.nic.bo/ +bo +com.bo +edu.bo +gov.bo +gob.bo +int.bo +org.bo +net.bo +mil.bo +tv.bo + +// br : http://registro.br/dominio/categoria.html +// Submitted by registry 2014-08-11 +br +adm.br +adv.br +agr.br +am.br +arq.br +art.br +ato.br +b.br +bio.br +blog.br +bmd.br +cim.br +cng.br +cnt.br +com.br +coop.br +ecn.br +eco.br +edu.br +emp.br +eng.br +esp.br +etc.br +eti.br +far.br +flog.br +fm.br +fnd.br +fot.br +fst.br +g12.br +ggf.br +gov.br +imb.br +ind.br +inf.br +jor.br +jus.br +leg.br +lel.br +mat.br +med.br +mil.br +mp.br +mus.br +net.br +*.nom.br +not.br +ntr.br +odo.br +org.br +ppg.br +pro.br +psc.br +psi.br +qsl.br +radio.br +rec.br +slg.br +srv.br +taxi.br +teo.br +tmp.br +trd.br +tur.br +tv.br +vet.br +vlog.br +wiki.br +zlg.br + +// bs : http://www.nic.bs/rules.html +bs +com.bs +net.bs +org.bs +edu.bs +gov.bs + +// bt : http://en.wikipedia.org/wiki/.bt +bt +com.bt +edu.bt +gov.bt +net.bt +org.bt + +// bv : No registrations at this time. +// Submitted by registry 2006-06-16 +bv + +// bw : http://en.wikipedia.org/wiki/.bw +// http://www.gobin.info/domainname/bw.doc +// list of other 2nd level tlds ? +bw +co.bw +org.bw + +// by : http://en.wikipedia.org/wiki/.by +// http://tld.by/rules_2006_en.html +// list of other 2nd level tlds ? +by +gov.by +mil.by +// Official information does not indicate that com.by is a reserved +// second-level domain, but it's being used as one (see www.google.com.by and +// www.yahoo.com.by, for example), so we list it here for safety's sake. +com.by + +// http://hoster.by/ +of.by + +// bz : http://en.wikipedia.org/wiki/.bz +// http://www.belizenic.bz/ +bz +com.bz +net.bz +org.bz +edu.bz +gov.bz + +// ca : http://en.wikipedia.org/wiki/.ca +ca +// ca geographical names +ab.ca +bc.ca +mb.ca +nb.ca +nf.ca +nl.ca +ns.ca +nt.ca +nu.ca +on.ca +pe.ca +qc.ca +sk.ca +yk.ca +// gc.ca: http://en.wikipedia.org/wiki/.gc.ca +// see also: http://registry.gc.ca/en/SubdomainFAQ +gc.ca + +// cat : http://en.wikipedia.org/wiki/.cat +cat + +// cc : http://en.wikipedia.org/wiki/.cc +cc + +// cd : http://en.wikipedia.org/wiki/.cd +// see also: https://www.nic.cd/domain/insertDomain_2.jsp?act=1 +cd +gov.cd + +// cf : http://en.wikipedia.org/wiki/.cf +cf + +// cg : http://en.wikipedia.org/wiki/.cg +cg + +// ch : http://en.wikipedia.org/wiki/.ch +ch + +// ci : http://en.wikipedia.org/wiki/.ci +// http://www.nic.ci/index.php?page=charte +ci +org.ci +or.ci +com.ci +co.ci +edu.ci +ed.ci +ac.ci +net.ci +go.ci +asso.ci +aéroport.ci +int.ci +presse.ci +md.ci +gouv.ci + +// ck : http://en.wikipedia.org/wiki/.ck +*.ck +!www.ck + +// cl : http://en.wikipedia.org/wiki/.cl +cl +gov.cl +gob.cl +co.cl +mil.cl + +// cm : http://en.wikipedia.org/wiki/.cm plus bug 981927 +cm +co.cm +com.cm +gov.cm +net.cm + +// cn : http://en.wikipedia.org/wiki/.cn +// Submitted by registry 2008-06-11 +cn +ac.cn +com.cn +edu.cn +gov.cn +net.cn +org.cn +mil.cn +公司.cn +网络.cn +網絡.cn +// cn geographic names +ah.cn +bj.cn +cq.cn +fj.cn +gd.cn +gs.cn +gz.cn +gx.cn +ha.cn +hb.cn +he.cn +hi.cn +hl.cn +hn.cn +jl.cn +js.cn +jx.cn +ln.cn +nm.cn +nx.cn +qh.cn +sc.cn +sd.cn +sh.cn +sn.cn +sx.cn +tj.cn +xj.cn +xz.cn +yn.cn +zj.cn +hk.cn +mo.cn +tw.cn + +// co : http://en.wikipedia.org/wiki/.co +// Submitted by registry 2008-06-11 +co +arts.co +com.co +edu.co +firm.co +gov.co +info.co +int.co +mil.co +net.co +nom.co +org.co +rec.co +web.co + +// com : http://en.wikipedia.org/wiki/.com +com + +// coop : http://en.wikipedia.org/wiki/.coop +coop + +// cr : http://www.nic.cr/niccr_publico/showRegistroDominiosScreen.do +cr +ac.cr +co.cr +ed.cr +fi.cr +go.cr +or.cr +sa.cr + +// cu : http://en.wikipedia.org/wiki/.cu +cu +com.cu +edu.cu +org.cu +net.cu +gov.cu +inf.cu + +// cv : http://en.wikipedia.org/wiki/.cv +cv + +// cw : http://www.una.cw/cw_registry/ +// Confirmed by registry 2013-03-26 +cw +com.cw +edu.cw +net.cw +org.cw + +// cx : http://en.wikipedia.org/wiki/.cx +// list of other 2nd level tlds ? +cx +gov.cx + +// cy : http://en.wikipedia.org/wiki/.cy +*.cy + +// cz : http://en.wikipedia.org/wiki/.cz +cz + +// de : http://en.wikipedia.org/wiki/.de +// Confirmed by registry (with technical +// reservations) 2008-07-01 +de + +// dj : http://en.wikipedia.org/wiki/.dj +dj + +// dk : http://en.wikipedia.org/wiki/.dk +// Confirmed by registry 2008-06-17 +dk + +// dm : http://en.wikipedia.org/wiki/.dm +dm +com.dm +net.dm +org.dm +edu.dm +gov.dm + +// do : http://en.wikipedia.org/wiki/.do +do +art.do +com.do +edu.do +gob.do +gov.do +mil.do +net.do +org.do +sld.do +web.do + +// dz : http://en.wikipedia.org/wiki/.dz +dz +com.dz +org.dz +net.dz +gov.dz +edu.dz +asso.dz +pol.dz +art.dz + +// ec : http://www.nic.ec/reg/paso1.asp +// Submitted by registry 2008-07-04 +ec +com.ec +info.ec +net.ec +fin.ec +k12.ec +med.ec +pro.ec +org.ec +edu.ec +gov.ec +gob.ec +mil.ec + +// edu : http://en.wikipedia.org/wiki/.edu +edu + +// ee : http://www.eenet.ee/EENet/dom_reeglid.html#lisa_B +ee +edu.ee +gov.ee +riik.ee +lib.ee +med.ee +com.ee +pri.ee +aip.ee +org.ee +fie.ee + +// eg : http://en.wikipedia.org/wiki/.eg +eg +com.eg +edu.eg +eun.eg +gov.eg +mil.eg +name.eg +net.eg +org.eg +sci.eg + +// er : http://en.wikipedia.org/wiki/.er +*.er + +// es : https://www.nic.es/site_ingles/ingles/dominios/index.html +es +com.es +nom.es +org.es +gob.es +edu.es + +// et : http://en.wikipedia.org/wiki/.et +et +com.et +gov.et +org.et +edu.et +biz.et +name.et +info.et + +// eu : http://en.wikipedia.org/wiki/.eu +eu + +// fi : http://en.wikipedia.org/wiki/.fi +fi +// aland.fi : http://en.wikipedia.org/wiki/.ax +// This domain is being phased out in favor of .ax. As there are still many +// domains under aland.fi, we still keep it on the list until aland.fi is +// completely removed. +// TODO: Check for updates (expected to be phased out around Q1/2009) +aland.fi + +// fj : http://en.wikipedia.org/wiki/.fj +*.fj + +// fk : http://en.wikipedia.org/wiki/.fk +*.fk + +// fm : http://en.wikipedia.org/wiki/.fm +fm + +// fo : http://en.wikipedia.org/wiki/.fo +fo + +// fr : http://www.afnic.fr/ +// domaines descriptifs : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-descriptifs +fr +com.fr +asso.fr +nom.fr +prd.fr +presse.fr +tm.fr +// domaines sectoriels : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-sectoriels +aeroport.fr +assedic.fr +avocat.fr +avoues.fr +cci.fr +chambagri.fr +chirurgiens-dentistes.fr +experts-comptables.fr +geometre-expert.fr +gouv.fr +greta.fr +huissier-justice.fr +medecin.fr +notaires.fr +pharmacien.fr +port.fr +veterinaire.fr + +// ga : http://en.wikipedia.org/wiki/.ga +ga + +// gb : This registry is effectively dormant +// Submitted by registry 2008-06-12 +gb + +// gd : http://en.wikipedia.org/wiki/.gd +gd + +// ge : http://www.nic.net.ge/policy_en.pdf +ge +com.ge +edu.ge +gov.ge +org.ge +mil.ge +net.ge +pvt.ge + +// gf : http://en.wikipedia.org/wiki/.gf +gf + +// gg : http://www.channelisles.net/register-domains/ +// Confirmed by registry 2013-11-28 +gg +co.gg +net.gg +org.gg + +// gh : http://en.wikipedia.org/wiki/.gh +// see also: http://www.nic.gh/reg_now.php +// Although domains directly at second level are not possible at the moment, +// they have been possible for some time and may come back. +gh +com.gh +edu.gh +gov.gh +org.gh +mil.gh + +// gi : http://www.nic.gi/rules.html +gi +com.gi +ltd.gi +gov.gi +mod.gi +edu.gi +org.gi + +// gl : http://en.wikipedia.org/wiki/.gl +// http://nic.gl +gl + +// gm : http://www.nic.gm/htmlpages%5Cgm-policy.htm +gm + +// gn : http://psg.com/dns/gn/gn.txt +// Submitted by registry 2008-06-17 +gn +ac.gn +com.gn +edu.gn +gov.gn +org.gn +net.gn + +// gov : http://en.wikipedia.org/wiki/.gov +gov + +// gp : http://www.nic.gp/index.php?lang=en +gp +com.gp +net.gp +mobi.gp +edu.gp +org.gp +asso.gp + +// gq : http://en.wikipedia.org/wiki/.gq +gq + +// gr : https://grweb.ics.forth.gr/english/1617-B-2005.html +// Submitted by registry 2008-06-09 +gr +com.gr +edu.gr +net.gr +org.gr +gov.gr + +// gs : http://en.wikipedia.org/wiki/.gs +gs + +// gt : http://www.gt/politicas_de_registro.html +gt +com.gt +edu.gt +gob.gt +ind.gt +mil.gt +net.gt +org.gt + +// gu : http://gadao.gov.gu/registration.txt +*.gu + +// gw : http://en.wikipedia.org/wiki/.gw +gw + +// gy : http://en.wikipedia.org/wiki/.gy +// http://registry.gy/ +gy +co.gy +com.gy +net.gy + +// hk : https://www.hkdnr.hk +// Submitted by registry 2008-06-11 +hk +com.hk +edu.hk +gov.hk +idv.hk +net.hk +org.hk +公司.hk +教育.hk +敎育.hk +政府.hk +個人.hk +个人.hk +箇人.hk +網络.hk +网络.hk +组織.hk +網絡.hk +网絡.hk +组织.hk +組織.hk +組织.hk + +// hm : http://en.wikipedia.org/wiki/.hm +hm + +// hn : http://www.nic.hn/politicas/ps02,,05.html +hn +com.hn +edu.hn +org.hn +net.hn +mil.hn +gob.hn + +// hr : http://www.dns.hr/documents/pdf/HRTLD-regulations.pdf +hr +iz.hr +from.hr +name.hr +com.hr + +// ht : http://www.nic.ht/info/charte.cfm +ht +com.ht +shop.ht +firm.ht +info.ht +adult.ht +net.ht +pro.ht +org.ht +med.ht +art.ht +coop.ht +pol.ht +asso.ht +edu.ht +rel.ht +gouv.ht +perso.ht + +// hu : http://www.domain.hu/domain/English/sld.html +// Confirmed by registry 2008-06-12 +hu +co.hu +info.hu +org.hu +priv.hu +sport.hu +tm.hu +2000.hu +agrar.hu +bolt.hu +casino.hu +city.hu +erotica.hu +erotika.hu +film.hu +forum.hu +games.hu +hotel.hu +ingatlan.hu +jogasz.hu +konyvelo.hu +lakas.hu +media.hu +news.hu +reklam.hu +sex.hu +shop.hu +suli.hu +szex.hu +tozsde.hu +utazas.hu +video.hu + +// id : https://register.pandi.or.id/ +id +ac.id +biz.id +co.id +desa.id +go.id +mil.id +my.id +net.id +or.id +sch.id +web.id + +// ie : http://en.wikipedia.org/wiki/.ie +ie +gov.ie + +// il : http://en.wikipedia.org/wiki/.il +*.il + +// im : https://www.nic.im/ +// Submitted by registry 2013-11-15 +im +ac.im +co.im +com.im +ltd.co.im +net.im +org.im +plc.co.im +tt.im +tv.im + +// in : http://en.wikipedia.org/wiki/.in +// see also: https://registry.in/Policies +// Please note, that nic.in is not an offical eTLD, but used by most +// government institutions. +in +co.in +firm.in +net.in +org.in +gen.in +ind.in +nic.in +ac.in +edu.in +res.in +gov.in +mil.in + +// info : http://en.wikipedia.org/wiki/.info +info + +// int : http://en.wikipedia.org/wiki/.int +// Confirmed by registry 2008-06-18 +int +eu.int + +// io : http://www.nic.io/rules.html +// list of other 2nd level tlds ? +io +com.io + +// iq : http://www.cmc.iq/english/iq/iqregister1.htm +iq +gov.iq +edu.iq +mil.iq +com.iq +org.iq +net.iq + +// ir : http://www.nic.ir/Terms_and_Conditions_ir,_Appendix_1_Domain_Rules +// Also see http://www.nic.ir/Internationalized_Domain_Names +// Two .ir entries added at request of , 2010-04-16 +ir +ac.ir +co.ir +gov.ir +id.ir +net.ir +org.ir +sch.ir +// xn--mgba3a4f16a.ir (.ir, Persian YEH) +ایران.ir +// xn--mgba3a4fra.ir (.ir, Arabic YEH) +ايران.ir + +// is : http://www.isnic.is/domain/rules.php +// Confirmed by registry 2008-12-06 +is +net.is +com.is +edu.is +gov.is +org.is +int.is + +// it : http://en.wikipedia.org/wiki/.it +it +gov.it +edu.it +// Reserved geo-names: +// http://www.nic.it/documenti/regolamenti-e-linee-guida/regolamento-assegnazione-versione-6.0.pdf +// There is also a list of reserved geo-names corresponding to Italian municipalities +// http://www.nic.it/documenti/appendice-c.pdf, but it is not included here. +// Regions +abr.it +abruzzo.it +aosta-valley.it +aostavalley.it +bas.it +basilicata.it +cal.it +calabria.it +cam.it +campania.it +emilia-romagna.it +emiliaromagna.it +emr.it +friuli-v-giulia.it +friuli-ve-giulia.it +friuli-vegiulia.it +friuli-venezia-giulia.it +friuli-veneziagiulia.it +friuli-vgiulia.it +friuliv-giulia.it +friulive-giulia.it +friulivegiulia.it +friulivenezia-giulia.it +friuliveneziagiulia.it +friulivgiulia.it +fvg.it +laz.it +lazio.it +lig.it +liguria.it +lom.it +lombardia.it +lombardy.it +lucania.it +mar.it +marche.it +mol.it +molise.it +piedmont.it +piemonte.it +pmn.it +pug.it +puglia.it +sar.it +sardegna.it +sardinia.it +sic.it +sicilia.it +sicily.it +taa.it +tos.it +toscana.it +trentino-a-adige.it +trentino-aadige.it +trentino-alto-adige.it +trentino-altoadige.it +trentino-s-tirol.it +trentino-stirol.it +trentino-sud-tirol.it +trentino-sudtirol.it +trentino-sued-tirol.it +trentino-suedtirol.it +trentinoa-adige.it +trentinoaadige.it +trentinoalto-adige.it +trentinoaltoadige.it +trentinos-tirol.it +trentinostirol.it +trentinosud-tirol.it +trentinosudtirol.it +trentinosued-tirol.it +trentinosuedtirol.it +tuscany.it +umb.it +umbria.it +val-d-aosta.it +val-daosta.it +vald-aosta.it +valdaosta.it +valle-aosta.it +valle-d-aosta.it +valle-daosta.it +valleaosta.it +valled-aosta.it +valledaosta.it +vallee-aoste.it +valleeaoste.it +vao.it +vda.it +ven.it +veneto.it +// Provinces +ag.it +agrigento.it +al.it +alessandria.it +alto-adige.it +altoadige.it +an.it +ancona.it +andria-barletta-trani.it +andria-trani-barletta.it +andriabarlettatrani.it +andriatranibarletta.it +ao.it +aosta.it +aoste.it +ap.it +aq.it +aquila.it +ar.it +arezzo.it +ascoli-piceno.it +ascolipiceno.it +asti.it +at.it +av.it +avellino.it +ba.it +balsan.it +bari.it +barletta-trani-andria.it +barlettatraniandria.it +belluno.it +benevento.it +bergamo.it +bg.it +bi.it +biella.it +bl.it +bn.it +bo.it +bologna.it +bolzano.it +bozen.it +br.it +brescia.it +brindisi.it +bs.it +bt.it +bz.it +ca.it +cagliari.it +caltanissetta.it +campidano-medio.it +campidanomedio.it +campobasso.it +carbonia-iglesias.it +carboniaiglesias.it +carrara-massa.it +carraramassa.it +caserta.it +catania.it +catanzaro.it +cb.it +ce.it +cesena-forli.it +cesenaforli.it +ch.it +chieti.it +ci.it +cl.it +cn.it +co.it +como.it +cosenza.it +cr.it +cremona.it +crotone.it +cs.it +ct.it +cuneo.it +cz.it +dell-ogliastra.it +dellogliastra.it +en.it +enna.it +fc.it +fe.it +fermo.it +ferrara.it +fg.it +fi.it +firenze.it +florence.it +fm.it +foggia.it +forli-cesena.it +forlicesena.it +fr.it +frosinone.it +ge.it +genoa.it +genova.it +go.it +gorizia.it +gr.it +grosseto.it +iglesias-carbonia.it +iglesiascarbonia.it +im.it +imperia.it +is.it +isernia.it +kr.it +la-spezia.it +laquila.it +laspezia.it +latina.it +lc.it +le.it +lecce.it +lecco.it +li.it +livorno.it +lo.it +lodi.it +lt.it +lu.it +lucca.it +macerata.it +mantova.it +massa-carrara.it +massacarrara.it +matera.it +mb.it +mc.it +me.it +medio-campidano.it +mediocampidano.it +messina.it +mi.it +milan.it +milano.it +mn.it +mo.it +modena.it +monza-brianza.it +monza-e-della-brianza.it +monza.it +monzabrianza.it +monzaebrianza.it +monzaedellabrianza.it +ms.it +mt.it +na.it +naples.it +napoli.it +no.it +novara.it +nu.it +nuoro.it +og.it +ogliastra.it +olbia-tempio.it +olbiatempio.it +or.it +oristano.it +ot.it +pa.it +padova.it +padua.it +palermo.it +parma.it +pavia.it +pc.it +pd.it +pe.it +perugia.it +pesaro-urbino.it +pesarourbino.it +pescara.it +pg.it +pi.it +piacenza.it +pisa.it +pistoia.it +pn.it +po.it +pordenone.it +potenza.it +pr.it +prato.it +pt.it +pu.it +pv.it +pz.it +ra.it +ragusa.it +ravenna.it +rc.it +re.it +reggio-calabria.it +reggio-emilia.it +reggiocalabria.it +reggioemilia.it +rg.it +ri.it +rieti.it +rimini.it +rm.it +rn.it +ro.it +roma.it +rome.it +rovigo.it +sa.it +salerno.it +sassari.it +savona.it +si.it +siena.it +siracusa.it +so.it +sondrio.it +sp.it +sr.it +ss.it +suedtirol.it +sv.it +ta.it +taranto.it +te.it +tempio-olbia.it +tempioolbia.it +teramo.it +terni.it +tn.it +to.it +torino.it +tp.it +tr.it +trani-andria-barletta.it +trani-barletta-andria.it +traniandriabarletta.it +tranibarlettaandria.it +trapani.it +trentino.it +trento.it +treviso.it +trieste.it +ts.it +turin.it +tv.it +ud.it +udine.it +urbino-pesaro.it +urbinopesaro.it +va.it +varese.it +vb.it +vc.it +ve.it +venezia.it +venice.it +verbania.it +vercelli.it +verona.it +vi.it +vibo-valentia.it +vibovalentia.it +vicenza.it +viterbo.it +vr.it +vs.it +vt.it +vv.it + +// je : http://www.channelisles.net/register-domains/ +// Confirmed by registry 2013-11-28 +je +co.je +net.je +org.je + +// jm : http://www.com.jm/register.html +*.jm + +// jo : http://www.dns.jo/Registration_policy.aspx +jo +com.jo +org.jo +net.jo +edu.jo +sch.jo +gov.jo +mil.jo +name.jo + +// jobs : http://en.wikipedia.org/wiki/.jobs +jobs + +// jp : http://en.wikipedia.org/wiki/.jp +// http://jprs.co.jp/en/jpdomain.html +// Submitted by registry 2014-10-30 +jp +// jp organizational type names +ac.jp +ad.jp +co.jp +ed.jp +go.jp +gr.jp +lg.jp +ne.jp +or.jp +// jp prefecture type names +aichi.jp +akita.jp +aomori.jp +chiba.jp +ehime.jp +fukui.jp +fukuoka.jp +fukushima.jp +gifu.jp +gunma.jp +hiroshima.jp +hokkaido.jp +hyogo.jp +ibaraki.jp +ishikawa.jp +iwate.jp +kagawa.jp +kagoshima.jp +kanagawa.jp +kochi.jp +kumamoto.jp +kyoto.jp +mie.jp +miyagi.jp +miyazaki.jp +nagano.jp +nagasaki.jp +nara.jp +niigata.jp +oita.jp +okayama.jp +okinawa.jp +osaka.jp +saga.jp +saitama.jp +shiga.jp +shimane.jp +shizuoka.jp +tochigi.jp +tokushima.jp +tokyo.jp +tottori.jp +toyama.jp +wakayama.jp +yamagata.jp +yamaguchi.jp +yamanashi.jp +栃木.jp +愛知.jp +愛媛.jp +兵庫.jp +熊本.jp +茨城.jp +北海道.jp +千葉.jp +和歌山.jp +長崎.jp +長野.jp +新潟.jp +青森.jp +静岡.jp +東京.jp +石川.jp +埼玉.jp +三重.jp +京都.jp +佐賀.jp +大分.jp +大阪.jp +奈良.jp +宮城.jp +宮崎.jp +富山.jp +山口.jp +山形.jp +山梨.jp +岩手.jp +岐阜.jp +岡山.jp +島根.jp +広島.jp +徳島.jp +沖縄.jp +滋賀.jp +神奈川.jp +福井.jp +福岡.jp +福島.jp +秋田.jp +群馬.jp +香川.jp +高知.jp +鳥取.jp +鹿児島.jp +// jp geographic type names +// http://jprs.jp/doc/rule/saisoku-1.html +*.kawasaki.jp +*.kitakyushu.jp +*.kobe.jp +*.nagoya.jp +*.sapporo.jp +*.sendai.jp +*.yokohama.jp +!city.kawasaki.jp +!city.kitakyushu.jp +!city.kobe.jp +!city.nagoya.jp +!city.sapporo.jp +!city.sendai.jp +!city.yokohama.jp +// 4th level registration +aisai.aichi.jp +ama.aichi.jp +anjo.aichi.jp +asuke.aichi.jp +chiryu.aichi.jp +chita.aichi.jp +fuso.aichi.jp +gamagori.aichi.jp +handa.aichi.jp +hazu.aichi.jp +hekinan.aichi.jp +higashiura.aichi.jp +ichinomiya.aichi.jp +inazawa.aichi.jp +inuyama.aichi.jp +isshiki.aichi.jp +iwakura.aichi.jp +kanie.aichi.jp +kariya.aichi.jp +kasugai.aichi.jp +kira.aichi.jp +kiyosu.aichi.jp +komaki.aichi.jp +konan.aichi.jp +kota.aichi.jp +mihama.aichi.jp +miyoshi.aichi.jp +nishio.aichi.jp +nisshin.aichi.jp +obu.aichi.jp +oguchi.aichi.jp +oharu.aichi.jp +okazaki.aichi.jp +owariasahi.aichi.jp +seto.aichi.jp +shikatsu.aichi.jp +shinshiro.aichi.jp +shitara.aichi.jp +tahara.aichi.jp +takahama.aichi.jp +tobishima.aichi.jp +toei.aichi.jp +togo.aichi.jp +tokai.aichi.jp +tokoname.aichi.jp +toyoake.aichi.jp +toyohashi.aichi.jp +toyokawa.aichi.jp +toyone.aichi.jp +toyota.aichi.jp +tsushima.aichi.jp +yatomi.aichi.jp +akita.akita.jp +daisen.akita.jp +fujisato.akita.jp +gojome.akita.jp +hachirogata.akita.jp +happou.akita.jp +higashinaruse.akita.jp +honjo.akita.jp +honjyo.akita.jp +ikawa.akita.jp +kamikoani.akita.jp +kamioka.akita.jp +katagami.akita.jp +kazuno.akita.jp +kitaakita.akita.jp +kosaka.akita.jp +kyowa.akita.jp +misato.akita.jp +mitane.akita.jp +moriyoshi.akita.jp +nikaho.akita.jp +noshiro.akita.jp +odate.akita.jp +oga.akita.jp +ogata.akita.jp +semboku.akita.jp +yokote.akita.jp +yurihonjo.akita.jp +aomori.aomori.jp +gonohe.aomori.jp +hachinohe.aomori.jp +hashikami.aomori.jp +hiranai.aomori.jp +hirosaki.aomori.jp +itayanagi.aomori.jp +kuroishi.aomori.jp +misawa.aomori.jp +mutsu.aomori.jp +nakadomari.aomori.jp +noheji.aomori.jp +oirase.aomori.jp +owani.aomori.jp +rokunohe.aomori.jp +sannohe.aomori.jp +shichinohe.aomori.jp +shingo.aomori.jp +takko.aomori.jp +towada.aomori.jp +tsugaru.aomori.jp +tsuruta.aomori.jp +abiko.chiba.jp +asahi.chiba.jp +chonan.chiba.jp +chosei.chiba.jp +choshi.chiba.jp +chuo.chiba.jp +funabashi.chiba.jp +futtsu.chiba.jp +hanamigawa.chiba.jp +ichihara.chiba.jp +ichikawa.chiba.jp +ichinomiya.chiba.jp +inzai.chiba.jp +isumi.chiba.jp +kamagaya.chiba.jp +kamogawa.chiba.jp +kashiwa.chiba.jp +katori.chiba.jp +katsuura.chiba.jp +kimitsu.chiba.jp +kisarazu.chiba.jp +kozaki.chiba.jp +kujukuri.chiba.jp +kyonan.chiba.jp +matsudo.chiba.jp +midori.chiba.jp +mihama.chiba.jp +minamiboso.chiba.jp +mobara.chiba.jp +mutsuzawa.chiba.jp +nagara.chiba.jp +nagareyama.chiba.jp +narashino.chiba.jp +narita.chiba.jp +noda.chiba.jp +oamishirasato.chiba.jp +omigawa.chiba.jp +onjuku.chiba.jp +otaki.chiba.jp +sakae.chiba.jp +sakura.chiba.jp +shimofusa.chiba.jp +shirako.chiba.jp +shiroi.chiba.jp +shisui.chiba.jp +sodegaura.chiba.jp +sosa.chiba.jp +tako.chiba.jp +tateyama.chiba.jp +togane.chiba.jp +tohnosho.chiba.jp +tomisato.chiba.jp +urayasu.chiba.jp +yachimata.chiba.jp +yachiyo.chiba.jp +yokaichiba.chiba.jp +yokoshibahikari.chiba.jp +yotsukaido.chiba.jp +ainan.ehime.jp +honai.ehime.jp +ikata.ehime.jp +imabari.ehime.jp +iyo.ehime.jp +kamijima.ehime.jp +kihoku.ehime.jp +kumakogen.ehime.jp +masaki.ehime.jp +matsuno.ehime.jp +matsuyama.ehime.jp +namikata.ehime.jp +niihama.ehime.jp +ozu.ehime.jp +saijo.ehime.jp +seiyo.ehime.jp +shikokuchuo.ehime.jp +tobe.ehime.jp +toon.ehime.jp +uchiko.ehime.jp +uwajima.ehime.jp +yawatahama.ehime.jp +echizen.fukui.jp +eiheiji.fukui.jp +fukui.fukui.jp +ikeda.fukui.jp +katsuyama.fukui.jp +mihama.fukui.jp +minamiechizen.fukui.jp +obama.fukui.jp +ohi.fukui.jp +ono.fukui.jp +sabae.fukui.jp +sakai.fukui.jp +takahama.fukui.jp +tsuruga.fukui.jp +wakasa.fukui.jp +ashiya.fukuoka.jp +buzen.fukuoka.jp +chikugo.fukuoka.jp +chikuho.fukuoka.jp +chikujo.fukuoka.jp +chikushino.fukuoka.jp +chikuzen.fukuoka.jp +chuo.fukuoka.jp +dazaifu.fukuoka.jp +fukuchi.fukuoka.jp +hakata.fukuoka.jp +higashi.fukuoka.jp +hirokawa.fukuoka.jp +hisayama.fukuoka.jp +iizuka.fukuoka.jp +inatsuki.fukuoka.jp +kaho.fukuoka.jp +kasuga.fukuoka.jp +kasuya.fukuoka.jp +kawara.fukuoka.jp +keisen.fukuoka.jp +koga.fukuoka.jp +kurate.fukuoka.jp +kurogi.fukuoka.jp +kurume.fukuoka.jp +minami.fukuoka.jp +miyako.fukuoka.jp +miyama.fukuoka.jp +miyawaka.fukuoka.jp +mizumaki.fukuoka.jp +munakata.fukuoka.jp +nakagawa.fukuoka.jp +nakama.fukuoka.jp +nishi.fukuoka.jp +nogata.fukuoka.jp +ogori.fukuoka.jp +okagaki.fukuoka.jp +okawa.fukuoka.jp +oki.fukuoka.jp +omuta.fukuoka.jp +onga.fukuoka.jp +onojo.fukuoka.jp +oto.fukuoka.jp +saigawa.fukuoka.jp +sasaguri.fukuoka.jp +shingu.fukuoka.jp +shinyoshitomi.fukuoka.jp +shonai.fukuoka.jp +soeda.fukuoka.jp +sue.fukuoka.jp +tachiarai.fukuoka.jp +tagawa.fukuoka.jp +takata.fukuoka.jp +toho.fukuoka.jp +toyotsu.fukuoka.jp +tsuiki.fukuoka.jp +ukiha.fukuoka.jp +umi.fukuoka.jp +usui.fukuoka.jp +yamada.fukuoka.jp +yame.fukuoka.jp +yanagawa.fukuoka.jp +yukuhashi.fukuoka.jp +aizubange.fukushima.jp +aizumisato.fukushima.jp +aizuwakamatsu.fukushima.jp +asakawa.fukushima.jp +bandai.fukushima.jp +date.fukushima.jp +fukushima.fukushima.jp +furudono.fukushima.jp +futaba.fukushima.jp +hanawa.fukushima.jp +higashi.fukushima.jp +hirata.fukushima.jp +hirono.fukushima.jp +iitate.fukushima.jp +inawashiro.fukushima.jp +ishikawa.fukushima.jp +iwaki.fukushima.jp +izumizaki.fukushima.jp +kagamiishi.fukushima.jp +kaneyama.fukushima.jp +kawamata.fukushima.jp +kitakata.fukushima.jp +kitashiobara.fukushima.jp +koori.fukushima.jp +koriyama.fukushima.jp +kunimi.fukushima.jp +miharu.fukushima.jp +mishima.fukushima.jp +namie.fukushima.jp +nango.fukushima.jp +nishiaizu.fukushima.jp +nishigo.fukushima.jp +okuma.fukushima.jp +omotego.fukushima.jp +ono.fukushima.jp +otama.fukushima.jp +samegawa.fukushima.jp +shimogo.fukushima.jp +shirakawa.fukushima.jp +showa.fukushima.jp +soma.fukushima.jp +sukagawa.fukushima.jp +taishin.fukushima.jp +tamakawa.fukushima.jp +tanagura.fukushima.jp +tenei.fukushima.jp +yabuki.fukushima.jp +yamato.fukushima.jp +yamatsuri.fukushima.jp +yanaizu.fukushima.jp +yugawa.fukushima.jp +anpachi.gifu.jp +ena.gifu.jp +gifu.gifu.jp +ginan.gifu.jp +godo.gifu.jp +gujo.gifu.jp +hashima.gifu.jp +hichiso.gifu.jp +hida.gifu.jp +higashishirakawa.gifu.jp +ibigawa.gifu.jp +ikeda.gifu.jp +kakamigahara.gifu.jp +kani.gifu.jp +kasahara.gifu.jp +kasamatsu.gifu.jp +kawaue.gifu.jp +kitagata.gifu.jp +mino.gifu.jp +minokamo.gifu.jp +mitake.gifu.jp +mizunami.gifu.jp +motosu.gifu.jp +nakatsugawa.gifu.jp +ogaki.gifu.jp +sakahogi.gifu.jp +seki.gifu.jp +sekigahara.gifu.jp +shirakawa.gifu.jp +tajimi.gifu.jp +takayama.gifu.jp +tarui.gifu.jp +toki.gifu.jp +tomika.gifu.jp +wanouchi.gifu.jp +yamagata.gifu.jp +yaotsu.gifu.jp +yoro.gifu.jp +annaka.gunma.jp +chiyoda.gunma.jp +fujioka.gunma.jp +higashiagatsuma.gunma.jp +isesaki.gunma.jp +itakura.gunma.jp +kanna.gunma.jp +kanra.gunma.jp +katashina.gunma.jp +kawaba.gunma.jp +kiryu.gunma.jp +kusatsu.gunma.jp +maebashi.gunma.jp +meiwa.gunma.jp +midori.gunma.jp +minakami.gunma.jp +naganohara.gunma.jp +nakanojo.gunma.jp +nanmoku.gunma.jp +numata.gunma.jp +oizumi.gunma.jp +ora.gunma.jp +ota.gunma.jp +shibukawa.gunma.jp +shimonita.gunma.jp +shinto.gunma.jp +showa.gunma.jp +takasaki.gunma.jp +takayama.gunma.jp +tamamura.gunma.jp +tatebayashi.gunma.jp +tomioka.gunma.jp +tsukiyono.gunma.jp +tsumagoi.gunma.jp +ueno.gunma.jp +yoshioka.gunma.jp +asaminami.hiroshima.jp +daiwa.hiroshima.jp +etajima.hiroshima.jp +fuchu.hiroshima.jp +fukuyama.hiroshima.jp +hatsukaichi.hiroshima.jp +higashihiroshima.hiroshima.jp +hongo.hiroshima.jp +jinsekikogen.hiroshima.jp +kaita.hiroshima.jp +kui.hiroshima.jp +kumano.hiroshima.jp +kure.hiroshima.jp +mihara.hiroshima.jp +miyoshi.hiroshima.jp +naka.hiroshima.jp +onomichi.hiroshima.jp +osakikamijima.hiroshima.jp +otake.hiroshima.jp +saka.hiroshima.jp +sera.hiroshima.jp +seranishi.hiroshima.jp +shinichi.hiroshima.jp +shobara.hiroshima.jp +takehara.hiroshima.jp +abashiri.hokkaido.jp +abira.hokkaido.jp +aibetsu.hokkaido.jp +akabira.hokkaido.jp +akkeshi.hokkaido.jp +asahikawa.hokkaido.jp +ashibetsu.hokkaido.jp +ashoro.hokkaido.jp +assabu.hokkaido.jp +atsuma.hokkaido.jp +bibai.hokkaido.jp +biei.hokkaido.jp +bifuka.hokkaido.jp +bihoro.hokkaido.jp +biratori.hokkaido.jp +chippubetsu.hokkaido.jp +chitose.hokkaido.jp +date.hokkaido.jp +ebetsu.hokkaido.jp +embetsu.hokkaido.jp +eniwa.hokkaido.jp +erimo.hokkaido.jp +esan.hokkaido.jp +esashi.hokkaido.jp +fukagawa.hokkaido.jp +fukushima.hokkaido.jp +furano.hokkaido.jp +furubira.hokkaido.jp +haboro.hokkaido.jp +hakodate.hokkaido.jp +hamatonbetsu.hokkaido.jp +hidaka.hokkaido.jp +higashikagura.hokkaido.jp +higashikawa.hokkaido.jp +hiroo.hokkaido.jp +hokuryu.hokkaido.jp +hokuto.hokkaido.jp +honbetsu.hokkaido.jp +horokanai.hokkaido.jp +horonobe.hokkaido.jp +ikeda.hokkaido.jp +imakane.hokkaido.jp +ishikari.hokkaido.jp +iwamizawa.hokkaido.jp +iwanai.hokkaido.jp +kamifurano.hokkaido.jp +kamikawa.hokkaido.jp +kamishihoro.hokkaido.jp +kamisunagawa.hokkaido.jp +kamoenai.hokkaido.jp +kayabe.hokkaido.jp +kembuchi.hokkaido.jp +kikonai.hokkaido.jp +kimobetsu.hokkaido.jp +kitahiroshima.hokkaido.jp +kitami.hokkaido.jp +kiyosato.hokkaido.jp +koshimizu.hokkaido.jp +kunneppu.hokkaido.jp +kuriyama.hokkaido.jp +kuromatsunai.hokkaido.jp +kushiro.hokkaido.jp +kutchan.hokkaido.jp +kyowa.hokkaido.jp +mashike.hokkaido.jp +matsumae.hokkaido.jp +mikasa.hokkaido.jp +minamifurano.hokkaido.jp +mombetsu.hokkaido.jp +moseushi.hokkaido.jp +mukawa.hokkaido.jp +muroran.hokkaido.jp +naie.hokkaido.jp +nakagawa.hokkaido.jp +nakasatsunai.hokkaido.jp +nakatombetsu.hokkaido.jp +nanae.hokkaido.jp +nanporo.hokkaido.jp +nayoro.hokkaido.jp +nemuro.hokkaido.jp +niikappu.hokkaido.jp +niki.hokkaido.jp +nishiokoppe.hokkaido.jp +noboribetsu.hokkaido.jp +numata.hokkaido.jp +obihiro.hokkaido.jp +obira.hokkaido.jp +oketo.hokkaido.jp +okoppe.hokkaido.jp +otaru.hokkaido.jp +otobe.hokkaido.jp +otofuke.hokkaido.jp +otoineppu.hokkaido.jp +oumu.hokkaido.jp +ozora.hokkaido.jp +pippu.hokkaido.jp +rankoshi.hokkaido.jp +rebun.hokkaido.jp +rikubetsu.hokkaido.jp +rishiri.hokkaido.jp +rishirifuji.hokkaido.jp +saroma.hokkaido.jp +sarufutsu.hokkaido.jp +shakotan.hokkaido.jp +shari.hokkaido.jp +shibecha.hokkaido.jp +shibetsu.hokkaido.jp +shikabe.hokkaido.jp +shikaoi.hokkaido.jp +shimamaki.hokkaido.jp +shimizu.hokkaido.jp +shimokawa.hokkaido.jp +shinshinotsu.hokkaido.jp +shintoku.hokkaido.jp +shiranuka.hokkaido.jp +shiraoi.hokkaido.jp +shiriuchi.hokkaido.jp +sobetsu.hokkaido.jp +sunagawa.hokkaido.jp +taiki.hokkaido.jp +takasu.hokkaido.jp +takikawa.hokkaido.jp +takinoue.hokkaido.jp +teshikaga.hokkaido.jp +tobetsu.hokkaido.jp +tohma.hokkaido.jp +tomakomai.hokkaido.jp +tomari.hokkaido.jp +toya.hokkaido.jp +toyako.hokkaido.jp +toyotomi.hokkaido.jp +toyoura.hokkaido.jp +tsubetsu.hokkaido.jp +tsukigata.hokkaido.jp +urakawa.hokkaido.jp +urausu.hokkaido.jp +uryu.hokkaido.jp +utashinai.hokkaido.jp +wakkanai.hokkaido.jp +wassamu.hokkaido.jp +yakumo.hokkaido.jp +yoichi.hokkaido.jp +aioi.hyogo.jp +akashi.hyogo.jp +ako.hyogo.jp +amagasaki.hyogo.jp +aogaki.hyogo.jp +asago.hyogo.jp +ashiya.hyogo.jp +awaji.hyogo.jp +fukusaki.hyogo.jp +goshiki.hyogo.jp +harima.hyogo.jp +himeji.hyogo.jp +ichikawa.hyogo.jp +inagawa.hyogo.jp +itami.hyogo.jp +kakogawa.hyogo.jp +kamigori.hyogo.jp +kamikawa.hyogo.jp +kasai.hyogo.jp +kasuga.hyogo.jp +kawanishi.hyogo.jp +miki.hyogo.jp +minamiawaji.hyogo.jp +nishinomiya.hyogo.jp +nishiwaki.hyogo.jp +ono.hyogo.jp +sanda.hyogo.jp +sannan.hyogo.jp +sasayama.hyogo.jp +sayo.hyogo.jp +shingu.hyogo.jp +shinonsen.hyogo.jp +shiso.hyogo.jp +sumoto.hyogo.jp +taishi.hyogo.jp +taka.hyogo.jp +takarazuka.hyogo.jp +takasago.hyogo.jp +takino.hyogo.jp +tamba.hyogo.jp +tatsuno.hyogo.jp +toyooka.hyogo.jp +yabu.hyogo.jp +yashiro.hyogo.jp +yoka.hyogo.jp +yokawa.hyogo.jp +ami.ibaraki.jp +asahi.ibaraki.jp +bando.ibaraki.jp +chikusei.ibaraki.jp +daigo.ibaraki.jp +fujishiro.ibaraki.jp +hitachi.ibaraki.jp +hitachinaka.ibaraki.jp +hitachiomiya.ibaraki.jp +hitachiota.ibaraki.jp +ibaraki.ibaraki.jp +ina.ibaraki.jp +inashiki.ibaraki.jp +itako.ibaraki.jp +iwama.ibaraki.jp +joso.ibaraki.jp +kamisu.ibaraki.jp +kasama.ibaraki.jp +kashima.ibaraki.jp +kasumigaura.ibaraki.jp +koga.ibaraki.jp +miho.ibaraki.jp +mito.ibaraki.jp +moriya.ibaraki.jp +naka.ibaraki.jp +namegata.ibaraki.jp +oarai.ibaraki.jp +ogawa.ibaraki.jp +omitama.ibaraki.jp +ryugasaki.ibaraki.jp +sakai.ibaraki.jp +sakuragawa.ibaraki.jp +shimodate.ibaraki.jp +shimotsuma.ibaraki.jp +shirosato.ibaraki.jp +sowa.ibaraki.jp +suifu.ibaraki.jp +takahagi.ibaraki.jp +tamatsukuri.ibaraki.jp +tokai.ibaraki.jp +tomobe.ibaraki.jp +tone.ibaraki.jp +toride.ibaraki.jp +tsuchiura.ibaraki.jp +tsukuba.ibaraki.jp +uchihara.ibaraki.jp +ushiku.ibaraki.jp +yachiyo.ibaraki.jp +yamagata.ibaraki.jp +yawara.ibaraki.jp +yuki.ibaraki.jp +anamizu.ishikawa.jp +hakui.ishikawa.jp +hakusan.ishikawa.jp +kaga.ishikawa.jp +kahoku.ishikawa.jp +kanazawa.ishikawa.jp +kawakita.ishikawa.jp +komatsu.ishikawa.jp +nakanoto.ishikawa.jp +nanao.ishikawa.jp +nomi.ishikawa.jp +nonoichi.ishikawa.jp +noto.ishikawa.jp +shika.ishikawa.jp +suzu.ishikawa.jp +tsubata.ishikawa.jp +tsurugi.ishikawa.jp +uchinada.ishikawa.jp +wajima.ishikawa.jp +fudai.iwate.jp +fujisawa.iwate.jp +hanamaki.iwate.jp +hiraizumi.iwate.jp +hirono.iwate.jp +ichinohe.iwate.jp +ichinoseki.iwate.jp +iwaizumi.iwate.jp +iwate.iwate.jp +joboji.iwate.jp +kamaishi.iwate.jp +kanegasaki.iwate.jp +karumai.iwate.jp +kawai.iwate.jp +kitakami.iwate.jp +kuji.iwate.jp +kunohe.iwate.jp +kuzumaki.iwate.jp +miyako.iwate.jp +mizusawa.iwate.jp +morioka.iwate.jp +ninohe.iwate.jp +noda.iwate.jp +ofunato.iwate.jp +oshu.iwate.jp +otsuchi.iwate.jp +rikuzentakata.iwate.jp +shiwa.iwate.jp +shizukuishi.iwate.jp +sumita.iwate.jp +tanohata.iwate.jp +tono.iwate.jp +yahaba.iwate.jp +yamada.iwate.jp +ayagawa.kagawa.jp +higashikagawa.kagawa.jp +kanonji.kagawa.jp +kotohira.kagawa.jp +manno.kagawa.jp +marugame.kagawa.jp +mitoyo.kagawa.jp +naoshima.kagawa.jp +sanuki.kagawa.jp +tadotsu.kagawa.jp +takamatsu.kagawa.jp +tonosho.kagawa.jp +uchinomi.kagawa.jp +utazu.kagawa.jp +zentsuji.kagawa.jp +akune.kagoshima.jp +amami.kagoshima.jp +hioki.kagoshima.jp +isa.kagoshima.jp +isen.kagoshima.jp +izumi.kagoshima.jp +kagoshima.kagoshima.jp +kanoya.kagoshima.jp +kawanabe.kagoshima.jp +kinko.kagoshima.jp +kouyama.kagoshima.jp +makurazaki.kagoshima.jp +matsumoto.kagoshima.jp +minamitane.kagoshima.jp +nakatane.kagoshima.jp +nishinoomote.kagoshima.jp +satsumasendai.kagoshima.jp +soo.kagoshima.jp +tarumizu.kagoshima.jp +yusui.kagoshima.jp +aikawa.kanagawa.jp +atsugi.kanagawa.jp +ayase.kanagawa.jp +chigasaki.kanagawa.jp +ebina.kanagawa.jp +fujisawa.kanagawa.jp +hadano.kanagawa.jp +hakone.kanagawa.jp +hiratsuka.kanagawa.jp +isehara.kanagawa.jp +kaisei.kanagawa.jp +kamakura.kanagawa.jp +kiyokawa.kanagawa.jp +matsuda.kanagawa.jp +minamiashigara.kanagawa.jp +miura.kanagawa.jp +nakai.kanagawa.jp +ninomiya.kanagawa.jp +odawara.kanagawa.jp +oi.kanagawa.jp +oiso.kanagawa.jp +sagamihara.kanagawa.jp +samukawa.kanagawa.jp +tsukui.kanagawa.jp +yamakita.kanagawa.jp +yamato.kanagawa.jp +yokosuka.kanagawa.jp +yugawara.kanagawa.jp +zama.kanagawa.jp +zushi.kanagawa.jp +aki.kochi.jp +geisei.kochi.jp +hidaka.kochi.jp +higashitsuno.kochi.jp +ino.kochi.jp +kagami.kochi.jp +kami.kochi.jp +kitagawa.kochi.jp +kochi.kochi.jp +mihara.kochi.jp +motoyama.kochi.jp +muroto.kochi.jp +nahari.kochi.jp +nakamura.kochi.jp +nankoku.kochi.jp +nishitosa.kochi.jp +niyodogawa.kochi.jp +ochi.kochi.jp +okawa.kochi.jp +otoyo.kochi.jp +otsuki.kochi.jp +sakawa.kochi.jp +sukumo.kochi.jp +susaki.kochi.jp +tosa.kochi.jp +tosashimizu.kochi.jp +toyo.kochi.jp +tsuno.kochi.jp +umaji.kochi.jp +yasuda.kochi.jp +yusuhara.kochi.jp +amakusa.kumamoto.jp +arao.kumamoto.jp +aso.kumamoto.jp +choyo.kumamoto.jp +gyokuto.kumamoto.jp +hitoyoshi.kumamoto.jp +kamiamakusa.kumamoto.jp +kashima.kumamoto.jp +kikuchi.kumamoto.jp +kosa.kumamoto.jp +kumamoto.kumamoto.jp +mashiki.kumamoto.jp +mifune.kumamoto.jp +minamata.kumamoto.jp +minamioguni.kumamoto.jp +nagasu.kumamoto.jp +nishihara.kumamoto.jp +oguni.kumamoto.jp +ozu.kumamoto.jp +sumoto.kumamoto.jp +takamori.kumamoto.jp +uki.kumamoto.jp +uto.kumamoto.jp +yamaga.kumamoto.jp +yamato.kumamoto.jp +yatsushiro.kumamoto.jp +ayabe.kyoto.jp +fukuchiyama.kyoto.jp +higashiyama.kyoto.jp +ide.kyoto.jp +ine.kyoto.jp +joyo.kyoto.jp +kameoka.kyoto.jp +kamo.kyoto.jp +kita.kyoto.jp +kizu.kyoto.jp +kumiyama.kyoto.jp +kyotamba.kyoto.jp +kyotanabe.kyoto.jp +kyotango.kyoto.jp +maizuru.kyoto.jp +minami.kyoto.jp +minamiyamashiro.kyoto.jp +miyazu.kyoto.jp +muko.kyoto.jp +nagaokakyo.kyoto.jp +nakagyo.kyoto.jp +nantan.kyoto.jp +oyamazaki.kyoto.jp +sakyo.kyoto.jp +seika.kyoto.jp +tanabe.kyoto.jp +uji.kyoto.jp +ujitawara.kyoto.jp +wazuka.kyoto.jp +yamashina.kyoto.jp +yawata.kyoto.jp +asahi.mie.jp +inabe.mie.jp +ise.mie.jp +kameyama.mie.jp +kawagoe.mie.jp +kiho.mie.jp +kisosaki.mie.jp +kiwa.mie.jp +komono.mie.jp +kumano.mie.jp +kuwana.mie.jp +matsusaka.mie.jp +meiwa.mie.jp +mihama.mie.jp +minamiise.mie.jp +misugi.mie.jp +miyama.mie.jp +nabari.mie.jp +shima.mie.jp +suzuka.mie.jp +tado.mie.jp +taiki.mie.jp +taki.mie.jp +tamaki.mie.jp +toba.mie.jp +tsu.mie.jp +udono.mie.jp +ureshino.mie.jp +watarai.mie.jp +yokkaichi.mie.jp +furukawa.miyagi.jp +higashimatsushima.miyagi.jp +ishinomaki.miyagi.jp +iwanuma.miyagi.jp +kakuda.miyagi.jp +kami.miyagi.jp +kawasaki.miyagi.jp +kesennuma.miyagi.jp +marumori.miyagi.jp +matsushima.miyagi.jp +minamisanriku.miyagi.jp +misato.miyagi.jp +murata.miyagi.jp +natori.miyagi.jp +ogawara.miyagi.jp +ohira.miyagi.jp +onagawa.miyagi.jp +osaki.miyagi.jp +rifu.miyagi.jp +semine.miyagi.jp +shibata.miyagi.jp +shichikashuku.miyagi.jp +shikama.miyagi.jp +shiogama.miyagi.jp +shiroishi.miyagi.jp +tagajo.miyagi.jp +taiwa.miyagi.jp +tome.miyagi.jp +tomiya.miyagi.jp +wakuya.miyagi.jp +watari.miyagi.jp +yamamoto.miyagi.jp +zao.miyagi.jp +aya.miyazaki.jp +ebino.miyazaki.jp +gokase.miyazaki.jp +hyuga.miyazaki.jp +kadogawa.miyazaki.jp +kawaminami.miyazaki.jp +kijo.miyazaki.jp +kitagawa.miyazaki.jp +kitakata.miyazaki.jp +kitaura.miyazaki.jp +kobayashi.miyazaki.jp +kunitomi.miyazaki.jp +kushima.miyazaki.jp +mimata.miyazaki.jp +miyakonojo.miyazaki.jp +miyazaki.miyazaki.jp +morotsuka.miyazaki.jp +nichinan.miyazaki.jp +nishimera.miyazaki.jp +nobeoka.miyazaki.jp +saito.miyazaki.jp +shiiba.miyazaki.jp +shintomi.miyazaki.jp +takaharu.miyazaki.jp +takanabe.miyazaki.jp +takazaki.miyazaki.jp +tsuno.miyazaki.jp +achi.nagano.jp +agematsu.nagano.jp +anan.nagano.jp +aoki.nagano.jp +asahi.nagano.jp +azumino.nagano.jp +chikuhoku.nagano.jp +chikuma.nagano.jp +chino.nagano.jp +fujimi.nagano.jp +hakuba.nagano.jp +hara.nagano.jp +hiraya.nagano.jp +iida.nagano.jp +iijima.nagano.jp +iiyama.nagano.jp +iizuna.nagano.jp +ikeda.nagano.jp +ikusaka.nagano.jp +ina.nagano.jp +karuizawa.nagano.jp +kawakami.nagano.jp +kiso.nagano.jp +kisofukushima.nagano.jp +kitaaiki.nagano.jp +komagane.nagano.jp +komoro.nagano.jp +matsukawa.nagano.jp +matsumoto.nagano.jp +miasa.nagano.jp +minamiaiki.nagano.jp +minamimaki.nagano.jp +minamiminowa.nagano.jp +minowa.nagano.jp +miyada.nagano.jp +miyota.nagano.jp +mochizuki.nagano.jp +nagano.nagano.jp +nagawa.nagano.jp +nagiso.nagano.jp +nakagawa.nagano.jp +nakano.nagano.jp +nozawaonsen.nagano.jp +obuse.nagano.jp +ogawa.nagano.jp +okaya.nagano.jp +omachi.nagano.jp +omi.nagano.jp +ookuwa.nagano.jp +ooshika.nagano.jp +otaki.nagano.jp +otari.nagano.jp +sakae.nagano.jp +sakaki.nagano.jp +saku.nagano.jp +sakuho.nagano.jp +shimosuwa.nagano.jp +shinanomachi.nagano.jp +shiojiri.nagano.jp +suwa.nagano.jp +suzaka.nagano.jp +takagi.nagano.jp +takamori.nagano.jp +takayama.nagano.jp +tateshina.nagano.jp +tatsuno.nagano.jp +togakushi.nagano.jp +togura.nagano.jp +tomi.nagano.jp +ueda.nagano.jp +wada.nagano.jp +yamagata.nagano.jp +yamanouchi.nagano.jp +yasaka.nagano.jp +yasuoka.nagano.jp +chijiwa.nagasaki.jp +futsu.nagasaki.jp +goto.nagasaki.jp +hasami.nagasaki.jp +hirado.nagasaki.jp +iki.nagasaki.jp +isahaya.nagasaki.jp +kawatana.nagasaki.jp +kuchinotsu.nagasaki.jp +matsuura.nagasaki.jp +nagasaki.nagasaki.jp +obama.nagasaki.jp +omura.nagasaki.jp +oseto.nagasaki.jp +saikai.nagasaki.jp +sasebo.nagasaki.jp +seihi.nagasaki.jp +shimabara.nagasaki.jp +shinkamigoto.nagasaki.jp +togitsu.nagasaki.jp +tsushima.nagasaki.jp +unzen.nagasaki.jp +ando.nara.jp +gose.nara.jp +heguri.nara.jp +higashiyoshino.nara.jp +ikaruga.nara.jp +ikoma.nara.jp +kamikitayama.nara.jp +kanmaki.nara.jp +kashiba.nara.jp +kashihara.nara.jp +katsuragi.nara.jp +kawai.nara.jp +kawakami.nara.jp +kawanishi.nara.jp +koryo.nara.jp +kurotaki.nara.jp +mitsue.nara.jp +miyake.nara.jp +nara.nara.jp +nosegawa.nara.jp +oji.nara.jp +ouda.nara.jp +oyodo.nara.jp +sakurai.nara.jp +sango.nara.jp +shimoichi.nara.jp +shimokitayama.nara.jp +shinjo.nara.jp +soni.nara.jp +takatori.nara.jp +tawaramoto.nara.jp +tenkawa.nara.jp +tenri.nara.jp +uda.nara.jp +yamatokoriyama.nara.jp +yamatotakada.nara.jp +yamazoe.nara.jp +yoshino.nara.jp +aga.niigata.jp +agano.niigata.jp +gosen.niigata.jp +itoigawa.niigata.jp +izumozaki.niigata.jp +joetsu.niigata.jp +kamo.niigata.jp +kariwa.niigata.jp +kashiwazaki.niigata.jp +minamiuonuma.niigata.jp +mitsuke.niigata.jp +muika.niigata.jp +murakami.niigata.jp +myoko.niigata.jp +nagaoka.niigata.jp +niigata.niigata.jp +ojiya.niigata.jp +omi.niigata.jp +sado.niigata.jp +sanjo.niigata.jp +seiro.niigata.jp +seirou.niigata.jp +sekikawa.niigata.jp +shibata.niigata.jp +tagami.niigata.jp +tainai.niigata.jp +tochio.niigata.jp +tokamachi.niigata.jp +tsubame.niigata.jp +tsunan.niigata.jp +uonuma.niigata.jp +yahiko.niigata.jp +yoita.niigata.jp +yuzawa.niigata.jp +beppu.oita.jp +bungoono.oita.jp +bungotakada.oita.jp +hasama.oita.jp +hiji.oita.jp +himeshima.oita.jp +hita.oita.jp +kamitsue.oita.jp +kokonoe.oita.jp +kuju.oita.jp +kunisaki.oita.jp +kusu.oita.jp +oita.oita.jp +saiki.oita.jp +taketa.oita.jp +tsukumi.oita.jp +usa.oita.jp +usuki.oita.jp +yufu.oita.jp +akaiwa.okayama.jp +asakuchi.okayama.jp +bizen.okayama.jp +hayashima.okayama.jp +ibara.okayama.jp +kagamino.okayama.jp +kasaoka.okayama.jp +kibichuo.okayama.jp +kumenan.okayama.jp +kurashiki.okayama.jp +maniwa.okayama.jp +misaki.okayama.jp +nagi.okayama.jp +niimi.okayama.jp +nishiawakura.okayama.jp +okayama.okayama.jp +satosho.okayama.jp +setouchi.okayama.jp +shinjo.okayama.jp +shoo.okayama.jp +soja.okayama.jp +takahashi.okayama.jp +tamano.okayama.jp +tsuyama.okayama.jp +wake.okayama.jp +yakage.okayama.jp +aguni.okinawa.jp +ginowan.okinawa.jp +ginoza.okinawa.jp +gushikami.okinawa.jp +haebaru.okinawa.jp +higashi.okinawa.jp +hirara.okinawa.jp +iheya.okinawa.jp +ishigaki.okinawa.jp +ishikawa.okinawa.jp +itoman.okinawa.jp +izena.okinawa.jp +kadena.okinawa.jp +kin.okinawa.jp +kitadaito.okinawa.jp +kitanakagusuku.okinawa.jp +kumejima.okinawa.jp +kunigami.okinawa.jp +minamidaito.okinawa.jp +motobu.okinawa.jp +nago.okinawa.jp +naha.okinawa.jp +nakagusuku.okinawa.jp +nakijin.okinawa.jp +nanjo.okinawa.jp +nishihara.okinawa.jp +ogimi.okinawa.jp +okinawa.okinawa.jp +onna.okinawa.jp +shimoji.okinawa.jp +taketomi.okinawa.jp +tarama.okinawa.jp +tokashiki.okinawa.jp +tomigusuku.okinawa.jp +tonaki.okinawa.jp +urasoe.okinawa.jp +uruma.okinawa.jp +yaese.okinawa.jp +yomitan.okinawa.jp +yonabaru.okinawa.jp +yonaguni.okinawa.jp +zamami.okinawa.jp +abeno.osaka.jp +chihayaakasaka.osaka.jp +chuo.osaka.jp +daito.osaka.jp +fujiidera.osaka.jp +habikino.osaka.jp +hannan.osaka.jp +higashiosaka.osaka.jp +higashisumiyoshi.osaka.jp +higashiyodogawa.osaka.jp +hirakata.osaka.jp +ibaraki.osaka.jp +ikeda.osaka.jp +izumi.osaka.jp +izumiotsu.osaka.jp +izumisano.osaka.jp +kadoma.osaka.jp +kaizuka.osaka.jp +kanan.osaka.jp +kashiwara.osaka.jp +katano.osaka.jp +kawachinagano.osaka.jp +kishiwada.osaka.jp +kita.osaka.jp +kumatori.osaka.jp +matsubara.osaka.jp +minato.osaka.jp +minoh.osaka.jp +misaki.osaka.jp +moriguchi.osaka.jp +neyagawa.osaka.jp +nishi.osaka.jp +nose.osaka.jp +osakasayama.osaka.jp +sakai.osaka.jp +sayama.osaka.jp +sennan.osaka.jp +settsu.osaka.jp +shijonawate.osaka.jp +shimamoto.osaka.jp +suita.osaka.jp +tadaoka.osaka.jp +taishi.osaka.jp +tajiri.osaka.jp +takaishi.osaka.jp +takatsuki.osaka.jp +tondabayashi.osaka.jp +toyonaka.osaka.jp +toyono.osaka.jp +yao.osaka.jp +ariake.saga.jp +arita.saga.jp +fukudomi.saga.jp +genkai.saga.jp +hamatama.saga.jp +hizen.saga.jp +imari.saga.jp +kamimine.saga.jp +kanzaki.saga.jp +karatsu.saga.jp +kashima.saga.jp +kitagata.saga.jp +kitahata.saga.jp +kiyama.saga.jp +kouhoku.saga.jp +kyuragi.saga.jp +nishiarita.saga.jp +ogi.saga.jp +omachi.saga.jp +ouchi.saga.jp +saga.saga.jp +shiroishi.saga.jp +taku.saga.jp +tara.saga.jp +tosu.saga.jp +yoshinogari.saga.jp +arakawa.saitama.jp +asaka.saitama.jp +chichibu.saitama.jp +fujimi.saitama.jp +fujimino.saitama.jp +fukaya.saitama.jp +hanno.saitama.jp +hanyu.saitama.jp +hasuda.saitama.jp +hatogaya.saitama.jp +hatoyama.saitama.jp +hidaka.saitama.jp +higashichichibu.saitama.jp +higashimatsuyama.saitama.jp +honjo.saitama.jp +ina.saitama.jp +iruma.saitama.jp +iwatsuki.saitama.jp +kamiizumi.saitama.jp +kamikawa.saitama.jp +kamisato.saitama.jp +kasukabe.saitama.jp +kawagoe.saitama.jp +kawaguchi.saitama.jp +kawajima.saitama.jp +kazo.saitama.jp +kitamoto.saitama.jp +koshigaya.saitama.jp +kounosu.saitama.jp +kuki.saitama.jp +kumagaya.saitama.jp +matsubushi.saitama.jp +minano.saitama.jp +misato.saitama.jp +miyashiro.saitama.jp +miyoshi.saitama.jp +moroyama.saitama.jp +nagatoro.saitama.jp +namegawa.saitama.jp +niiza.saitama.jp +ogano.saitama.jp +ogawa.saitama.jp +ogose.saitama.jp +okegawa.saitama.jp +omiya.saitama.jp +otaki.saitama.jp +ranzan.saitama.jp +ryokami.saitama.jp +saitama.saitama.jp +sakado.saitama.jp +satte.saitama.jp +sayama.saitama.jp +shiki.saitama.jp +shiraoka.saitama.jp +soka.saitama.jp +sugito.saitama.jp +toda.saitama.jp +tokigawa.saitama.jp +tokorozawa.saitama.jp +tsurugashima.saitama.jp +urawa.saitama.jp +warabi.saitama.jp +yashio.saitama.jp +yokoze.saitama.jp +yono.saitama.jp +yorii.saitama.jp +yoshida.saitama.jp +yoshikawa.saitama.jp +yoshimi.saitama.jp +aisho.shiga.jp +gamo.shiga.jp +higashiomi.shiga.jp +hikone.shiga.jp +koka.shiga.jp +konan.shiga.jp +kosei.shiga.jp +koto.shiga.jp +kusatsu.shiga.jp +maibara.shiga.jp +moriyama.shiga.jp +nagahama.shiga.jp +nishiazai.shiga.jp +notogawa.shiga.jp +omihachiman.shiga.jp +otsu.shiga.jp +ritto.shiga.jp +ryuoh.shiga.jp +takashima.shiga.jp +takatsuki.shiga.jp +torahime.shiga.jp +toyosato.shiga.jp +yasu.shiga.jp +akagi.shimane.jp +ama.shimane.jp +gotsu.shimane.jp +hamada.shimane.jp +higashiizumo.shimane.jp +hikawa.shimane.jp +hikimi.shimane.jp +izumo.shimane.jp +kakinoki.shimane.jp +masuda.shimane.jp +matsue.shimane.jp +misato.shimane.jp +nishinoshima.shimane.jp +ohda.shimane.jp +okinoshima.shimane.jp +okuizumo.shimane.jp +shimane.shimane.jp +tamayu.shimane.jp +tsuwano.shimane.jp +unnan.shimane.jp +yakumo.shimane.jp +yasugi.shimane.jp +yatsuka.shimane.jp +arai.shizuoka.jp +atami.shizuoka.jp +fuji.shizuoka.jp +fujieda.shizuoka.jp +fujikawa.shizuoka.jp +fujinomiya.shizuoka.jp +fukuroi.shizuoka.jp +gotemba.shizuoka.jp +haibara.shizuoka.jp +hamamatsu.shizuoka.jp +higashiizu.shizuoka.jp +ito.shizuoka.jp +iwata.shizuoka.jp +izu.shizuoka.jp +izunokuni.shizuoka.jp +kakegawa.shizuoka.jp +kannami.shizuoka.jp +kawanehon.shizuoka.jp +kawazu.shizuoka.jp +kikugawa.shizuoka.jp +kosai.shizuoka.jp +makinohara.shizuoka.jp +matsuzaki.shizuoka.jp +minamiizu.shizuoka.jp +mishima.shizuoka.jp +morimachi.shizuoka.jp +nishiizu.shizuoka.jp +numazu.shizuoka.jp +omaezaki.shizuoka.jp +shimada.shizuoka.jp +shimizu.shizuoka.jp +shimoda.shizuoka.jp +shizuoka.shizuoka.jp +susono.shizuoka.jp +yaizu.shizuoka.jp +yoshida.shizuoka.jp +ashikaga.tochigi.jp +bato.tochigi.jp +haga.tochigi.jp +ichikai.tochigi.jp +iwafune.tochigi.jp +kaminokawa.tochigi.jp +kanuma.tochigi.jp +karasuyama.tochigi.jp +kuroiso.tochigi.jp +mashiko.tochigi.jp +mibu.tochigi.jp +moka.tochigi.jp +motegi.tochigi.jp +nasu.tochigi.jp +nasushiobara.tochigi.jp +nikko.tochigi.jp +nishikata.tochigi.jp +nogi.tochigi.jp +ohira.tochigi.jp +ohtawara.tochigi.jp +oyama.tochigi.jp +sakura.tochigi.jp +sano.tochigi.jp +shimotsuke.tochigi.jp +shioya.tochigi.jp +takanezawa.tochigi.jp +tochigi.tochigi.jp +tsuga.tochigi.jp +ujiie.tochigi.jp +utsunomiya.tochigi.jp +yaita.tochigi.jp +aizumi.tokushima.jp +anan.tokushima.jp +ichiba.tokushima.jp +itano.tokushima.jp +kainan.tokushima.jp +komatsushima.tokushima.jp +matsushige.tokushima.jp +mima.tokushima.jp +minami.tokushima.jp +miyoshi.tokushima.jp +mugi.tokushima.jp +nakagawa.tokushima.jp +naruto.tokushima.jp +sanagochi.tokushima.jp +shishikui.tokushima.jp +tokushima.tokushima.jp +wajiki.tokushima.jp +adachi.tokyo.jp +akiruno.tokyo.jp +akishima.tokyo.jp +aogashima.tokyo.jp +arakawa.tokyo.jp +bunkyo.tokyo.jp +chiyoda.tokyo.jp +chofu.tokyo.jp +chuo.tokyo.jp +edogawa.tokyo.jp +fuchu.tokyo.jp +fussa.tokyo.jp +hachijo.tokyo.jp +hachioji.tokyo.jp +hamura.tokyo.jp +higashikurume.tokyo.jp +higashimurayama.tokyo.jp +higashiyamato.tokyo.jp +hino.tokyo.jp +hinode.tokyo.jp +hinohara.tokyo.jp +inagi.tokyo.jp +itabashi.tokyo.jp +katsushika.tokyo.jp +kita.tokyo.jp +kiyose.tokyo.jp +kodaira.tokyo.jp +koganei.tokyo.jp +kokubunji.tokyo.jp +komae.tokyo.jp +koto.tokyo.jp +kouzushima.tokyo.jp +kunitachi.tokyo.jp +machida.tokyo.jp +meguro.tokyo.jp +minato.tokyo.jp +mitaka.tokyo.jp +mizuho.tokyo.jp +musashimurayama.tokyo.jp +musashino.tokyo.jp +nakano.tokyo.jp +nerima.tokyo.jp +ogasawara.tokyo.jp +okutama.tokyo.jp +ome.tokyo.jp +oshima.tokyo.jp +ota.tokyo.jp +setagaya.tokyo.jp +shibuya.tokyo.jp +shinagawa.tokyo.jp +shinjuku.tokyo.jp +suginami.tokyo.jp +sumida.tokyo.jp +tachikawa.tokyo.jp +taito.tokyo.jp +tama.tokyo.jp +toshima.tokyo.jp +chizu.tottori.jp +hino.tottori.jp +kawahara.tottori.jp +koge.tottori.jp +kotoura.tottori.jp +misasa.tottori.jp +nanbu.tottori.jp +nichinan.tottori.jp +sakaiminato.tottori.jp +tottori.tottori.jp +wakasa.tottori.jp +yazu.tottori.jp +yonago.tottori.jp +asahi.toyama.jp +fuchu.toyama.jp +fukumitsu.toyama.jp +funahashi.toyama.jp +himi.toyama.jp +imizu.toyama.jp +inami.toyama.jp +johana.toyama.jp +kamiichi.toyama.jp +kurobe.toyama.jp +nakaniikawa.toyama.jp +namerikawa.toyama.jp +nanto.toyama.jp +nyuzen.toyama.jp +oyabe.toyama.jp +taira.toyama.jp +takaoka.toyama.jp +tateyama.toyama.jp +toga.toyama.jp +tonami.toyama.jp +toyama.toyama.jp +unazuki.toyama.jp +uozu.toyama.jp +yamada.toyama.jp +arida.wakayama.jp +aridagawa.wakayama.jp +gobo.wakayama.jp +hashimoto.wakayama.jp +hidaka.wakayama.jp +hirogawa.wakayama.jp +inami.wakayama.jp +iwade.wakayama.jp +kainan.wakayama.jp +kamitonda.wakayama.jp +katsuragi.wakayama.jp +kimino.wakayama.jp +kinokawa.wakayama.jp +kitayama.wakayama.jp +koya.wakayama.jp +koza.wakayama.jp +kozagawa.wakayama.jp +kudoyama.wakayama.jp +kushimoto.wakayama.jp +mihama.wakayama.jp +misato.wakayama.jp +nachikatsuura.wakayama.jp +shingu.wakayama.jp +shirahama.wakayama.jp +taiji.wakayama.jp +tanabe.wakayama.jp +wakayama.wakayama.jp +yuasa.wakayama.jp +yura.wakayama.jp +asahi.yamagata.jp +funagata.yamagata.jp +higashine.yamagata.jp +iide.yamagata.jp +kahoku.yamagata.jp +kaminoyama.yamagata.jp +kaneyama.yamagata.jp +kawanishi.yamagata.jp +mamurogawa.yamagata.jp +mikawa.yamagata.jp +murayama.yamagata.jp +nagai.yamagata.jp +nakayama.yamagata.jp +nanyo.yamagata.jp +nishikawa.yamagata.jp +obanazawa.yamagata.jp +oe.yamagata.jp +oguni.yamagata.jp +ohkura.yamagata.jp +oishida.yamagata.jp +sagae.yamagata.jp +sakata.yamagata.jp +sakegawa.yamagata.jp +shinjo.yamagata.jp +shirataka.yamagata.jp +shonai.yamagata.jp +takahata.yamagata.jp +tendo.yamagata.jp +tozawa.yamagata.jp +tsuruoka.yamagata.jp +yamagata.yamagata.jp +yamanobe.yamagata.jp +yonezawa.yamagata.jp +yuza.yamagata.jp +abu.yamaguchi.jp +hagi.yamaguchi.jp +hikari.yamaguchi.jp +hofu.yamaguchi.jp +iwakuni.yamaguchi.jp +kudamatsu.yamaguchi.jp +mitou.yamaguchi.jp +nagato.yamaguchi.jp +oshima.yamaguchi.jp +shimonoseki.yamaguchi.jp +shunan.yamaguchi.jp +tabuse.yamaguchi.jp +tokuyama.yamaguchi.jp +toyota.yamaguchi.jp +ube.yamaguchi.jp +yuu.yamaguchi.jp +chuo.yamanashi.jp +doshi.yamanashi.jp +fuefuki.yamanashi.jp +fujikawa.yamanashi.jp +fujikawaguchiko.yamanashi.jp +fujiyoshida.yamanashi.jp +hayakawa.yamanashi.jp +hokuto.yamanashi.jp +ichikawamisato.yamanashi.jp +kai.yamanashi.jp +kofu.yamanashi.jp +koshu.yamanashi.jp +kosuge.yamanashi.jp +minami-alps.yamanashi.jp +minobu.yamanashi.jp +nakamichi.yamanashi.jp +nanbu.yamanashi.jp +narusawa.yamanashi.jp +nirasaki.yamanashi.jp +nishikatsura.yamanashi.jp +oshino.yamanashi.jp +otsuki.yamanashi.jp +showa.yamanashi.jp +tabayama.yamanashi.jp +tsuru.yamanashi.jp +uenohara.yamanashi.jp +yamanakako.yamanashi.jp +yamanashi.yamanashi.jp + +// ke : http://www.kenic.or.ke/index.php?option=com_content&task=view&id=117&Itemid=145 +*.ke + +// kg : http://www.domain.kg/dmn_n.html +kg +org.kg +net.kg +com.kg +edu.kg +gov.kg +mil.kg + +// kh : http://www.mptc.gov.kh/dns_registration.htm +*.kh + +// ki : http://www.ki/dns/index.html +ki +edu.ki +biz.ki +net.ki +org.ki +gov.ki +info.ki +com.ki + +// km : http://en.wikipedia.org/wiki/.km +// http://www.domaine.km/documents/charte.doc +km +org.km +nom.km +gov.km +prd.km +tm.km +edu.km +mil.km +ass.km +com.km +// These are only mentioned as proposed suggestions at domaine.km, but +// http://en.wikipedia.org/wiki/.km says they're available for registration: +coop.km +asso.km +presse.km +medecin.km +notaires.km +pharmaciens.km +veterinaire.km +gouv.km + +// kn : http://en.wikipedia.org/wiki/.kn +// http://www.dot.kn/domainRules.html +kn +net.kn +org.kn +edu.kn +gov.kn + +// kp : http://www.kcce.kp/en_index.php +kp +com.kp +edu.kp +gov.kp +org.kp +rep.kp +tra.kp + +// kr : http://en.wikipedia.org/wiki/.kr +// see also: http://domain.nida.or.kr/eng/registration.jsp +kr +ac.kr +co.kr +es.kr +go.kr +hs.kr +kg.kr +mil.kr +ms.kr +ne.kr +or.kr +pe.kr +re.kr +sc.kr +// kr geographical names +busan.kr +chungbuk.kr +chungnam.kr +daegu.kr +daejeon.kr +gangwon.kr +gwangju.kr +gyeongbuk.kr +gyeonggi.kr +gyeongnam.kr +incheon.kr +jeju.kr +jeonbuk.kr +jeonnam.kr +seoul.kr +ulsan.kr + +// kw : http://en.wikipedia.org/wiki/.kw +*.kw + +// ky : http://www.icta.ky/da_ky_reg_dom.php +// Confirmed by registry 2008-06-17 +ky +edu.ky +gov.ky +com.ky +org.ky +net.ky + +// kz : http://en.wikipedia.org/wiki/.kz +// see also: http://www.nic.kz/rules/index.jsp +kz +org.kz +edu.kz +net.kz +gov.kz +mil.kz +com.kz + +// la : http://en.wikipedia.org/wiki/.la +// Submitted by registry 2008-06-10 +la +int.la +net.la +info.la +edu.la +gov.la +per.la +com.la +org.la + +// lb : http://en.wikipedia.org/wiki/.lb +// Submitted by registry 2008-06-17 +lb +com.lb +edu.lb +gov.lb +net.lb +org.lb + +// lc : http://en.wikipedia.org/wiki/.lc +// see also: http://www.nic.lc/rules.htm +lc +com.lc +net.lc +co.lc +org.lc +edu.lc +gov.lc + +// li : http://en.wikipedia.org/wiki/.li +li + +// lk : http://www.nic.lk/seclevpr.html +lk +gov.lk +sch.lk +net.lk +int.lk +com.lk +org.lk +edu.lk +ngo.lk +soc.lk +web.lk +ltd.lk +assn.lk +grp.lk +hotel.lk + +// lr : http://psg.com/dns/lr/lr.txt +// Submitted by registry 2008-06-17 +lr +com.lr +edu.lr +gov.lr +org.lr +net.lr + +// ls : http://en.wikipedia.org/wiki/.ls +ls +co.ls +org.ls + +// lt : http://en.wikipedia.org/wiki/.lt +lt +// gov.lt : http://www.gov.lt/index_en.php +gov.lt + +// lu : http://www.dns.lu/en/ +lu + +// lv : http://www.nic.lv/DNS/En/generic.php +lv +com.lv +edu.lv +gov.lv +org.lv +mil.lv +id.lv +net.lv +asn.lv +conf.lv + +// ly : http://www.nic.ly/regulations.php +ly +com.ly +net.ly +gov.ly +plc.ly +edu.ly +sch.ly +med.ly +org.ly +id.ly + +// ma : http://en.wikipedia.org/wiki/.ma +// http://www.anrt.ma/fr/admin/download/upload/file_fr782.pdf +ma +co.ma +net.ma +gov.ma +org.ma +ac.ma +press.ma + +// mc : http://www.nic.mc/ +mc +tm.mc +asso.mc + +// md : http://en.wikipedia.org/wiki/.md +md + +// me : http://en.wikipedia.org/wiki/.me +me +co.me +net.me +org.me +edu.me +ac.me +gov.me +its.me +priv.me + +// mg : http://www.nic.mg/tarif.htm +mg +org.mg +nom.mg +gov.mg +prd.mg +tm.mg +edu.mg +mil.mg +com.mg + +// mh : http://en.wikipedia.org/wiki/.mh +mh + +// mil : http://en.wikipedia.org/wiki/.mil +mil + +// mk : http://en.wikipedia.org/wiki/.mk +// see also: http://dns.marnet.net.mk/postapka.php +mk +com.mk +org.mk +net.mk +edu.mk +gov.mk +inf.mk +name.mk + +// ml : http://www.gobin.info/domainname/ml-template.doc +// see also: http://en.wikipedia.org/wiki/.ml +ml +com.ml +edu.ml +gouv.ml +gov.ml +net.ml +org.ml +presse.ml + +// mm : http://en.wikipedia.org/wiki/.mm +*.mm + +// mn : http://en.wikipedia.org/wiki/.mn +mn +gov.mn +edu.mn +org.mn + +// mo : http://www.monic.net.mo/ +mo +com.mo +net.mo +org.mo +edu.mo +gov.mo + +// mobi : http://en.wikipedia.org/wiki/.mobi +mobi + +// mp : http://www.dot.mp/ +// Confirmed by registry 2008-06-17 +mp + +// mq : http://en.wikipedia.org/wiki/.mq +mq + +// mr : http://en.wikipedia.org/wiki/.mr +mr +gov.mr + +// ms : http://www.nic.ms/pdf/MS_Domain_Name_Rules.pdf +ms +com.ms +edu.ms +gov.ms +net.ms +org.ms + +// mt : https://www.nic.org.mt/go/policy +// Submitted by registry 2013-11-19 +mt +com.mt +edu.mt +net.mt +org.mt + +// mu : http://en.wikipedia.org/wiki/.mu +mu +com.mu +net.mu +org.mu +gov.mu +ac.mu +co.mu +or.mu + +// museum : http://about.museum/naming/ +// http://index.museum/ +museum +academy.museum +agriculture.museum +air.museum +airguard.museum +alabama.museum +alaska.museum +amber.museum +ambulance.museum +american.museum +americana.museum +americanantiques.museum +americanart.museum +amsterdam.museum +and.museum +annefrank.museum +anthro.museum +anthropology.museum +antiques.museum +aquarium.museum +arboretum.museum +archaeological.museum +archaeology.museum +architecture.museum +art.museum +artanddesign.museum +artcenter.museum +artdeco.museum +arteducation.museum +artgallery.museum +arts.museum +artsandcrafts.museum +asmatart.museum +assassination.museum +assisi.museum +association.museum +astronomy.museum +atlanta.museum +austin.museum +australia.museum +automotive.museum +aviation.museum +axis.museum +badajoz.museum +baghdad.museum +bahn.museum +bale.museum +baltimore.museum +barcelona.museum +baseball.museum +basel.museum +baths.museum +bauern.museum +beauxarts.museum +beeldengeluid.museum +bellevue.museum +bergbau.museum +berkeley.museum +berlin.museum +bern.museum +bible.museum +bilbao.museum +bill.museum +birdart.museum +birthplace.museum +bonn.museum +boston.museum +botanical.museum +botanicalgarden.museum +botanicgarden.museum +botany.museum +brandywinevalley.museum +brasil.museum +bristol.museum +british.museum +britishcolumbia.museum +broadcast.museum +brunel.museum +brussel.museum +brussels.museum +bruxelles.museum +building.museum +burghof.museum +bus.museum +bushey.museum +cadaques.museum +california.museum +cambridge.museum +can.museum +canada.museum +capebreton.museum +carrier.museum +cartoonart.museum +casadelamoneda.museum +castle.museum +castres.museum +celtic.museum +center.museum +chattanooga.museum +cheltenham.museum +chesapeakebay.museum +chicago.museum +children.museum +childrens.museum +childrensgarden.museum +chiropractic.museum +chocolate.museum +christiansburg.museum +cincinnati.museum +cinema.museum +circus.museum +civilisation.museum +civilization.museum +civilwar.museum +clinton.museum +clock.museum +coal.museum +coastaldefence.museum +cody.museum +coldwar.museum +collection.museum +colonialwilliamsburg.museum +coloradoplateau.museum +columbia.museum +columbus.museum +communication.museum +communications.museum +community.museum +computer.museum +computerhistory.museum +comunicações.museum +contemporary.museum +contemporaryart.museum +convent.museum +copenhagen.museum +corporation.museum +correios-e-telecomunicações.museum +corvette.museum +costume.museum +countryestate.museum +county.museum +crafts.museum +cranbrook.museum +creation.museum +cultural.museum +culturalcenter.museum +culture.museum +cyber.museum +cymru.museum +dali.museum +dallas.museum +database.museum +ddr.museum +decorativearts.museum +delaware.museum +delmenhorst.museum +denmark.museum +depot.museum +design.museum +detroit.museum +dinosaur.museum +discovery.museum +dolls.museum +donostia.museum +durham.museum +eastafrica.museum +eastcoast.museum +education.museum +educational.museum +egyptian.museum +eisenbahn.museum +elburg.museum +elvendrell.museum +embroidery.museum +encyclopedic.museum +england.museum +entomology.museum +environment.museum +environmentalconservation.museum +epilepsy.museum +essex.museum +estate.museum +ethnology.museum +exeter.museum +exhibition.museum +family.museum +farm.museum +farmequipment.museum +farmers.museum +farmstead.museum +field.museum +figueres.museum +filatelia.museum +film.museum +fineart.museum +finearts.museum +finland.museum +flanders.museum +florida.museum +force.museum +fortmissoula.museum +fortworth.museum +foundation.museum +francaise.museum +frankfurt.museum +franziskaner.museum +freemasonry.museum +freiburg.museum +fribourg.museum +frog.museum +fundacio.museum +furniture.museum +gallery.museum +garden.museum +gateway.museum +geelvinck.museum +gemological.museum +geology.museum +georgia.museum +giessen.museum +glas.museum +glass.museum +gorge.museum +grandrapids.museum +graz.museum +guernsey.museum +halloffame.museum +hamburg.museum +handson.museum +harvestcelebration.museum +hawaii.museum +health.museum +heimatunduhren.museum +hellas.museum +helsinki.museum +hembygdsforbund.museum +heritage.museum +histoire.museum +historical.museum +historicalsociety.museum +historichouses.museum +historisch.museum +historisches.museum +history.museum +historyofscience.museum +horology.museum +house.museum +humanities.museum +illustration.museum +imageandsound.museum +indian.museum +indiana.museum +indianapolis.museum +indianmarket.museum +intelligence.museum +interactive.museum +iraq.museum +iron.museum +isleofman.museum +jamison.museum +jefferson.museum +jerusalem.museum +jewelry.museum +jewish.museum +jewishart.museum +jfk.museum +journalism.museum +judaica.museum +judygarland.museum +juedisches.museum +juif.museum +karate.museum +karikatur.museum +kids.museum +koebenhavn.museum +koeln.museum +kunst.museum +kunstsammlung.museum +kunstunddesign.museum +labor.museum +labour.museum +lajolla.museum +lancashire.museum +landes.museum +lans.museum +läns.museum +larsson.museum +lewismiller.museum +lincoln.museum +linz.museum +living.museum +livinghistory.museum +localhistory.museum +london.museum +losangeles.museum +louvre.museum +loyalist.museum +lucerne.museum +luxembourg.museum +luzern.museum +mad.museum +madrid.museum +mallorca.museum +manchester.museum +mansion.museum +mansions.museum +manx.museum +marburg.museum +maritime.museum +maritimo.museum +maryland.museum +marylhurst.museum +media.museum +medical.museum +medizinhistorisches.museum +meeres.museum +memorial.museum +mesaverde.museum +michigan.museum +midatlantic.museum +military.museum +mill.museum +miners.museum +mining.museum +minnesota.museum +missile.museum +missoula.museum +modern.museum +moma.museum +money.museum +monmouth.museum +monticello.museum +montreal.museum +moscow.museum +motorcycle.museum +muenchen.museum +muenster.museum +mulhouse.museum +muncie.museum +museet.museum +museumcenter.museum +museumvereniging.museum +music.museum +national.museum +nationalfirearms.museum +nationalheritage.museum +nativeamerican.museum +naturalhistory.museum +naturalhistorymuseum.museum +naturalsciences.museum +nature.museum +naturhistorisches.museum +natuurwetenschappen.museum +naumburg.museum +naval.museum +nebraska.museum +neues.museum +newhampshire.museum +newjersey.museum +newmexico.museum +newport.museum +newspaper.museum +newyork.museum +niepce.museum +norfolk.museum +north.museum +nrw.museum +nuernberg.museum +nuremberg.museum +nyc.museum +nyny.museum +oceanographic.museum +oceanographique.museum +omaha.museum +online.museum +ontario.museum +openair.museum +oregon.museum +oregontrail.museum +otago.museum +oxford.museum +pacific.museum +paderborn.museum +palace.museum +paleo.museum +palmsprings.museum +panama.museum +paris.museum +pasadena.museum +pharmacy.museum +philadelphia.museum +philadelphiaarea.museum +philately.museum +phoenix.museum +photography.museum +pilots.museum +pittsburgh.museum +planetarium.museum +plantation.museum +plants.museum +plaza.museum +portal.museum +portland.museum +portlligat.museum +posts-and-telecommunications.museum +preservation.museum +presidio.museum +press.museum +project.museum +public.museum +pubol.museum +quebec.museum +railroad.museum +railway.museum +research.museum +resistance.museum +riodejaneiro.museum +rochester.museum +rockart.museum +roma.museum +russia.museum +saintlouis.museum +salem.museum +salvadordali.museum +salzburg.museum +sandiego.museum +sanfrancisco.museum +santabarbara.museum +santacruz.museum +santafe.museum +saskatchewan.museum +satx.museum +savannahga.museum +schlesisches.museum +schoenbrunn.museum +schokoladen.museum +school.museum +schweiz.museum +science.museum +scienceandhistory.museum +scienceandindustry.museum +sciencecenter.museum +sciencecenters.museum +science-fiction.museum +sciencehistory.museum +sciences.museum +sciencesnaturelles.museum +scotland.museum +seaport.museum +settlement.museum +settlers.museum +shell.museum +sherbrooke.museum +sibenik.museum +silk.museum +ski.museum +skole.museum +society.museum +sologne.museum +soundandvision.museum +southcarolina.museum +southwest.museum +space.museum +spy.museum +square.museum +stadt.museum +stalbans.museum +starnberg.museum +state.museum +stateofdelaware.museum +station.museum +steam.museum +steiermark.museum +stjohn.museum +stockholm.museum +stpetersburg.museum +stuttgart.museum +suisse.museum +surgeonshall.museum +surrey.museum +svizzera.museum +sweden.museum +sydney.museum +tank.museum +tcm.museum +technology.museum +telekommunikation.museum +television.museum +texas.museum +textile.museum +theater.museum +time.museum +timekeeping.museum +topology.museum +torino.museum +touch.museum +town.museum +transport.museum +tree.museum +trolley.museum +trust.museum +trustee.museum +uhren.museum +ulm.museum +undersea.museum +university.museum +usa.museum +usantiques.museum +usarts.museum +uscountryestate.museum +usculture.museum +usdecorativearts.museum +usgarden.museum +ushistory.museum +ushuaia.museum +uslivinghistory.museum +utah.museum +uvic.museum +valley.museum +vantaa.museum +versailles.museum +viking.museum +village.museum +virginia.museum +virtual.museum +virtuel.museum +vlaanderen.museum +volkenkunde.museum +wales.museum +wallonie.museum +war.museum +washingtondc.museum +watchandclock.museum +watch-and-clock.museum +western.museum +westfalen.museum +whaling.museum +wildlife.museum +williamsburg.museum +windmill.museum +workshop.museum +york.museum +yorkshire.museum +yosemite.museum +youth.museum +zoological.museum +zoology.museum +ירושלים.museum +иком.museum + +// mv : http://en.wikipedia.org/wiki/.mv +// "mv" included because, contra Wikipedia, google.mv exists. +mv +aero.mv +biz.mv +com.mv +coop.mv +edu.mv +gov.mv +info.mv +int.mv +mil.mv +museum.mv +name.mv +net.mv +org.mv +pro.mv + +// mw : http://www.registrar.mw/ +mw +ac.mw +biz.mw +co.mw +com.mw +coop.mw +edu.mw +gov.mw +int.mw +museum.mw +net.mw +org.mw + +// mx : http://www.nic.mx/ +// Submitted by registry 2008-06-19 +mx +com.mx +org.mx +gob.mx +edu.mx +net.mx + +// my : http://www.mynic.net.my/ +my +com.my +net.my +org.my +gov.my +edu.my +mil.my +name.my + +// mz : http://www.gobin.info/domainname/mz-template.doc +*.mz +!teledata.mz + +// na : http://www.na-nic.com.na/ +// http://www.info.na/domain/ +na +info.na +pro.na +name.na +school.na +or.na +dr.na +us.na +mx.na +ca.na +in.na +cc.na +tv.na +ws.na +mobi.na +co.na +com.na +org.na + +// name : has 2nd-level tlds, but there's no list of them +name + +// nc : http://www.cctld.nc/ +nc +asso.nc + +// ne : http://en.wikipedia.org/wiki/.ne +ne + +// net : http://en.wikipedia.org/wiki/.net +net + +// nf : http://en.wikipedia.org/wiki/.nf +nf +com.nf +net.nf +per.nf +rec.nf +web.nf +arts.nf +firm.nf +info.nf +other.nf +store.nf + +// ng : http://psg.com/dns/ng/ +ng +com.ng +edu.ng +name.ng +net.ng +org.ng +sch.ng +gov.ng +mil.ng +mobi.ng + +// ni : http://www.nic.ni/dominios.htm +*.ni + +// nl : http://www.domain-registry.nl/ace.php/c,728,122,,,,Home.html +// Confirmed by registry (with technical +// reservations) 2008-06-08 +nl + +// BV.nl will be a registry for dutch BV's (besloten vennootschap) +bv.nl + +// no : http://www.norid.no/regelverk/index.en.html +// The Norwegian registry has declined to notify us of updates. The web pages +// referenced below are the official source of the data. There is also an +// announce mailing list: +// https://postlister.uninett.no/sympa/info/norid-diskusjon +no +// Norid generic domains : http://www.norid.no/regelverk/vedlegg-c.en.html +fhs.no +vgs.no +fylkesbibl.no +folkebibl.no +museum.no +idrett.no +priv.no +// Non-Norid generic domains : http://www.norid.no/regelverk/vedlegg-d.en.html +mil.no +stat.no +dep.no +kommune.no +herad.no +// no geographical names : http://www.norid.no/regelverk/vedlegg-b.en.html +// counties +aa.no +ah.no +bu.no +fm.no +hl.no +hm.no +jan-mayen.no +mr.no +nl.no +nt.no +of.no +ol.no +oslo.no +rl.no +sf.no +st.no +svalbard.no +tm.no +tr.no +va.no +vf.no +// primary and lower secondary schools per county +gs.aa.no +gs.ah.no +gs.bu.no +gs.fm.no +gs.hl.no +gs.hm.no +gs.jan-mayen.no +gs.mr.no +gs.nl.no +gs.nt.no +gs.of.no +gs.ol.no +gs.oslo.no +gs.rl.no +gs.sf.no +gs.st.no +gs.svalbard.no +gs.tm.no +gs.tr.no +gs.va.no +gs.vf.no +// cities +akrehamn.no +åkrehamn.no +algard.no +ålgård.no +arna.no +brumunddal.no +bryne.no +bronnoysund.no +brønnøysund.no +drobak.no +drøbak.no +egersund.no +fetsund.no +floro.no +florø.no +fredrikstad.no +hokksund.no +honefoss.no +hønefoss.no +jessheim.no +jorpeland.no +jørpeland.no +kirkenes.no +kopervik.no +krokstadelva.no +langevag.no +langevåg.no +leirvik.no +mjondalen.no +mjøndalen.no +mo-i-rana.no +mosjoen.no +mosjøen.no +nesoddtangen.no +orkanger.no +osoyro.no +osøyro.no +raholt.no +råholt.no +sandnessjoen.no +sandnessjøen.no +skedsmokorset.no +slattum.no +spjelkavik.no +stathelle.no +stavern.no +stjordalshalsen.no +stjørdalshalsen.no +tananger.no +tranby.no +vossevangen.no +// communities +afjord.no +åfjord.no +agdenes.no +al.no +ål.no +alesund.no +ålesund.no +alstahaug.no +alta.no +áltá.no +alaheadju.no +álaheadju.no +alvdal.no +amli.no +åmli.no +amot.no +åmot.no +andebu.no +andoy.no +andøy.no +andasuolo.no +ardal.no +årdal.no +aremark.no +arendal.no +ås.no +aseral.no +åseral.no +asker.no +askim.no +askvoll.no +askoy.no +askøy.no +asnes.no +åsnes.no +audnedaln.no +aukra.no +aure.no +aurland.no +aurskog-holand.no +aurskog-høland.no +austevoll.no +austrheim.no +averoy.no +averøy.no +balestrand.no +ballangen.no +balat.no +bálát.no +balsfjord.no +bahccavuotna.no +báhccavuotna.no +bamble.no +bardu.no +beardu.no +beiarn.no +bajddar.no +bájddar.no +baidar.no +báidár.no +berg.no +bergen.no +berlevag.no +berlevåg.no +bearalvahki.no +bearalváhki.no +bindal.no +birkenes.no +bjarkoy.no +bjarkøy.no +bjerkreim.no +bjugn.no +bodo.no +bodø.no +badaddja.no +bådåddjå.no +budejju.no +bokn.no +bremanger.no +bronnoy.no +brønnøy.no +bygland.no +bykle.no +barum.no +bærum.no +bo.telemark.no +bø.telemark.no +bo.nordland.no +bø.nordland.no +bievat.no +bievát.no +bomlo.no +bømlo.no +batsfjord.no +båtsfjord.no +bahcavuotna.no +báhcavuotna.no +dovre.no +drammen.no +drangedal.no +dyroy.no +dyrøy.no +donna.no +dønna.no +eid.no +eidfjord.no +eidsberg.no +eidskog.no +eidsvoll.no +eigersund.no +elverum.no +enebakk.no +engerdal.no +etne.no +etnedal.no +evenes.no +evenassi.no +evenášši.no +evje-og-hornnes.no +farsund.no +fauske.no +fuossko.no +fuoisku.no +fedje.no +fet.no +finnoy.no +finnøy.no +fitjar.no +fjaler.no +fjell.no +flakstad.no +flatanger.no +flekkefjord.no +flesberg.no +flora.no +fla.no +flå.no +folldal.no +forsand.no +fosnes.no +frei.no +frogn.no +froland.no +frosta.no +frana.no +fræna.no +froya.no +frøya.no +fusa.no +fyresdal.no +forde.no +førde.no +gamvik.no +gangaviika.no +gáŋgaviika.no +gaular.no +gausdal.no +gildeskal.no +gildeskål.no +giske.no +gjemnes.no +gjerdrum.no +gjerstad.no +gjesdal.no +gjovik.no +gjøvik.no +gloppen.no +gol.no +gran.no +grane.no +granvin.no +gratangen.no +grimstad.no +grong.no +kraanghke.no +kråanghke.no +grue.no +gulen.no +hadsel.no +halden.no +halsa.no +hamar.no +hamaroy.no +habmer.no +hábmer.no +hapmir.no +hápmir.no +hammerfest.no +hammarfeasta.no +hámmárfeasta.no +haram.no +hareid.no +harstad.no +hasvik.no +aknoluokta.no +ákŋoluokta.no +hattfjelldal.no +aarborte.no +haugesund.no +hemne.no +hemnes.no +hemsedal.no +heroy.more-og-romsdal.no +herøy.møre-og-romsdal.no +heroy.nordland.no +herøy.nordland.no +hitra.no +hjartdal.no +hjelmeland.no +hobol.no +hobøl.no +hof.no +hol.no +hole.no +holmestrand.no +holtalen.no +holtålen.no +hornindal.no +horten.no +hurdal.no +hurum.no +hvaler.no +hyllestad.no +hagebostad.no +hægebostad.no +hoyanger.no +høyanger.no +hoylandet.no +høylandet.no +ha.no +hå.no +ibestad.no +inderoy.no +inderøy.no +iveland.no +jevnaker.no +jondal.no +jolster.no +jølster.no +karasjok.no +karasjohka.no +kárášjohka.no +karlsoy.no +galsa.no +gálsá.no +karmoy.no +karmøy.no +kautokeino.no +guovdageaidnu.no +klepp.no +klabu.no +klæbu.no +kongsberg.no +kongsvinger.no +kragero.no +kragerø.no +kristiansand.no +kristiansund.no +krodsherad.no +krødsherad.no +kvalsund.no +rahkkeravju.no +ráhkkerávju.no +kvam.no +kvinesdal.no +kvinnherad.no +kviteseid.no +kvitsoy.no +kvitsøy.no +kvafjord.no +kvæfjord.no +giehtavuoatna.no +kvanangen.no +kvænangen.no +navuotna.no +návuotna.no +kafjord.no +kåfjord.no +gaivuotna.no +gáivuotna.no +larvik.no +lavangen.no +lavagis.no +loabat.no +loabát.no +lebesby.no +davvesiida.no +leikanger.no +leirfjord.no +leka.no +leksvik.no +lenvik.no +leangaviika.no +leaŋgaviika.no +lesja.no +levanger.no +lier.no +lierne.no +lillehammer.no +lillesand.no +lindesnes.no +lindas.no +lindås.no +lom.no +loppa.no +lahppi.no +láhppi.no +lund.no +lunner.no +luroy.no +lurøy.no +luster.no +lyngdal.no +lyngen.no +ivgu.no +lardal.no +lerdal.no +lærdal.no +lodingen.no +lødingen.no +lorenskog.no +lørenskog.no +loten.no +løten.no +malvik.no +masoy.no +måsøy.no +muosat.no +muosát.no +mandal.no +marker.no +marnardal.no +masfjorden.no +meland.no +meldal.no +melhus.no +meloy.no +meløy.no +meraker.no +meråker.no +moareke.no +moåreke.no +midsund.no +midtre-gauldal.no +modalen.no +modum.no +molde.no +moskenes.no +moss.no +mosvik.no +malselv.no +målselv.no +malatvuopmi.no +málatvuopmi.no +namdalseid.no +aejrie.no +namsos.no +namsskogan.no +naamesjevuemie.no +nååmesjevuemie.no +laakesvuemie.no +nannestad.no +narvik.no +narviika.no +naustdal.no +nedre-eiker.no +nes.akershus.no +nes.buskerud.no +nesna.no +nesodden.no +nesseby.no +unjarga.no +unjárga.no +nesset.no +nissedal.no +nittedal.no +nord-aurdal.no +nord-fron.no +nord-odal.no +norddal.no +nordkapp.no +davvenjarga.no +davvenjárga.no +nordre-land.no +nordreisa.no +raisa.no +ráisa.no +nore-og-uvdal.no +notodden.no +naroy.no +nærøy.no +notteroy.no +nøtterøy.no +odda.no +oksnes.no +øksnes.no +oppdal.no +oppegard.no +oppegård.no +orkdal.no +orland.no +ørland.no +orskog.no +ørskog.no +orsta.no +ørsta.no +os.hedmark.no +os.hordaland.no +osen.no +osteroy.no +osterøy.no +ostre-toten.no +østre-toten.no +overhalla.no +ovre-eiker.no +øvre-eiker.no +oyer.no +øyer.no +oygarden.no +øygarden.no +oystre-slidre.no +øystre-slidre.no +porsanger.no +porsangu.no +porsáŋgu.no +porsgrunn.no +radoy.no +radøy.no +rakkestad.no +rana.no +ruovat.no +randaberg.no +rauma.no +rendalen.no +rennebu.no +rennesoy.no +rennesøy.no +rindal.no +ringebu.no +ringerike.no +ringsaker.no +rissa.no +risor.no +risør.no +roan.no +rollag.no +rygge.no +ralingen.no +rælingen.no +rodoy.no +rødøy.no +romskog.no +rømskog.no +roros.no +røros.no +rost.no +røst.no +royken.no +røyken.no +royrvik.no +røyrvik.no +rade.no +råde.no +salangen.no +siellak.no +saltdal.no +salat.no +sálát.no +sálat.no +samnanger.no +sande.more-og-romsdal.no +sande.møre-og-romsdal.no +sande.vestfold.no +sandefjord.no +sandnes.no +sandoy.no +sandøy.no +sarpsborg.no +sauda.no +sauherad.no +sel.no +selbu.no +selje.no +seljord.no +sigdal.no +siljan.no +sirdal.no +skaun.no +skedsmo.no +ski.no +skien.no +skiptvet.no +skjervoy.no +skjervøy.no +skierva.no +skiervá.no +skjak.no +skjåk.no +skodje.no +skanland.no +skånland.no +skanit.no +skánit.no +smola.no +smøla.no +snillfjord.no +snasa.no +snåsa.no +snoasa.no +snaase.no +snåase.no +sogndal.no +sokndal.no +sola.no +solund.no +songdalen.no +sortland.no +spydeberg.no +stange.no +stavanger.no +steigen.no +steinkjer.no +stjordal.no +stjørdal.no +stokke.no +stor-elvdal.no +stord.no +stordal.no +storfjord.no +omasvuotna.no +strand.no +stranda.no +stryn.no +sula.no +suldal.no +sund.no +sunndal.no +surnadal.no +sveio.no +svelvik.no +sykkylven.no +sogne.no +søgne.no +somna.no +sømna.no +sondre-land.no +søndre-land.no +sor-aurdal.no +sør-aurdal.no +sor-fron.no +sør-fron.no +sor-odal.no +sør-odal.no +sor-varanger.no +sør-varanger.no +matta-varjjat.no +mátta-várjjat.no +sorfold.no +sørfold.no +sorreisa.no +sørreisa.no +sorum.no +sørum.no +tana.no +deatnu.no +time.no +tingvoll.no +tinn.no +tjeldsund.no +dielddanuorri.no +tjome.no +tjøme.no +tokke.no +tolga.no +torsken.no +tranoy.no +tranøy.no +tromso.no +tromsø.no +tromsa.no +romsa.no +trondheim.no +troandin.no +trysil.no +trana.no +træna.no +trogstad.no +trøgstad.no +tvedestrand.no +tydal.no +tynset.no +tysfjord.no +divtasvuodna.no +divttasvuotna.no +tysnes.no +tysvar.no +tysvær.no +tonsberg.no +tønsberg.no +ullensaker.no +ullensvang.no +ulvik.no +utsira.no +vadso.no +vadsø.no +cahcesuolo.no +čáhcesuolo.no +vaksdal.no +valle.no +vang.no +vanylven.no +vardo.no +vardø.no +varggat.no +várggát.no +vefsn.no +vaapste.no +vega.no +vegarshei.no +vegårshei.no +vennesla.no +verdal.no +verran.no +vestby.no +vestnes.no +vestre-slidre.no +vestre-toten.no +vestvagoy.no +vestvågøy.no +vevelstad.no +vik.no +vikna.no +vindafjord.no +volda.no +voss.no +varoy.no +værøy.no +vagan.no +vågan.no +voagat.no +vagsoy.no +vågsøy.no +vaga.no +vågå.no +valer.ostfold.no +våler.østfold.no +valer.hedmark.no +våler.hedmark.no + +// np : http://www.mos.com.np/register.html +*.np + +// nr : http://cenpac.net.nr/dns/index.html +// Confirmed by registry 2008-06-17 +nr +biz.nr +info.nr +gov.nr +edu.nr +org.nr +net.nr +com.nr + +// nu : http://en.wikipedia.org/wiki/.nu +nu + +// nz : http://en.wikipedia.org/wiki/.nz +// Confirmed by registry 2014-05-19 +nz +ac.nz +co.nz +cri.nz +geek.nz +gen.nz +govt.nz +health.nz +iwi.nz +kiwi.nz +maori.nz +mil.nz +māori.nz +net.nz +org.nz +parliament.nz +school.nz + +// om : http://en.wikipedia.org/wiki/.om +om +co.om +com.om +edu.om +gov.om +med.om +museum.om +net.om +org.om +pro.om + +// org : http://en.wikipedia.org/wiki/.org +org + +// pa : http://www.nic.pa/ +// Some additional second level "domains" resolve directly as hostnames, such as +// pannet.pa, so we add a rule for "pa". +pa +ac.pa +gob.pa +com.pa +org.pa +sld.pa +edu.pa +net.pa +ing.pa +abo.pa +med.pa +nom.pa + +// pe : https://www.nic.pe/InformeFinalComision.pdf +pe +edu.pe +gob.pe +nom.pe +mil.pe +org.pe +com.pe +net.pe + +// pf : http://www.gobin.info/domainname/formulaire-pf.pdf +pf +com.pf +org.pf +edu.pf + +// pg : http://en.wikipedia.org/wiki/.pg +*.pg + +// ph : http://www.domains.ph/FAQ2.asp +// Submitted by registry 2008-06-13 +ph +com.ph +net.ph +org.ph +gov.ph +edu.ph +ngo.ph +mil.ph +i.ph + +// pk : http://pk5.pknic.net.pk/pk5/msgNamepk.PK +pk +com.pk +net.pk +edu.pk +org.pk +fam.pk +biz.pk +web.pk +gov.pk +gob.pk +gok.pk +gon.pk +gop.pk +gos.pk +info.pk + +// pl http://www.dns.pl/english/index.html +// confirmed on 26.09.2014 from Bogna Tchórzewska +pl +com.pl +net.pl +org.pl +info.pl +waw.pl +gov.pl +// pl functional domains (http://www.dns.pl/english/index.html) +aid.pl +agro.pl +atm.pl +auto.pl +biz.pl +edu.pl +gmina.pl +gsm.pl +mail.pl +miasta.pl +media.pl +mil.pl +nieruchomosci.pl +nom.pl +pc.pl +powiat.pl +priv.pl +realestate.pl +rel.pl +sex.pl +shop.pl +sklep.pl +sos.pl +szkola.pl +targi.pl +tm.pl +tourism.pl +travel.pl +turystyka.pl +// Government domains (administred by ippt.gov.pl) +uw.gov.pl +um.gov.pl +ug.gov.pl +upow.gov.pl +starostwo.gov.pl +so.gov.pl +sr.gov.pl +po.gov.pl +pa.gov.pl +// pl regional domains (http://www.dns.pl/english/index.html) +augustow.pl +babia-gora.pl +bedzin.pl +beskidy.pl +bialowieza.pl +bialystok.pl +bielawa.pl +bieszczady.pl +boleslawiec.pl +bydgoszcz.pl +bytom.pl +cieszyn.pl +czeladz.pl +czest.pl +dlugoleka.pl +elblag.pl +elk.pl +glogow.pl +gniezno.pl +gorlice.pl +grajewo.pl +ilawa.pl +jaworzno.pl +jelenia-gora.pl +jgora.pl +kalisz.pl +kazimierz-dolny.pl +karpacz.pl +kartuzy.pl +kaszuby.pl +katowice.pl +kepno.pl +ketrzyn.pl +klodzko.pl +kobierzyce.pl +kolobrzeg.pl +konin.pl +konskowola.pl +kutno.pl +lapy.pl +lebork.pl +legnica.pl +lezajsk.pl +limanowa.pl +lomza.pl +lowicz.pl +lubin.pl +lukow.pl +malbork.pl +malopolska.pl +mazowsze.pl +mazury.pl +mielec.pl +mielno.pl +mragowo.pl +naklo.pl +nowaruda.pl +nysa.pl +olawa.pl +olecko.pl +olkusz.pl +olsztyn.pl +opoczno.pl +opole.pl +ostroda.pl +ostroleka.pl +ostrowiec.pl +ostrowwlkp.pl +pila.pl +pisz.pl +podhale.pl +podlasie.pl +polkowice.pl +pomorze.pl +pomorskie.pl +prochowice.pl +pruszkow.pl +przeworsk.pl +pulawy.pl +radom.pl +rawa-maz.pl +rybnik.pl +rzeszow.pl +sanok.pl +sejny.pl +slask.pl +slupsk.pl +sosnowiec.pl +stalowa-wola.pl +skoczow.pl +starachowice.pl +stargard.pl +suwalki.pl +swidnica.pl +swiebodzin.pl +swinoujscie.pl +szczecin.pl +szczytno.pl +tarnobrzeg.pl +tgory.pl +turek.pl +tychy.pl +ustka.pl +walbrzych.pl +warmia.pl +warszawa.pl +wegrow.pl +wielun.pl +wlocl.pl +wloclawek.pl +wodzislaw.pl +wolomin.pl +wroclaw.pl +zachpomor.pl +zagan.pl +zarow.pl +zgora.pl +zgorzelec.pl + +// pm : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf +pm + +// pn : http://www.government.pn/PnRegistry/policies.htm +pn +gov.pn +co.pn +org.pn +edu.pn +net.pn + +// post : http://en.wikipedia.org/wiki/.post +post + +// pr : http://www.nic.pr/index.asp?f=1 +pr +com.pr +net.pr +org.pr +gov.pr +edu.pr +isla.pr +pro.pr +biz.pr +info.pr +name.pr +// these aren't mentioned on nic.pr, but on http://en.wikipedia.org/wiki/.pr +est.pr +prof.pr +ac.pr + +// pro : http://www.nic.pro/support_faq.htm +pro +aca.pro +bar.pro +cpa.pro +jur.pro +law.pro +med.pro +eng.pro + +// ps : http://en.wikipedia.org/wiki/.ps +// http://www.nic.ps/registration/policy.html#reg +ps +edu.ps +gov.ps +sec.ps +plo.ps +com.ps +org.ps +net.ps + +// pt : http://online.dns.pt/dns/start_dns +pt +net.pt +gov.pt +org.pt +edu.pt +int.pt +publ.pt +com.pt +nome.pt + +// pw : http://en.wikipedia.org/wiki/.pw +pw +co.pw +ne.pw +or.pw +ed.pw +go.pw +belau.pw + +// py : http://www.nic.py/pautas.html#seccion_9 +// Confirmed by registry 2012-10-03 +py +com.py +coop.py +edu.py +gov.py +mil.py +net.py +org.py + +// qa : http://domains.qa/en/ +qa +com.qa +edu.qa +gov.qa +mil.qa +name.qa +net.qa +org.qa +sch.qa + +// re : http://www.afnic.re/obtenir/chartes/nommage-re/annexe-descriptifs +re +com.re +asso.re +nom.re + +// ro : http://www.rotld.ro/ +ro +com.ro +org.ro +tm.ro +nt.ro +nom.ro +info.ro +rec.ro +arts.ro +firm.ro +store.ro +www.ro + +// rs : http://en.wikipedia.org/wiki/.rs +rs +co.rs +org.rs +edu.rs +ac.rs +gov.rs +in.rs + +// ru : http://www.cctld.ru/ru/docs/aktiv_8.php +// Industry domains +ru +ac.ru +com.ru +edu.ru +int.ru +net.ru +org.ru +pp.ru +// Geographical domains +adygeya.ru +altai.ru +amur.ru +arkhangelsk.ru +astrakhan.ru +bashkiria.ru +belgorod.ru +bir.ru +bryansk.ru +buryatia.ru +cbg.ru +chel.ru +chelyabinsk.ru +chita.ru +chukotka.ru +chuvashia.ru +dagestan.ru +dudinka.ru +e-burg.ru +grozny.ru +irkutsk.ru +ivanovo.ru +izhevsk.ru +jar.ru +joshkar-ola.ru +kalmykia.ru +kaluga.ru +kamchatka.ru +karelia.ru +kazan.ru +kchr.ru +kemerovo.ru +khabarovsk.ru +khakassia.ru +khv.ru +kirov.ru +koenig.ru +komi.ru +kostroma.ru +krasnoyarsk.ru +kuban.ru +kurgan.ru +kursk.ru +lipetsk.ru +magadan.ru +mari.ru +mari-el.ru +marine.ru +mordovia.ru +// mosreg.ru Bug 1090800 - removed at request of Aleksey Konstantinov +msk.ru +murmansk.ru +nalchik.ru +nnov.ru +nov.ru +novosibirsk.ru +nsk.ru +omsk.ru +orenburg.ru +oryol.ru +palana.ru +penza.ru +perm.ru +ptz.ru +rnd.ru +ryazan.ru +sakhalin.ru +samara.ru +saratov.ru +simbirsk.ru +smolensk.ru +spb.ru +stavropol.ru +stv.ru +surgut.ru +tambov.ru +tatarstan.ru +tom.ru +tomsk.ru +tsaritsyn.ru +tsk.ru +tula.ru +tuva.ru +tver.ru +tyumen.ru +udm.ru +udmurtia.ru +ulan-ude.ru +vladikavkaz.ru +vladimir.ru +vladivostok.ru +volgograd.ru +vologda.ru +voronezh.ru +vrn.ru +vyatka.ru +yakutia.ru +yamal.ru +yaroslavl.ru +yekaterinburg.ru +yuzhno-sakhalinsk.ru +// More geographical domains +amursk.ru +baikal.ru +cmw.ru +fareast.ru +jamal.ru +kms.ru +k-uralsk.ru +kustanai.ru +kuzbass.ru +magnitka.ru +mytis.ru +nakhodka.ru +nkz.ru +norilsk.ru +oskol.ru +pyatigorsk.ru +rubtsovsk.ru +snz.ru +syzran.ru +vdonsk.ru +zgrad.ru +// State domains +gov.ru +mil.ru +// Technical domains +test.ru + +// rw : http://www.nic.rw/cgi-bin/policy.pl +rw +gov.rw +net.rw +edu.rw +ac.rw +com.rw +co.rw +int.rw +mil.rw +gouv.rw + +// sa : http://www.nic.net.sa/ +sa +com.sa +net.sa +org.sa +gov.sa +med.sa +pub.sa +edu.sa +sch.sa + +// sb : http://www.sbnic.net.sb/ +// Submitted by registry 2008-06-08 +sb +com.sb +edu.sb +gov.sb +net.sb +org.sb + +// sc : http://www.nic.sc/ +sc +com.sc +gov.sc +net.sc +org.sc +edu.sc + +// sd : http://www.isoc.sd/sudanic.isoc.sd/billing_pricing.htm +// Submitted by registry 2008-06-17 +sd +com.sd +net.sd +org.sd +edu.sd +med.sd +tv.sd +gov.sd +info.sd + +// se : http://en.wikipedia.org/wiki/.se +// Submitted by registry 2014-03-18 +se +a.se +ac.se +b.se +bd.se +brand.se +c.se +d.se +e.se +f.se +fh.se +fhsk.se +fhv.se +g.se +h.se +i.se +k.se +komforb.se +kommunalforbund.se +komvux.se +l.se +lanbib.se +m.se +n.se +naturbruksgymn.se +o.se +org.se +p.se +parti.se +pp.se +press.se +r.se +s.se +t.se +tm.se +u.se +w.se +x.se +y.se +z.se + +// sg : http://www.nic.net.sg/page/registration-policies-procedures-and-guidelines +sg +com.sg +net.sg +org.sg +gov.sg +edu.sg +per.sg + +// sh : http://www.nic.sh/registrar.html +sh +com.sh +net.sh +gov.sh +org.sh +mil.sh + +// si : http://en.wikipedia.org/wiki/.si +si + +// sj : No registrations at this time. +// Submitted by registry 2008-06-16 +sj + +// sk : http://en.wikipedia.org/wiki/.sk +// list of 2nd level domains ? +sk + +// sl : http://www.nic.sl +// Submitted by registry 2008-06-12 +sl +com.sl +net.sl +edu.sl +gov.sl +org.sl + +// sm : http://en.wikipedia.org/wiki/.sm +sm + +// sn : http://en.wikipedia.org/wiki/.sn +sn +art.sn +com.sn +edu.sn +gouv.sn +org.sn +perso.sn +univ.sn + +// so : http://www.soregistry.com/ +so +com.so +net.so +org.so + +// sr : http://en.wikipedia.org/wiki/.sr +sr + +// st : http://www.nic.st/html/policyrules/ +st +co.st +com.st +consulado.st +edu.st +embaixada.st +gov.st +mil.st +net.st +org.st +principe.st +saotome.st +store.st + +// su : http://en.wikipedia.org/wiki/.su +su +adygeya.su +arkhangelsk.su +balashov.su +bashkiria.su +bryansk.su +dagestan.su +grozny.su +ivanovo.su +kalmykia.su +kaluga.su +karelia.su +khakassia.su +krasnodar.su +kurgan.su +lenug.su +mordovia.su +msk.su +murmansk.su +nalchik.su +nov.su +obninsk.su +penza.su +pokrovsk.su +sochi.su +spb.su +togliatti.su +troitsk.su +tula.su +tuva.su +vladikavkaz.su +vladimir.su +vologda.su + +// sv : http://www.svnet.org.sv/niveldos.pdf +sv +com.sv +edu.sv +gob.sv +org.sv +red.sv + +// sx : http://en.wikipedia.org/wiki/.sx +// Confirmed by registry 2012-05-31 +sx +gov.sx + +// sy : http://en.wikipedia.org/wiki/.sy +// see also: http://www.gobin.info/domainname/sy.doc +sy +edu.sy +gov.sy +net.sy +mil.sy +com.sy +org.sy + +// sz : http://en.wikipedia.org/wiki/.sz +// http://www.sispa.org.sz/ +sz +co.sz +ac.sz +org.sz + +// tc : http://en.wikipedia.org/wiki/.tc +tc + +// td : http://en.wikipedia.org/wiki/.td +td + +// tel: http://en.wikipedia.org/wiki/.tel +// http://www.telnic.org/ +tel + +// tf : http://en.wikipedia.org/wiki/.tf +tf + +// tg : http://en.wikipedia.org/wiki/.tg +// http://www.nic.tg/ +tg + +// th : http://en.wikipedia.org/wiki/.th +// Submitted by registry 2008-06-17 +th +ac.th +co.th +go.th +in.th +mi.th +net.th +or.th + +// tj : http://www.nic.tj/policy.html +tj +ac.tj +biz.tj +co.tj +com.tj +edu.tj +go.tj +gov.tj +int.tj +mil.tj +name.tj +net.tj +nic.tj +org.tj +test.tj +web.tj + +// tk : http://en.wikipedia.org/wiki/.tk +tk + +// tl : http://en.wikipedia.org/wiki/.tl +tl +gov.tl + +// tm : http://www.nic.tm/local.html +tm +com.tm +co.tm +org.tm +net.tm +nom.tm +gov.tm +mil.tm +edu.tm + +// tn : http://en.wikipedia.org/wiki/.tn +// http://whois.ati.tn/ +tn +com.tn +ens.tn +fin.tn +gov.tn +ind.tn +intl.tn +nat.tn +net.tn +org.tn +info.tn +perso.tn +tourism.tn +edunet.tn +rnrt.tn +rns.tn +rnu.tn +mincom.tn +agrinet.tn +defense.tn +turen.tn + +// to : http://en.wikipedia.org/wiki/.to +// Submitted by registry 2008-06-17 +to +com.to +gov.to +net.to +org.to +edu.to +mil.to + +// tp : No registrations at this time. +// Submitted by Ryan Sleevi 2014-01-03 +tp + +// subTLDs: https://www.nic.tr/forms/eng/policies.pdf +// and: https://www.nic.tr/forms/politikalar.pdf +// Submitted by 2014-07-19 +tr +com.tr +info.tr +biz.tr +net.tr +org.tr +web.tr +gen.tr +tv.tr +av.tr +dr.tr +bbs.tr +name.tr +tel.tr +gov.tr +bel.tr +pol.tr +mil.tr +k12.tr +edu.tr +kep.tr + +// Used by Northern Cyprus +nc.tr + +// Used by government agencies of Northern Cyprus +gov.nc.tr + +// travel : http://en.wikipedia.org/wiki/.travel +travel + +// tt : http://www.nic.tt/ +tt +co.tt +com.tt +org.tt +net.tt +biz.tt +info.tt +pro.tt +int.tt +coop.tt +jobs.tt +mobi.tt +travel.tt +museum.tt +aero.tt +name.tt +gov.tt +edu.tt + +// tv : http://en.wikipedia.org/wiki/.tv +// Not listing any 2LDs as reserved since none seem to exist in practice, +// Wikipedia notwithstanding. +tv + +// tw : http://en.wikipedia.org/wiki/.tw +tw +edu.tw +gov.tw +mil.tw +com.tw +net.tw +org.tw +idv.tw +game.tw +ebiz.tw +club.tw +網路.tw +組織.tw +商業.tw + +// tz : http://www.tznic.or.tz/index.php/domains +// Confirmed by registry 2013-01-22 +tz +ac.tz +co.tz +go.tz +hotel.tz +info.tz +me.tz +mil.tz +mobi.tz +ne.tz +or.tz +sc.tz +tv.tz + +// ua : https://hostmaster.ua/policy/?ua +// Submitted by registry 2012-04-27 +ua +// ua 2LD +com.ua +edu.ua +gov.ua +in.ua +net.ua +org.ua +// ua geographic names +// https://hostmaster.ua/2ld/ +cherkassy.ua +cherkasy.ua +chernigov.ua +chernihiv.ua +chernivtsi.ua +chernovtsy.ua +ck.ua +cn.ua +cr.ua +crimea.ua +cv.ua +dn.ua +dnepropetrovsk.ua +dnipropetrovsk.ua +dominic.ua +donetsk.ua +dp.ua +if.ua +ivano-frankivsk.ua +kh.ua +kharkiv.ua +kharkov.ua +kherson.ua +khmelnitskiy.ua +khmelnytskyi.ua +kiev.ua +kirovograd.ua +km.ua +kr.ua +krym.ua +ks.ua +kv.ua +kyiv.ua +lg.ua +lt.ua +lugansk.ua +lutsk.ua +lv.ua +lviv.ua +mk.ua +mykolaiv.ua +nikolaev.ua +od.ua +odesa.ua +odessa.ua +pl.ua +poltava.ua +rivne.ua +rovno.ua +rv.ua +sb.ua +sebastopol.ua +sevastopol.ua +sm.ua +sumy.ua +te.ua +ternopil.ua +uz.ua +uzhgorod.ua +vinnica.ua +vinnytsia.ua +vn.ua +volyn.ua +yalta.ua +zaporizhzhe.ua +zaporizhzhia.ua +zhitomir.ua +zhytomyr.ua +zp.ua +zt.ua + +// Private registries in .ua +co.ua +pp.ua + +// ug : https://www.registry.co.ug/ +ug +co.ug +or.ug +ac.ug +sc.ug +go.ug +ne.ug +com.ug +org.ug + +// uk : http://en.wikipedia.org/wiki/.uk +// Submitted by registry +uk +ac.uk +co.uk +gov.uk +ltd.uk +me.uk +net.uk +nhs.uk +org.uk +plc.uk +police.uk +*.sch.uk + +// us : http://en.wikipedia.org/wiki/.us +us +dni.us +fed.us +isa.us +kids.us +nsn.us +// us geographic names +ak.us +al.us +ar.us +as.us +az.us +ca.us +co.us +ct.us +dc.us +de.us +fl.us +ga.us +gu.us +hi.us +ia.us +id.us +il.us +in.us +ks.us +ky.us +la.us +ma.us +md.us +me.us +mi.us +mn.us +mo.us +ms.us +mt.us +nc.us +nd.us +ne.us +nh.us +nj.us +nm.us +nv.us +ny.us +oh.us +ok.us +or.us +pa.us +pr.us +ri.us +sc.us +sd.us +tn.us +tx.us +ut.us +vi.us +vt.us +va.us +wa.us +wi.us +wv.us +wy.us +// The registrar notes several more specific domains available in each state, +// such as state.*.us, dst.*.us, etc., but resolution of these is somewhat +// haphazard; in some states these domains resolve as addresses, while in others +// only subdomains are available, or even nothing at all. We include the +// most common ones where it's clear that different sites are different +// entities. +k12.ak.us +k12.al.us +k12.ar.us +k12.as.us +k12.az.us +k12.ca.us +k12.co.us +k12.ct.us +k12.dc.us +k12.de.us +k12.fl.us +k12.ga.us +k12.gu.us +// k12.hi.us Bug 614565 - Hawaii has a state-wide DOE login +k12.ia.us +k12.id.us +k12.il.us +k12.in.us +k12.ks.us +k12.ky.us +k12.la.us +k12.ma.us +k12.md.us +k12.me.us +k12.mi.us +k12.mn.us +k12.mo.us +k12.ms.us +k12.mt.us +k12.nc.us +// k12.nd.us Bug 1028347 - Removed at request of Travis Rosso +k12.ne.us +k12.nh.us +k12.nj.us +k12.nm.us +k12.nv.us +k12.ny.us +k12.oh.us +k12.ok.us +k12.or.us +k12.pa.us +k12.pr.us +k12.ri.us +k12.sc.us +// k12.sd.us Bug 934131 - Removed at request of James Booze +k12.tn.us +k12.tx.us +k12.ut.us +k12.vi.us +k12.vt.us +k12.va.us +k12.wa.us +k12.wi.us +// k12.wv.us Bug 947705 - Removed at request of Verne Britton +k12.wy.us +cc.ak.us +cc.al.us +cc.ar.us +cc.as.us +cc.az.us +cc.ca.us +cc.co.us +cc.ct.us +cc.dc.us +cc.de.us +cc.fl.us +cc.ga.us +cc.gu.us +cc.hi.us +cc.ia.us +cc.id.us +cc.il.us +cc.in.us +cc.ks.us +cc.ky.us +cc.la.us +cc.ma.us +cc.md.us +cc.me.us +cc.mi.us +cc.mn.us +cc.mo.us +cc.ms.us +cc.mt.us +cc.nc.us +cc.nd.us +cc.ne.us +cc.nh.us +cc.nj.us +cc.nm.us +cc.nv.us +cc.ny.us +cc.oh.us +cc.ok.us +cc.or.us +cc.pa.us +cc.pr.us +cc.ri.us +cc.sc.us +cc.sd.us +cc.tn.us +cc.tx.us +cc.ut.us +cc.vi.us +cc.vt.us +cc.va.us +cc.wa.us +cc.wi.us +cc.wv.us +cc.wy.us +lib.ak.us +lib.al.us +lib.ar.us +lib.as.us +lib.az.us +lib.ca.us +lib.co.us +lib.ct.us +lib.dc.us +lib.de.us +lib.fl.us +lib.ga.us +lib.gu.us +lib.hi.us +lib.ia.us +lib.id.us +lib.il.us +lib.in.us +lib.ks.us +lib.ky.us +lib.la.us +lib.ma.us +lib.md.us +lib.me.us +lib.mi.us +lib.mn.us +lib.mo.us +lib.ms.us +lib.mt.us +lib.nc.us +lib.nd.us +lib.ne.us +lib.nh.us +lib.nj.us +lib.nm.us +lib.nv.us +lib.ny.us +lib.oh.us +lib.ok.us +lib.or.us +lib.pa.us +lib.pr.us +lib.ri.us +lib.sc.us +lib.sd.us +lib.tn.us +lib.tx.us +lib.ut.us +lib.vi.us +lib.vt.us +lib.va.us +lib.wa.us +lib.wi.us +// lib.wv.us Bug 941670 - Removed at request of Larry W Arnold +lib.wy.us +// k12.ma.us contains school districts in Massachusetts. The 4LDs are +// managed indepedently except for private (PVT), charter (CHTR) and +// parochial (PAROCH) schools. Those are delegated dorectly to the +// 5LD operators. +pvt.k12.ma.us +chtr.k12.ma.us +paroch.k12.ma.us + +// uy : http://www.nic.org.uy/ +uy +com.uy +edu.uy +gub.uy +mil.uy +net.uy +org.uy + +// uz : http://www.reg.uz/ +uz +co.uz +com.uz +net.uz +org.uz + +// va : http://en.wikipedia.org/wiki/.va +va + +// vc : http://en.wikipedia.org/wiki/.vc +// Submitted by registry 2008-06-13 +vc +com.vc +net.vc +org.vc +gov.vc +mil.vc +edu.vc + +// ve : https://registro.nic.ve/ +// Confirmed by registry 2012-10-04 +// Updated 2014-05-20 - Bug 940478 +ve +arts.ve +co.ve +com.ve +e12.ve +edu.ve +firm.ve +gob.ve +gov.ve +info.ve +int.ve +mil.ve +net.ve +org.ve +rec.ve +store.ve +tec.ve +web.ve + +// vg : http://en.wikipedia.org/wiki/.vg +vg + +// vi : http://www.nic.vi/newdomainform.htm +// http://www.nic.vi/Domain_Rules/body_domain_rules.html indicates some other +// TLDs are "reserved", such as edu.vi and gov.vi, but doesn't actually say they +// are available for registration (which they do not seem to be). +vi +co.vi +com.vi +k12.vi +net.vi +org.vi + +// vn : https://www.dot.vn/vnnic/vnnic/domainregistration.jsp +vn +com.vn +net.vn +org.vn +edu.vn +gov.vn +int.vn +ac.vn +biz.vn +info.vn +name.vn +pro.vn +health.vn + +// vu : http://en.wikipedia.org/wiki/.vu +// http://www.vunic.vu/ +vu +com.vu +edu.vu +net.vu +org.vu + +// wf : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf +wf + +// ws : http://en.wikipedia.org/wiki/.ws +// http://samoanic.ws/index.dhtml +ws +com.ws +net.ws +org.ws +gov.ws +edu.ws + +// yt : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf +yt + +// IDN ccTLDs +// Please sort by ISO 3166 ccTLD, then punicode string +// when submitting patches and follow this format: +// ("" ) : +// [optional sponsoring org] +// + +// xn--mgbaam7a8h ("Emerat" Arabic) : AE +// http://nic.ae/english/arabicdomain/rules.jsp +امارات + +// xn--54b7fta0cc ("Bangla" Bangla) : BD +বাংলা + +// xn--fiqs8s ("China" Chinese-Han-Simplified <.Zhongguo>) : CN +// CNNIC +// http://cnnic.cn/html/Dir/2005/10/11/3218.htm +中国 + +// xn--fiqz9s ("China" Chinese-Han-Traditional <.Zhongguo>) : CN +// CNNIC +// http://cnnic.cn/html/Dir/2005/10/11/3218.htm +中國 + +// xn--lgbbat1ad8j ("Algeria / Al Jazair" Arabic) : DZ +الجزائر + +// xn--wgbh1c ("Egypt" Arabic .masr) : EG +// http://www.dotmasr.eg/ +مصر + +// xn--node ("ge" Georgian (Mkhedruli)) : GE +გე + +// xn--j6w193g ("Hong Kong" Chinese-Han) : HK +// https://www2.hkirc.hk/register/rules.jsp +香港 + +// xn--h2brj9c ("Bharat" Devanagari) : IN +// India +भारत + +// xn--mgbbh1a71e ("Bharat" Arabic) : IN +// India +بھارت + +// xn--fpcrj9c3d ("Bharat" Telugu) : IN +// India +భారత్ + +// xn--gecrj9c ("Bharat" Gujarati) : IN +// India +ભારત + +// xn--s9brj9c ("Bharat" Gurmukhi) : IN +// India +ਭਾਰਤ + +// xn--45brj9c ("Bharat" Bengali) : IN +// India +ভারত + +// xn--xkc2dl3a5ee0h ("India" Tamil) : IN +// India +இந்தியா + +// xn--mgba3a4f16a ("Iran" Persian) : IR +ایران + +// xn--mgba3a4fra ("Iran" Arabic) : IR +ايران + +// xn--mgbayh7gpa ("al-Ordon" Arabic) : JO +// National Information Technology Center (NITC) +// Royal Scientific Society, Al-Jubeiha +الاردن + +// xn--3e0b707e ("Republic of Korea" Hangul) : KR +한국 + +// xn--80ao21a ("Kaz" Kazakh) : KZ +қаз + +// xn--fzc2c9e2c ("Lanka" Sinhalese-Sinhala) : LK +// http://nic.lk +ලංකා + +// xn--xkc2al3hye2a ("Ilangai" Tamil) : LK +// http://nic.lk +இலங்கை + +// xn--mgbc0a9azcg ("Morocco / al-Maghrib" Arabic) : MA +المغرب + +// xn--l1acc ("mon" Mongolian) : MN +мон + +// xn--mgbx4cd0ab ("Malaysia" Malay) : MY +مليسيا + +// xn--mgb9awbf ("Oman" Arabic) : OM +عمان + +// xn--ygbi2ammx ("Falasteen" Arabic) : PS +// The Palestinian National Internet Naming Authority (PNINA) +// http://www.pnina.ps +فلسطين + +// xn--90a3ac ("srb" Cyrillic) : RS +// http://www.rnids.rs/en/the-.срб-domain +срб +пр.срб +орг.срб +обр.срб +од.срб +упр.срб +ак.срб + +// xn--p1ai ("rf" Russian-Cyrillic) : RU +// http://www.cctld.ru/en/docs/rulesrf.php +рф + +// xn--wgbl6a ("Qatar" Arabic) : QA +// http://www.ict.gov.qa/ +قطر + +// xn--mgberp4a5d4ar ("AlSaudiah" Arabic) : SA +// http://www.nic.net.sa/ +السعودية + +// xn--mgberp4a5d4a87g ("AlSaudiah" Arabic) variant : SA +السعودیة + +// xn--mgbqly7c0a67fbc ("AlSaudiah" Arabic) variant : SA +السعودیۃ + +// xn--mgbqly7cvafr ("AlSaudiah" Arabic) variant : SA +السعوديه + +// xn--ogbpf8fl ("Syria" Arabic) : SY +سورية + +// xn--mgbtf8fl ("Syria" Arabic) variant : SY +سوريا + +// xn--yfro4i67o Singapore ("Singapore" Chinese-Han) : SG +新加坡 + +// xn--clchc0ea0b2g2a9gcd ("Singapore" Tamil) : SG +சிங்கப்பூர் + +// xn--o3cw4h ("Thai" Thai) : TH +// http://www.thnic.co.th +ไทย + +// xn--pgbs0dh ("Tunis") : TN +// http://nic.tn +تونس + +// xn--kpry57d ("Taiwan" Chinese-Han-Traditional) : TW +// http://www.twnic.net/english/dn/dn_07a.htm +台灣 + +// xn--kprw13d ("Taiwan" Chinese-Han-Simplified) : TW +// http://www.twnic.net/english/dn/dn_07a.htm +台湾 + +// xn--nnx388a ("Taiwan") variant : TW +臺灣 + +// xn--j1amh ("ukr" Cyrillic) : UA +укр + +// xn--mgb2ddes ("AlYemen" Arabic) : YE +اليمن + +// xxx : http://icmregistry.com +xxx + +// ye : http://www.y.net.ye/services/domain_name.htm +*.ye + +// za : http://www.zadna.org.za/slds.html +*.za + +// zm : http://en.wikipedia.org/wiki/.zm +*.zm + +// zw : http://en.wikipedia.org/wiki/.zw +*.zw + + +// List of new gTLDs imported from https://newgtlds.icann.org/newgtlds.csv on 2015-04-07T06:02:08Z + +// aaa : 2015-02-26 American Automobile Association, Inc. +aaa + +// abb : 2014-10-24 ABB Ltd +abb + +// abbott : 2014-07-24 Abbott Laboratories, Inc. +abbott + +// abogado : 2014-04-24 Top Level Domain Holdings Limited +abogado + +// academy : 2013-11-07 Half Oaks, LLC +academy + +// accenture : 2014-08-15 Accenture plc +accenture + +// accountant : 2014-11-20 dot Accountant Limited +accountant + +// accountants : 2014-03-20 Knob Town, LLC +accountants + +// aco : 2015-01-08 ACO Severin Ahlmann GmbH & Co. KG +aco + +// active : 2014-05-01 The Active Network, Inc +active + +// actor : 2013-12-12 United TLD Holdco Ltd. +actor + +// ads : 2014-12-04 Charleston Road Registry Inc. +ads + +// adult : 2014-10-16 ICM Registry AD LLC +adult + +// aeg : 2015-03-19 Aktiebolaget Electrolux +aeg + +// afl : 2014-10-02 Australian Football League +afl + +// africa : 2014-03-24 ZA Central Registry NPC trading as Registry.Africa +africa + +// africamagic : 2015-03-05 Electronic Media Network (Pty) Ltd +africamagic + +// agency : 2013-11-14 Steel Falls, LLC +agency + +// aig : 2014-12-18 American International Group, Inc. +aig + +// airforce : 2014-03-06 United TLD Holdco Ltd. +airforce + +// airtel : 2014-10-24 Bharti Airtel Limited +airtel + +// alibaba : 2015-01-15 Alibaba Group Holding Limited +alibaba + +// alipay : 2015-01-15 Alibaba Group Holding Limited +alipay + +// allfinanz : 2014-07-03 Allfinanz Deutsche Vermögensberatung Aktiengesellschaft +allfinanz + +// alsace : 2014-07-02 REGION D ALSACE +alsace + +// amsterdam : 2014-07-24 Gemeente Amsterdam +amsterdam + +// analytics : 2014-12-18 Campus IP LLC +analytics + +// android : 2014-08-07 Charleston Road Registry Inc. +android + +// anquan : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD. +anquan + +// apartments : 2014-12-11 June Maple, LLC +apartments + +// aquarelle : 2014-07-24 Aquarelle.com +aquarelle + +// aramco : 2014-11-20 Aramco Services Company +aramco + +// archi : 2014-02-06 STARTING DOT LIMITED +archi + +// army : 2014-03-06 United TLD Holdco Ltd. +army + +// arte : 2014-12-11 Association Relative à la Télévision Européenne G.E.I.E. +arte + +// associates : 2014-03-06 Baxter Hill, LLC +associates + +// attorney : 2014-03-20 +attorney + +// auction : 2014-03-20 +auction + +// audio : 2014-03-20 Uniregistry, Corp. +audio + +// author : 2014-12-18 Amazon EU S.à r.l. +author + +// auto : 2014-11-13 Uniregistry, Corp. +auto + +// autos : 2014-01-09 DERAutos, LLC +autos + +// avianca : 2015-01-08 Aerovias del Continente Americano S.A. Avianca +avianca + +// axa : 2013-12-19 AXA SA +axa + +// azure : 2014-12-18 Microsoft Corporation +azure + +// baidu : 2015-01-08 Baidu, Inc. +baidu + +// band : 2014-06-12 +band + +// bank : 2014-09-25 fTLD Registry Services LLC +bank + +// bar : 2013-12-12 Punto 2012 Sociedad Anonima Promotora de Inversion de Capital Variable +bar + +// barcelona : 2014-07-24 Municipi de Barcelona +barcelona + +// barclaycard : 2014-11-20 Barclays Bank PLC +barclaycard + +// barclays : 2014-11-20 Barclays Bank PLC +barclays + +// bargains : 2013-11-14 Half Hallow, LLC +bargains + +// bauhaus : 2014-04-17 Werkhaus GmbH +bauhaus + +// bayern : 2014-01-23 Bayern Connect GmbH +bayern + +// bbc : 2014-12-18 British Broadcasting Corporation +bbc + +// bbva : 2014-10-02 BANCO BILBAO VIZCAYA ARGENTARIA, S.A. +bbva + +// bcg : 2015-04-02 The Boston Consulting Group, Inc. +bcg + +// bcn : 2014-07-24 Municipi de Barcelona +bcn + +// beer : 2014-01-09 Top Level Domain Holdings Limited +beer + +// bentley : 2014-12-18 Bentley Motors Limited +bentley + +// berlin : 2013-10-31 dotBERLIN GmbH & Co. KG +berlin + +// best : 2013-12-19 BestTLD Pty Ltd +best + +// bharti : 2014-01-09 Bharti Enterprises (Holding) Private Limited +bharti + +// bible : 2014-06-19 American Bible Society +bible + +// bid : 2013-12-19 dot Bid Limited +bid + +// bike : 2013-08-27 Grand Hollow, LLC +bike + +// bing : 2014-12-18 Microsoft Corporation +bing + +// bingo : 2014-12-04 Sand Cedar, LLC +bingo + +// bio : 2014-03-06 STARTING DOT LIMITED +bio + +// black : 2014-01-16 Afilias Limited +black + +// blackfriday : 2014-01-16 Uniregistry, Corp. +blackfriday + +// bloomberg : 2014-07-17 Bloomberg IP Holdings LLC +bloomberg + +// blue : 2013-11-07 Afilias Limited +blue + +// bms : 2014-10-30 Bristol-Myers Squibb Company +bms + +// bmw : 2014-01-09 Bayerische Motoren Werke Aktiengesellschaft +bmw + +// bnl : 2014-07-24 Banca Nazionale del Lavoro +bnl + +// bnpparibas : 2014-05-29 BNP Paribas +bnpparibas + +// boats : 2014-12-04 DERBoats, LLC +boats + +// bom : 2014-10-16 Núcleo de Informação e Coordenação do Ponto BR - NIC.br +bom + +// bond : 2014-06-05 Bond University Limited +bond + +// boo : 2014-01-30 Charleston Road Registry Inc. +boo + +// boots : 2015-01-08 THE BOOTS COMPANY PLC +boots + +// bot : 2014-12-18 Amazon EU S.à r.l. +bot + +// boutique : 2013-11-14 Over Galley, LLC +boutique + +// bradesco : 2014-12-18 Banco Bradesco S.A. +bradesco + +// bridgestone : 2014-12-18 Bridgestone Corporation +bridgestone + +// broadway : 2014-12-22 Celebrate Broadway, Inc. +broadway + +// broker : 2014-12-11 IG Group Holdings PLC +broker + +// brother : 2015-01-29 Brother Industries, Ltd. +brother + +// brussels : 2014-02-06 DNS.be vzw +brussels + +// budapest : 2013-11-21 Top Level Domain Holdings Limited +budapest + +// build : 2013-11-07 Plan Bee LLC +build + +// builders : 2013-11-07 Atomic Madison, LLC +builders + +// business : 2013-11-07 Spring Cross, LLC +business + +// buy : 2014-12-18 Amazon EU S.à r.l. +buy + +// buzz : 2013-10-02 DOTSTRATEGY CO. +buzz + +// bzh : 2014-02-27 Association www.bzh +bzh + +// cab : 2013-10-24 Half Sunset, LLC +cab + +// cafe : 2015-02-11 Pioneer Canyon, LLC +cafe + +// cal : 2014-07-24 Charleston Road Registry Inc. +cal + +// call : 2014-12-18 Amazon EU S.à r.l. +call + +// camera : 2013-08-27 Atomic Maple, LLC +camera + +// camp : 2013-11-07 Delta Dynamite, LLC +camp + +// cancerresearch : 2014-05-15 Australian Cancer Research Foundation +cancerresearch + +// canon : 2014-09-12 Canon Inc. +canon + +// capetown : 2014-03-24 ZA Central Registry NPC trading as ZA Central Registry +capetown + +// capital : 2014-03-06 Delta Mill, LLC +capital + +// car : 2015-01-22 Charleston Road Registry Inc. +car + +// caravan : 2013-12-12 Caravan International, Inc. +caravan + +// cards : 2013-12-05 Foggy Hollow, LLC +cards + +// care : 2014-03-06 Goose Cross +care + +// career : 2013-10-09 dotCareer LLC +career + +// careers : 2013-10-02 Wild Corner, LLC +careers + +// cars : 2014-11-13 Uniregistry, Corp. +cars + +// cartier : 2014-06-23 Richemont DNS Inc. +cartier + +// casa : 2013-11-21 Top Level Domain Holdings Limited +casa + +// cash : 2014-03-06 Delta Lake, LLC +cash + +// casino : 2014-12-18 Binky Sky, LLC +casino + +// catering : 2013-12-05 New Falls. LLC +catering + +// cba : 2014-06-26 COMMONWEALTH BANK OF AUSTRALIA +cba + +// cbn : 2014-08-22 The Christian Broadcasting Network, Inc. +cbn + +// center : 2013-11-07 Tin Mill, LLC +center + +// ceo : 2013-11-07 CEOTLD Pty Ltd +ceo + +// cern : 2014-06-05 European Organization for Nuclear Research (\ +cern + +// cfa : 2014-08-28 CFA Institute +cfa + +// cfd : 2014-12-11 IG Group Holdings PLC +cfd + +// channel : 2014-05-08 Charleston Road Registry Inc. +channel + +// chat : 2014-12-04 Sand Fields, LLC +chat + +// cheap : 2013-11-14 Sand Cover, LLC +cheap + +// chloe : 2014-10-16 Richemont DNS Inc. +chloe + +// christmas : 2013-11-21 Uniregistry, Corp. +christmas + +// chrome : 2014-07-24 Charleston Road Registry Inc. +chrome + +// church : 2014-02-06 Holly Fields, LLC +church + +// cipriani : 2015-02-19 Hotel Cipriani Srl +cipriani + +// circle : 2014-12-18 Amazon EU S.à r.l. +circle + +// cisco : 2014-12-22 Cisco Technology, Inc. +cisco + +// citic : 2014-01-09 CITIC Group Corporation +citic + +// city : 2014-05-29 Snow Sky, LLC +city + +// cityeats : 2014-12-11 Lifestyle Domain Holdings, Inc. +cityeats + +// claims : 2014-03-20 Black Corner, LLC +claims + +// cleaning : 2013-12-05 Fox Shadow, LLC +cleaning + +// click : 2014-06-05 Uniregistry, Corp. +click + +// clinic : 2014-03-20 Goose Park, LLC +clinic + +// clothing : 2013-08-27 Steel Lake, LLC +clothing + +// club : 2013-11-08 .CLUB DOMAINS, LLC +club + +// coach : 2014-10-09 Koko Island, LLC +coach + +// codes : 2013-10-31 Puff Willow, LLC +codes + +// coffee : 2013-10-17 Trixy Cover, LLC +coffee + +// college : 2014-01-16 XYZ.COM LLC +college + +// cologne : 2014-02-05 NetCologne Gesellschaft für Telekommunikation mbH +cologne + +// commbank : 2014-06-26 COMMONWEALTH BANK OF AUSTRALIA +commbank + +// community : 2013-12-05 Fox Orchard, LLC +community + +// company : 2013-11-07 Silver Avenue, LLC +company + +// computer : 2013-10-24 Pine Mill, LLC +computer + +// comsec : 2015-01-08 VeriSign, Inc. +comsec + +// condos : 2013-12-05 Pine House, LLC +condos + +// construction : 2013-09-16 Fox Dynamite, LLC +construction + +// consulting : 2013-12-05 +consulting + +// contact : 2015-01-08 Top Level Spectrum, Inc. +contact + +// contractors : 2013-09-10 Magic Woods, LLC +contractors + +// cooking : 2013-11-21 Top Level Domain Holdings Limited +cooking + +// cool : 2013-11-14 Koko Lake, LLC +cool + +// corsica : 2014-09-25 Collectivité Territoriale de Corse +corsica + +// country : 2013-12-19 Top Level Domain Holdings Limited +country + +// coupon : 2015-02-26 Amazon EU S.à r.l. +coupon + +// coupons : 2015-03-26 Black Island, LLC +coupons + +// courses : 2014-12-04 OPEN UNIVERSITIES AUSTRALIA PTY LTD +courses + +// credit : 2014-03-20 Snow Shadow, LLC +credit + +// creditcard : 2014-03-20 Binky Frostbite, LLC +creditcard + +// creditunion : 2015-01-22 CUNA Performance Resources, LLC +creditunion + +// cricket : 2014-10-09 dot Cricket Limited +cricket + +// crown : 2014-10-24 Crown Equipment Corporation +crown + +// crs : 2014-04-03 Federated Co-operatives Limited +crs + +// cruises : 2013-12-05 Spring Way, LLC +cruises + +// csc : 2014-09-25 Alliance-One Services, Inc. +csc + +// cuisinella : 2014-04-03 SALM S.A.S. +cuisinella + +// cymru : 2014-05-08 Nominet UK +cymru + +// cyou : 2015-01-22 Beijing Gamease Age Digital Technology Co., Ltd. +cyou + +// dabur : 2014-02-06 Dabur India Limited +dabur + +// dad : 2014-01-23 Charleston Road Registry Inc. +dad + +// dance : 2013-10-24 United TLD Holdco Ltd. +dance + +// date : 2014-11-20 dot Date Limited +date + +// dating : 2013-12-05 Pine Fest, LLC +dating + +// datsun : 2014-03-27 NISSAN MOTOR CO., LTD. +datsun + +// day : 2014-01-30 Charleston Road Registry Inc. +day + +// dclk : 2014-11-20 Charleston Road Registry Inc. +dclk + +// dealer : 2014-12-22 Dealer Dot Com, Inc. +dealer + +// deals : 2014-05-22 Sand Sunset, LLC +deals + +// degree : 2014-03-06 +degree + +// delivery : 2014-09-11 Steel Station, LLC +delivery + +// dell : 2014-10-24 Dell Inc. +dell + +// delta : 2015-02-19 Delta Air Lines, Inc. +delta + +// democrat : 2013-10-24 United TLD Holdco Ltd. +democrat + +// dental : 2014-03-20 Tin Birch, LLC +dental + +// dentist : 2014-03-20 +dentist + +// desi : 2013-11-14 Desi Networks LLC +desi + +// design : 2014-11-07 Top Level Design, LLC +design + +// dev : 2014-10-16 Charleston Road Registry Inc. +dev + +// diamonds : 2013-09-22 John Edge, LLC +diamonds + +// diet : 2014-06-26 Uniregistry, Corp. +diet + +// digital : 2014-03-06 Dash Park, LLC +digital + +// direct : 2014-04-10 Half Trail, LLC +direct + +// directory : 2013-09-20 Extra Madison, LLC +directory + +// discount : 2014-03-06 Holly Hill, LLC +discount + +// dnp : 2013-12-13 Dai Nippon Printing Co., Ltd. +dnp + +// docs : 2014-10-16 Charleston Road Registry Inc. +docs + +// dog : 2014-12-04 Koko Mill, LLC +dog + +// doha : 2014-09-18 Communications Regulatory Authority (CRA) +doha + +// domains : 2013-10-17 Sugar Cross, LLC +domains + +// doosan : 2014-04-03 Doosan Corporation +doosan + +// download : 2014-11-20 dot Support Limited +download + +// drive : 2015-03-05 Charleston Road Registry Inc. +drive + +// dstv : 2015-03-12 MultiChoice (Proprietary) Limited +dstv + +// dubai : 2015-01-01 Dubai Smart Government Department +dubai + +// durban : 2014-03-24 ZA Central Registry NPC trading as ZA Central Registry +durban + +// dvag : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG +dvag + +// earth : 2014-12-04 Interlink Co., Ltd. +earth + +// eat : 2014-01-23 Charleston Road Registry Inc. +eat + +// edeka : 2014-12-18 EDEKA Verband kaufmännischer Genossenschaften e.V. +edeka + +// education : 2013-11-07 Brice Way, LLC +education + +// email : 2013-10-31 Spring Madison, LLC +email + +// emerck : 2014-04-03 Merck KGaA +emerck + +// energy : 2014-09-11 Binky Birch, LLC +energy + +// engineer : 2014-03-06 United TLD Holdco Ltd. +engineer + +// engineering : 2014-03-06 Romeo Canyon +engineering + +// enterprises : 2013-09-20 Snow Oaks, LLC +enterprises + +// epson : 2014-12-04 Seiko Epson Corporation +epson + +// equipment : 2013-08-27 Corn Station, LLC +equipment + +// erni : 2014-04-03 ERNI Group Holding AG +erni + +// esq : 2014-05-08 Charleston Road Registry Inc. +esq + +// estate : 2013-08-27 Trixy Park, LLC +estate + +// eurovision : 2014-04-24 European Broadcasting Union (EBU) +eurovision + +// eus : 2013-12-12 Puntueus Fundazioa +eus + +// events : 2013-12-05 Pioneer Maple, LLC +events + +// everbank : 2014-05-15 EverBank +everbank + +// exchange : 2014-03-06 Spring Falls, LLC +exchange + +// expert : 2013-11-21 Magic Pass, LLC +expert + +// exposed : 2013-12-05 Victor Beach, LLC +exposed + +// express : 2015-02-11 Sea Sunset, LLC +express + +// fage : 2014-12-18 Fage International S.A. +fage + +// fail : 2014-03-06 Atomic Pipe, LLC +fail + +// fairwinds : 2014-11-13 FairWinds Partners, LLC +fairwinds + +// faith : 2014-11-20 dot Faith Limited +faith + +// family : 2015-04-02 Bitter Galley, LLC +family + +// fan : 2014-03-06 +fan + +// fans : 2014-11-07 Asiamix Digital Limited +fans + +// farm : 2013-11-07 Just Maple, LLC +farm + +// fashion : 2014-07-03 Top Level Domain Holdings Limited +fashion + +// fast : 2014-12-18 Amazon EU S.à r.l. +fast + +// feedback : 2013-12-19 Top Level Spectrum, Inc. +feedback + +// ferrero : 2014-12-18 Ferrero Trading Lux S.A. +ferrero + +// film : 2015-01-08 Motion Picture Domain Registry Pty Ltd +film + +// final : 2014-10-16 Núcleo de Informação e Coordenação do Ponto BR - NIC.br +final + +// finance : 2014-03-20 Cotton Cypress, LLC +finance + +// financial : 2014-03-06 Just Cover, LLC +financial + +// firestone : 2014-12-18 Bridgestone Corporation +firestone + +// firmdale : 2014-03-27 Firmdale Holdings Limited +firmdale + +// fish : 2013-12-12 Fox Woods, LLC +fish + +// fishing : 2013-11-21 Top Level Domain Holdings Limited +fishing + +// fit : 2014-11-07 Top Level Domain Holdings Limited +fit + +// fitness : 2014-03-06 Brice Orchard, LLC +fitness + +// flickr : 2015-04-02 Yahoo! Domain Services Inc. +flickr + +// flights : 2013-12-05 Fox Station, LLC +flights + +// florist : 2013-11-07 Half Cypress, LLC +florist + +// flowers : 2014-10-09 Uniregistry, Corp. +flowers + +// flsmidth : 2014-07-24 FLSmidth A/S +flsmidth + +// fly : 2014-05-08 Charleston Road Registry Inc. +fly + +// foo : 2014-01-23 Charleston Road Registry Inc. +foo + +// football : 2014-12-18 Foggy Farms, LLC +football + +// ford : 2014-11-13 Ford Motor Company +ford + +// forex : 2014-12-11 IG Group Holdings PLC +forex + +// forsale : 2014-05-22 +forsale + +// forum : 2015-04-02 Fegistry, LLC +forum + +// foundation : 2013-12-05 John Dale, LLC +foundation + +// frl : 2014-05-15 FRLregistry B.V. +frl + +// frogans : 2013-12-19 OP3FT +frogans + +// frontier : 2015-02-05 Frontier Communications Corporation +frontier + +// fund : 2014-03-20 John Castle, LLC +fund + +// furniture : 2014-03-20 Lone Fields, LLC +furniture + +// futbol : 2013-09-20 +futbol + +// fyi : 2015-04-02 Silver Tigers, LLC +fyi + +// gal : 2013-11-07 Asociación puntoGAL +gal + +// gallery : 2013-09-13 Sugar House, LLC +gallery + +// gallup : 2015-02-19 Gallup, Inc. +gallup + +// garden : 2014-06-26 Top Level Domain Holdings Limited +garden + +// gbiz : 2014-07-17 Charleston Road Registry Inc. +gbiz + +// gdn : 2014-07-31 Joint Stock Company \ +gdn + +// gea : 2014-12-04 GEA Group Aktiengesellschaft +gea + +// gent : 2014-01-23 COMBELL GROUP NV/SA +gent + +// genting : 2015-03-12 Resorts World Inc Pte. Ltd. +genting + +// ggee : 2014-01-09 GMO Internet, Inc. +ggee + +// gift : 2013-10-17 Uniregistry, Corp. +gift + +// gifts : 2014-07-03 Goose Sky, LLC +gifts + +// gives : 2014-03-06 United TLD Holdco Ltd. +gives + +// giving : 2014-11-13 Giving Limited +giving + +// glass : 2013-11-07 Black Cover, LLC +glass + +// gle : 2014-07-24 Charleston Road Registry Inc. +gle + +// global : 2014-04-17 Dot GLOBAL AS +global + +// globo : 2013-12-19 Globo Comunicação e Participações S.A +globo + +// gmail : 2014-05-01 Charleston Road Registry Inc. +gmail + +// gmo : 2014-01-09 GMO Internet, Inc. +gmo + +// gmx : 2014-04-24 1&1 Mail & Media GmbH +gmx + +// gold : 2015-01-22 June Edge, LLC +gold + +// goldpoint : 2014-11-20 YODOBASHI CAMERA CO.,LTD. +goldpoint + +// golf : 2014-12-18 Lone falls, LLC +golf + +// goo : 2014-12-18 NTT Resonant Inc. +goo + +// goog : 2014-11-20 Charleston Road Registry Inc. +goog + +// google : 2014-07-24 Charleston Road Registry Inc. +google + +// gop : 2014-01-16 Republican State Leadership Committee, Inc. +gop + +// got : 2014-12-18 Amazon EU S.à r.l. +got + +// gotv : 2015-03-12 MultiChoice (Proprietary) Limited +gotv + +// graphics : 2013-09-13 Over Madison, LLC +graphics + +// gratis : 2014-03-20 Pioneer Tigers, LLC +gratis + +// green : 2014-05-08 Afilias Limited +green + +// gripe : 2014-03-06 Corn Sunset, LLC +gripe + +// group : 2014-08-15 Romeo Town, LLC +group + +// gucci : 2014-11-13 Guccio Gucci S.p.a. +gucci + +// guge : 2014-08-28 Charleston Road Registry Inc. +guge + +// guide : 2013-09-13 Snow Moon, LLC +guide + +// guitars : 2013-11-14 Uniregistry, Corp. +guitars + +// guru : 2013-08-27 Pioneer Cypress, LLC +guru + +// hamburg : 2014-02-20 Hamburg Top-Level-Domain GmbH +hamburg + +// hangout : 2014-11-13 Charleston Road Registry Inc. +hangout + +// haus : 2013-12-05 +haus + +// hdfcbank : 2015-02-12 HDFC Bank Limited +hdfcbank + +// health : 2015-02-11 DotHealth, LLC +health + +// healthcare : 2014-06-12 Silver Glen, LLC +healthcare + +// help : 2014-06-26 Uniregistry, Corp. +help + +// helsinki : 2015-02-05 City of Helsinki +helsinki + +// here : 2014-02-06 Charleston Road Registry Inc. +here + +// hermes : 2014-07-10 HERMES INTERNATIONAL +hermes + +// hiphop : 2014-03-06 Uniregistry, Corp. +hiphop + +// hitachi : 2014-10-31 Hitachi, Ltd. +hitachi + +// hiv : 2014-03-13 dotHIV gemeinnuetziger e.V. +hiv + +// hockey : 2015-03-19 Half Willow, LLC +hockey + +// holdings : 2013-08-27 John Madison, LLC +holdings + +// holiday : 2013-11-07 Goose Woods, LLC +holiday + +// homedepot : 2015-04-02 Homer TLC, Inc. +homedepot + +// homes : 2014-01-09 DERHomes, LLC +homes + +// honda : 2014-12-18 Honda Motor Co., Ltd. +honda + +// horse : 2013-11-21 Top Level Domain Holdings Limited +horse + +// host : 2014-04-17 DotHost Inc. +host + +// hosting : 2014-05-29 Uniregistry, Corp. +hosting + +// hoteles : 2015-03-05 Travel Reservations SRL +hoteles + +// hotmail : 2014-12-18 Microsoft Corporation +hotmail + +// house : 2013-11-07 Sugar Park, LLC +house + +// how : 2014-01-23 Charleston Road Registry Inc. +how + +// hsbc : 2014-10-24 HSBC Holdings PLC +hsbc + +// htc : 2015-04-02 HTC corporation +htc + +// ibm : 2014-07-31 International Business Machines Corporation +ibm + +// icbc : 2015-02-19 Industrial and Commercial Bank of China Limited +icbc + +// ice : 2014-10-30 IntercontinentalExchange, Inc. +ice + +// icu : 2015-01-08 One.com A/S +icu + +// ifm : 2014-01-30 ifm electronic gmbh +ifm + +// iinet : 2014-07-03 Connect West Pty. Ltd. +iinet + +// immo : 2014-07-10 Auburn Bloom, LLC +immo + +// immobilien : 2013-11-07 United TLD Holdco Ltd. +immobilien + +// industries : 2013-12-05 Outer House, LLC +industries + +// infiniti : 2014-03-27 NISSAN MOTOR CO., LTD. +infiniti + +// ing : 2014-01-23 Charleston Road Registry Inc. +ing + +// ink : 2013-12-05 Top Level Design, LLC +ink + +// institute : 2013-11-07 Outer Maple, LLC +institute + +// insurance : 2015-02-19 fTLD Registry Services LLC +insurance + +// insure : 2014-03-20 Pioneer Willow, LLC +insure + +// international : 2013-11-07 Wild Way, LLC +international + +// investments : 2014-03-20 Holly Glen, LLC +investments + +// ipiranga : 2014-08-28 Ipiranga Produtos de Petroleo S.A. +ipiranga + +// irish : 2014-08-07 Dot-Irish LLC +irish + +// iselect : 2015-02-11 iSelect Ltd +iselect + +// ist : 2014-08-28 Istanbul Metropolitan Municipality +ist + +// istanbul : 2014-08-28 Istanbul Metropolitan Municipality +istanbul + +// itau : 2014-10-02 Itau Unibanco Holding S.A. +itau + +// iwc : 2014-06-23 Richemont DNS Inc. +iwc + +// jaguar : 2014-11-13 Jaguar Land Rover Ltd +jaguar + +// java : 2014-06-19 Oracle Corporation +java + +// jcb : 2014-11-20 JCB Co., Ltd. +jcb + +// jetzt : 2014-01-09 New TLD Company AB +jetzt + +// jewelry : 2015-03-05 Wild Bloom, LLC +jewelry + +// jio : 2015-04-02 Affinity Names, Inc. +jio + +// jlc : 2014-12-04 Richemont DNS Inc. +jlc + +// jll : 2015-04-02 Jones Lang LaSalle Incorporated +jll + +// jmp : 2015-03-26 Matrix IP LLC +jmp + +// joburg : 2014-03-24 ZA Central Registry NPC trading as ZA Central Registry +joburg + +// jot : 2014-12-18 Amazon EU S.à r.l. +jot + +// joy : 2014-12-18 Amazon EU S.à r.l. +joy + +// jprs : 2014-09-18 Japan Registry Services Co., Ltd. +jprs + +// juegos : 2014-03-20 Uniregistry, Corp. +juegos + +// kaufen : 2013-11-07 United TLD Holdco Ltd. +kaufen + +// kddi : 2014-09-12 KDDI CORPORATION +kddi + +// kfh : 2014-12-04 Kuwait Finance House +kfh + +// kim : 2013-09-23 Afilias Limited +kim + +// kinder : 2014-11-07 Ferrero Trading Lux S.A. +kinder + +// kitchen : 2013-09-20 Just Goodbye, LLC +kitchen + +// kiwi : 2013-09-20 DOT KIWI LIMITED +kiwi + +// koeln : 2014-01-09 NetCologne Gesellschaft für Telekommunikation mbH +koeln + +// komatsu : 2015-01-08 Komatsu Ltd. +komatsu + +// kpn : 2015-01-08 Koninklijke KPN N.V. +kpn + +// krd : 2013-12-05 KRG Department of Information Technology +krd + +// kred : 2013-12-19 KredTLD Pty Ltd +kred + +// kyknet : 2015-03-05 Electronic Media Network (Pty) Ltd +kyknet + +// kyoto : 2014-11-07 Academic Institution: Kyoto Jyoho Gakuen +kyoto + +// lacaixa : 2014-01-09 CAIXA D'ESTALVIS I PENSIONS DE BARCELONA +lacaixa + +// lancaster : 2015-02-12 LANCASTER +lancaster + +// land : 2013-09-10 Pine Moon, LLC +land + +// landrover : 2014-11-13 Jaguar Land Rover Ltd +landrover + +// lasalle : 2015-04-02 Jones Lang LaSalle Incorporated +lasalle + +// lat : 2014-10-16 ECOM-LAC Federaciòn de Latinoamèrica y el Caribe para Internet y el Comercio Electrònico +lat + +// latrobe : 2014-06-16 La Trobe University +latrobe + +// law : 2015-01-22 Minds + Machines Group Limited +law + +// lawyer : 2014-03-20 +lawyer + +// lds : 2014-03-20 IRI Domain Management, LLC (\ +lds + +// lease : 2014-03-06 Victor Trail, LLC +lease + +// leclerc : 2014-08-07 A.C.D. LEC Association des Centres Distributeurs Edouard Leclerc +leclerc + +// legal : 2014-10-16 Blue Falls, LLC +legal + +// lgbt : 2014-05-08 Afilias Limited +lgbt + +// liaison : 2014-10-02 Liaison Technologies, Incorporated +liaison + +// lidl : 2014-09-18 Schwarz Domains und Services GmbH & Co. KG +lidl + +// life : 2014-02-06 Trixy Oaks, LLC +life + +// lifeinsurance : 2015-01-15 American Council of Life Insurers +lifeinsurance + +// lifestyle : 2014-12-11 Lifestyle Domain Holdings, Inc. +lifestyle + +// lighting : 2013-08-27 John McCook, LLC +lighting + +// like : 2014-12-18 Amazon EU S.à r.l. +like + +// limited : 2014-03-06 Big Fest, LLC +limited + +// limo : 2013-10-17 Hidden Frostbite, LLC +limo + +// lincoln : 2014-11-13 Ford Motor Company +lincoln + +// linde : 2014-12-04 Linde Aktiengesellschaft +linde + +// link : 2013-11-14 Uniregistry, Corp. +link + +// live : 2014-12-04 Half Woods, LLC +live + +// lixil : 2015-03-19 LIXIL Group Corporation +lixil + +// loan : 2014-11-20 dot Loan Limited +loan + +// loans : 2014-03-20 June Woods, LLC +loans + +// lol : 2015-01-30 Uniregistry, Corp. +lol + +// london : 2013-11-14 Dot London Domains Limited +london + +// lotte : 2014-11-07 Lotte Holdings Co., Ltd. +lotte + +// lotto : 2014-04-10 Afilias Limited +lotto + +// love : 2014-12-22 Merchant Law Group LLP +love + +// ltd : 2014-09-25 Over Corner, LLC +ltd + +// ltda : 2014-04-17 DOMAIN ROBOT SERVICOS DE HOSPEDAGEM NA INTERNET LTDA +ltda + +// lupin : 2014-11-07 LUPIN LIMITED +lupin + +// luxe : 2014-01-09 Top Level Domain Holdings Limited +luxe + +// luxury : 2013-10-17 Luxury Partners, LLC +luxury + +// madrid : 2014-05-01 Comunidad de Madrid +madrid + +// maif : 2014-10-02 Mutuelle Assurance Instituteur France (MAIF) +maif + +// maison : 2013-12-05 Victor Frostbite, LLC +maison + +// makeup : 2015-01-15 L'Oréal +makeup + +// man : 2014-12-04 MAN SE +man + +// management : 2013-11-07 John Goodbye, LLC +management + +// mango : 2013-10-24 PUNTO FA S.L. +mango + +// market : 2014-03-06 +market + +// marketing : 2013-11-07 Fern Pass, LLC +marketing + +// markets : 2014-12-11 IG Group Holdings PLC +markets + +// marriott : 2014-10-09 Marriott Worldwide Corporation +marriott + +// mba : 2015-04-02 Lone Hollow, LLC +mba + +// media : 2014-03-06 Grand Glen, LLC +media + +// meet : 2014-01-16 +meet + +// melbourne : 2014-05-29 The Crown in right of the State of Victoria, represented by its Department of State Development, Business and Innovation +melbourne + +// meme : 2014-01-30 Charleston Road Registry Inc. +meme + +// memorial : 2014-10-16 Dog Beach, LLC +memorial + +// men : 2015-02-26 Exclusive Registry Limited +men + +// menu : 2013-09-11 Wedding TLD2, LLC +menu + +// meo : 2014-11-07 PT Comunicacoes S.A. +meo + +// miami : 2013-12-19 Top Level Domain Holdings Limited +miami + +// microsoft : 2014-12-18 Microsoft Corporation +microsoft + +// mini : 2014-01-09 Bayerische Motoren Werke Aktiengesellschaft +mini + +// mma : 2014-11-07 MMA IARD +mma + +// mnet : 2015-03-05 Electronic Media Network (Pty) Ltd +mnet + +// mobily : 2014-12-18 GreenTech Consultancy Company W.L.L. +mobily + +// moda : 2013-11-07 United TLD Holdco Ltd. +moda + +// moe : 2013-11-13 Interlink Co., Ltd. +moe + +// moi : 2014-12-18 Amazon EU S.à r.l. +moi + +// monash : 2013-09-30 Monash University +monash + +// money : 2014-10-16 Outer McCook, LLC +money + +// montblanc : 2014-06-23 Richemont DNS Inc. +montblanc + +// mormon : 2013-12-05 IRI Domain Management, LLC (\ +mormon + +// mortgage : 2014-03-20 +mortgage + +// moscow : 2013-12-19 Foundation for Assistance for Internet Technologies and Infrastructure Development (FAITID) +moscow + +// motorcycles : 2014-01-09 DERMotorcycles, LLC +motorcycles + +// mov : 2014-01-30 Charleston Road Registry Inc. +mov + +// movie : 2015-02-05 New Frostbite, LLC +movie + +// movistar : 2014-10-16 Telefónica S.A. +movistar + +// mtn : 2014-12-04 MTN Dubai Limited +mtn + +// mtpc : 2014-11-20 Mitsubishi Tanabe Pharma Corporation +mtpc + +// mtr : 2015-03-12 MTR Corporation Limited +mtr + +// multichoice : 2015-03-12 MultiChoice (Proprietary) Limited +multichoice + +// mutual : 2015-04-02 Northwestern Mutual MU TLD Registry, LLC +mutual + +// mzansimagic : 2015-03-05 Electronic Media Network (Pty) Ltd +mzansimagic + +// nadex : 2014-12-11 IG Group Holdings PLC +nadex + +// nagoya : 2013-10-24 GMO Registry, Inc. +nagoya + +// naspers : 2015-02-12 Intelprop (Proprietary) Limited +naspers + +// natura : 2015-03-12 NATURA COSMÉTICOS S.A. +natura + +// navy : 2014-03-06 United TLD Holdco Ltd. +navy + +// nec : 2015-01-08 NEC Corporation +nec + +// netbank : 2014-06-26 COMMONWEALTH BANK OF AUSTRALIA +netbank + +// network : 2013-11-14 Trixy Manor, LLC +network + +// neustar : 2013-12-05 NeuStar, Inc. +neustar + +// new : 2014-01-30 Charleston Road Registry Inc. +new + +// news : 2014-12-18 +news + +// nexus : 2014-07-24 Charleston Road Registry Inc. +nexus + +// ngo : 2014-03-06 Public Interest Registry +ngo + +// nhk : 2014-02-13 Japan Broadcasting Corporation (NHK) +nhk + +// nico : 2014-12-04 DWANGO Co., Ltd. +nico + +// ninja : 2013-11-07 United TLD Holdco Ltd. +ninja + +// nissan : 2014-03-27 NISSAN MOTOR CO., LTD. +nissan + +// nokia : 2015-01-08 Nokia Corporation +nokia + +// norton : 2014-12-04 Symantec Corporation +norton + +// nowruz : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti. +nowruz + +// nra : 2014-05-22 NRA Holdings Company, INC. +nra + +// nrw : 2013-11-21 Minds + Machines GmbH +nrw + +// ntt : 2014-10-31 NIPPON TELEGRAPH AND TELEPHONE CORPORATION +ntt + +// nyc : 2014-01-23 The City of New York by and through the New York City Department of Information Technology & Telecommunications +nyc + +// obi : 2014-09-25 OBI Group Holding SE & Co. KGaA +obi + +// office : 2015-03-12 Microsoft Corporation +office + +// okinawa : 2013-12-05 BusinessRalliart Inc. +okinawa + +// omega : 2015-01-08 The Swatch Group Ltd +omega + +// one : 2014-11-07 One.com A/S +one + +// ong : 2014-03-06 Public Interest Registry +ong + +// onl : 2013-09-16 I-Registry Ltd. +onl + +// online : 2015-01-15 DotOnline Inc. +online + +// ooo : 2014-01-09 INFIBEAM INCORPORATION LIMITED +ooo + +// oracle : 2014-06-19 Oracle Corporation +oracle + +// orange : 2015-03-12 Orange Brand Services Limited +orange + +// organic : 2014-03-27 Afilias Limited +organic + +// orientexpress : 2015-02-05 Belmond Ltd. +orientexpress + +// osaka : 2014-09-04 Interlink Co., Ltd. +osaka + +// otsuka : 2013-10-11 Otsuka Holdings Co., Ltd. +otsuka + +// ovh : 2014-01-16 OVH SAS +ovh + +// page : 2014-12-04 Charleston Road Registry Inc. +page + +// pamperedchef : 2015-02-05 The Pampered Chef, Ltd. +pamperedchef + +// panerai : 2014-11-07 Richemont DNS Inc. +panerai + +// paris : 2014-01-30 City of Paris +paris + +// pars : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti. +pars + +// partners : 2013-12-05 Magic Glen, LLC +partners + +// parts : 2013-12-05 Sea Goodbye, LLC +parts + +// party : 2014-09-11 Blue Sky Registry Limited +party + +// passagens : 2015-03-05 Travel Reservations SRL +passagens + +// payu : 2015-02-12 MIH PayU B.V. +payu + +// pharmacy : 2014-06-19 National Association of Boards of Pharmacy +pharmacy + +// philips : 2014-11-07 Koninklijke Philips N.V. +philips + +// photo : 2013-11-14 Uniregistry, Corp. +photo + +// photography : 2013-09-20 Sugar Glen, LLC +photography + +// photos : 2013-10-17 Sea Corner, LLC +photos + +// physio : 2014-05-01 PhysBiz Pty Ltd +physio + +// piaget : 2014-10-16 Richemont DNS Inc. +piaget + +// pics : 2013-11-14 Uniregistry, Corp. +pics + +// pictet : 2014-06-26 Pictet Europe S.A. +pictet + +// pictures : 2014-03-06 Foggy Sky, LLC +pictures + +// pid : 2015-01-08 Top Level Spectrum, Inc. +pid + +// pin : 2014-12-18 Amazon EU S.à r.l. +pin + +// pink : 2013-10-01 Afilias Limited +pink + +// pizza : 2014-06-26 Foggy Moon, LLC +pizza + +// place : 2014-04-24 Snow Galley, LLC +place + +// play : 2015-03-05 Charleston Road Registry Inc. +play + +// plumbing : 2013-09-10 Spring Tigers, LLC +plumbing + +// plus : 2015-02-05 Sugar Mill, LLC +plus + +// pohl : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG +pohl + +// poker : 2014-07-03 Afilias Domains No. 5 Limited +poker + +// porn : 2014-10-16 ICM Registry PN LLC +porn + +// praxi : 2013-12-05 Praxi S.p.A. +praxi + +// press : 2014-04-03 DotPress Inc. +press + +// prod : 2014-01-23 Charleston Road Registry Inc. +prod + +// productions : 2013-12-05 Magic Birch, LLC +productions + +// prof : 2014-07-24 Charleston Road Registry Inc. +prof + +// promo : 2014-12-18 Play.PROMO Oy +promo + +// properties : 2013-12-05 Big Pass, LLC +properties + +// property : 2014-05-22 Uniregistry, Corp. +property + +// pub : 2013-12-12 United TLD Holdco Ltd. +pub + +// qpon : 2013-11-14 dotCOOL, Inc. +qpon + +// quebec : 2013-12-19 PointQuébec Inc +quebec + +// quest : 2015-03-26 Quest ION Limited +quest + +// racing : 2014-12-04 Premier Registry Limited +racing + +// read : 2014-12-18 Amazon EU S.à r.l. +read + +// realtor : 2014-05-29 Real Estate Domains LLC +realtor + +// realty : 2015-03-19 Fegistry, LLC +realty + +// recipes : 2013-10-17 Grand Island, LLC +recipes + +// red : 2013-11-07 Afilias Limited +red + +// redstone : 2014-10-31 Redstone Haute Couture Co., Ltd. +redstone + +// redumbrella : 2015-03-26 Travelers TLD, LLC +redumbrella + +// rehab : 2014-03-06 United TLD Holdco Ltd. +rehab + +// reise : 2014-03-13 dotreise GmbH +reise + +// reisen : 2014-03-06 New Cypress, LLC +reisen + +// reit : 2014-09-04 National Association of Real Estate Investment Trusts, Inc. +reit + +// reliance : 2015-04-02 Reliance Industries Limited +reliance + +// ren : 2013-12-12 Beijing Qianxiang Wangjing Technology Development Co., Ltd. +ren + +// rent : 2014-12-04 DERRent, LLC +rent + +// rentals : 2013-12-05 Big Hollow,LLC +rentals + +// repair : 2013-11-07 Lone Sunset, LLC +repair + +// report : 2013-12-05 Binky Glen, LLC +report + +// republican : 2014-03-20 United TLD Holdco Ltd. +republican + +// rest : 2013-12-19 Punto 2012 Sociedad Anonima Promotora de Inversion de Capital Variable +rest + +// restaurant : 2014-07-03 Snow Avenue, LLC +restaurant + +// review : 2014-11-20 dot Review Limited +review + +// reviews : 2013-09-13 +reviews + +// rich : 2013-11-21 I-Registry Ltd. +rich + +// ricoh : 2014-11-20 Ricoh Company, Ltd. +ricoh + +// ril : 2015-04-02 Reliance Industries Limited +ril + +// rio : 2014-02-27 Empresa Municipal de Informática SA - IPLANRIO +rio + +// rip : 2014-07-10 United TLD Holdco Ltd. +rip + +// rocher : 2014-12-18 Ferrero Trading Lux S.A. +rocher + +// rocks : 2013-11-14 +rocks + +// rodeo : 2013-12-19 Top Level Domain Holdings Limited +rodeo + +// room : 2014-12-18 Amazon EU S.à r.l. +room + +// rsvp : 2014-05-08 Charleston Road Registry Inc. +rsvp + +// ruhr : 2013-10-02 regiodot GmbH & Co. KG +ruhr + +// run : 2015-03-19 Snow Park, LLC +run + +// rwe : 2015-04-02 RWE AG +rwe + +// ryukyu : 2014-01-09 BusinessRalliart Inc. +ryukyu + +// saarland : 2013-12-12 dotSaarland GmbH +saarland + +// safe : 2014-12-18 Amazon EU S.à r.l. +safe + +// safety : 2015-01-08 Safety Registry Services, LLC. +safety + +// sakura : 2014-12-18 SAKURA Internet Inc. +sakura + +// sale : 2014-10-16 +sale + +// salon : 2014-12-11 Outer Orchard, LLC +salon + +// samsung : 2014-04-03 SAMSUNG SDS CO., LTD +samsung + +// sandvik : 2014-11-13 Sandvik AB +sandvik + +// sandvikcoromant : 2014-11-07 Sandvik AB +sandvikcoromant + +// sanofi : 2014-10-09 Sanofi +sanofi + +// sap : 2014-03-27 SAP AG +sap + +// sapo : 2014-11-07 PT Comunicacoes S.A. +sapo + +// sarl : 2014-07-03 Delta Orchard, LLC +sarl + +// sas : 2015-04-02 Research IP LLC +sas + +// saxo : 2014-10-31 Saxo Bank A/S +saxo + +// sbi : 2015-03-12 STATE BANK OF INDIA +sbi + +// sbs : 2014-11-07 SPECIAL BROADCASTING SERVICE CORPORATION +sbs + +// sca : 2014-03-13 SVENSKA CELLULOSA AKTIEBOLAGET SCA (publ) +sca + +// scb : 2014-02-20 The Siam Commercial Bank Public Company Limited (\ +scb + +// schmidt : 2014-04-03 SALM S.A.S. +schmidt + +// scholarships : 2014-04-24 Scholarships.com, LLC +scholarships + +// school : 2014-12-18 Little Galley, LLC +school + +// schule : 2014-03-06 Outer Moon, LLC +schule + +// schwarz : 2014-09-18 Schwarz Domains und Services GmbH & Co. KG +schwarz + +// science : 2014-09-11 dot Science Limited +science + +// scor : 2014-10-31 SCOR SE +scor + +// scot : 2014-01-23 Dot Scot Registry Limited +scot + +// seat : 2014-05-22 SEAT, S.A. (Sociedad Unipersonal) +seat + +// seek : 2014-12-04 Seek Limited +seek + +// sener : 2014-10-24 Sener Ingeniería y Sistemas, S.A. +sener + +// services : 2014-02-27 Fox Castle, LLC +services + +// sew : 2014-07-17 SEW-EURODRIVE GmbH & Co KG +sew + +// sex : 2014-11-13 ICM Registry SX LLC +sex + +// sexy : 2013-09-11 Uniregistry, Corp. +sexy + +// sharp : 2014-05-01 Sharp Corporation +sharp + +// shia : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti. +shia + +// shiksha : 2013-11-14 Afilias Limited +shiksha + +// shoes : 2013-10-02 Binky Galley, LLC +shoes + +// shouji : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD. +shouji + +// show : 2015-03-05 Snow Beach, LLC +show + +// shriram : 2014-01-23 Shriram Capital Ltd. +shriram + +// sina : 2015-03-12 Sina Corporation +sina + +// singles : 2013-08-27 Fern Madison, LLC +singles + +// site : 2015-01-15 DotSite Inc. +site + +// skin : 2015-01-15 L'Oréal +skin + +// sky : 2014-06-19 Sky IP International Ltd, a company incorporated in England and Wales, operating via its registered Swiss branch +sky + +// skype : 2014-12-18 Microsoft Corporation +skype + +// smile : 2014-12-18 Amazon EU S.à r.l. +smile + +// sncf : 2015-02-19 Société Nationale des Chemins de fer Francais S N C F +sncf + +// soccer : 2015-03-26 Foggy Shadow, LLC +soccer + +// social : 2013-11-07 United TLD Holdco Ltd. +social + +// software : 2014-03-20 +software + +// sohu : 2013-12-19 Sohu.com Limited +sohu + +// solar : 2013-11-07 Ruby Town, LLC +solar + +// solutions : 2013-11-07 Silver Cover, LLC +solutions + +// song : 2015-02-26 Amazon EU S.à r.l. +song + +// sony : 2015-01-08 Sony Corporation +sony + +// soy : 2014-01-23 Charleston Road Registry Inc. +soy + +// space : 2014-04-03 DotSpace Inc. +space + +// spiegel : 2014-02-05 SPIEGEL-Verlag Rudolf Augstein GmbH & Co. KG +spiegel + +// spot : 2015-02-26 Amazon EU S.à r.l. +spot + +// spreadbetting : 2014-12-11 IG Group Holdings PLC +spreadbetting + +// stada : 2014-11-13 STADA Arzneimittel AG +stada + +// star : 2015-01-08 Star India Private Limited +star + +// starhub : 2015-02-05 StarHub Limited +starhub + +// statebank : 2015-03-12 STATE BANK OF INDIA +statebank + +// statoil : 2014-12-04 Statoil ASA +statoil + +// stc : 2014-10-09 Saudi Telecom Company +stc + +// stcgroup : 2014-10-09 Saudi Telecom Company +stcgroup + +// stockholm : 2014-12-18 Stockholms kommun +stockholm + +// storage : 2014-12-22 Self Storage Company LLC +storage + +// studio : 2015-02-11 Spring Goodbye, LLC +studio + +// study : 2014-12-11 OPEN UNIVERSITIES AUSTRALIA PTY LTD +study + +// style : 2014-12-04 Binky Moon, LLC +style + +// sucks : 2014-12-22 Vox Populi Registry Inc. +sucks + +// supersport : 2015-03-05 SuperSport International Holdings Proprietary Limited +supersport + +// supplies : 2013-12-19 Atomic Fields, LLC +supplies + +// supply : 2013-12-19 Half Falls, LLC +supply + +// support : 2013-10-24 Grand Orchard, LLC +support + +// surf : 2014-01-09 Top Level Domain Holdings Limited +surf + +// surgery : 2014-03-20 Tin Avenue, LLC +surgery + +// suzuki : 2014-02-20 SUZUKI MOTOR CORPORATION +suzuki + +// swatch : 2015-01-08 The Swatch Group Ltd +swatch + +// swiss : 2014-10-16 Swiss Confederation +swiss + +// sydney : 2014-09-18 State of New South Wales, Department of Premier and Cabinet +sydney + +// symantec : 2014-12-04 Symantec Corporation +symantec + +// systems : 2013-11-07 Dash Cypress, LLC +systems + +// tab : 2014-12-04 Tabcorp Holdings Limited +tab + +// taipei : 2014-07-10 Taipei City Government +taipei + +// taobao : 2015-01-15 Alibaba Group Holding Limited +taobao + +// tatamotors : 2015-03-12 Tata Motors Ltd +tatamotors + +// tatar : 2014-04-24 Limited Liability Company \ +tatar + +// tattoo : 2013-08-30 Uniregistry, Corp. +tattoo + +// tax : 2014-03-20 Storm Orchard, LLC +tax + +// taxi : 2015-03-19 Pine Falls, LLC +taxi + +// tci : 2014-09-12 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti. +tci + +// team : 2015-03-05 Atomic Lake, LLC +team + +// tech : 2015-01-30 Dot Tech LLC +tech + +// technology : 2013-09-13 Auburn Falls +technology + +// telecity : 2015-02-19 TelecityGroup International Limited +telecity + +// telefonica : 2014-10-16 Telefónica S.A. +telefonica + +// temasek : 2014-08-07 Temasek Holdings (Private) Limited +temasek + +// tennis : 2014-12-04 Cotton Bloom, LLC +tennis + +// thd : 2015-04-02 Homer TLC, Inc. +thd + +// theater : 2015-03-19 Blue Tigers, LLC +theater + +// tickets : 2015-02-05 Accent Media Limited +tickets + +// tienda : 2013-11-14 Victor Manor, LLC +tienda + +// tiffany : 2015-01-30 Tiffany and Company +tiffany + +// tips : 2013-09-20 Corn Willow, LLC +tips + +// tires : 2014-11-07 Dog Edge, LLC +tires + +// tirol : 2014-04-24 punkt Tirol GmbH +tirol + +// tmall : 2015-01-15 Alibaba Group Holding Limited +tmall + +// today : 2013-09-20 Pearl Woods, LLC +today + +// tokyo : 2013-11-13 GMO Registry, Inc. +tokyo + +// tools : 2013-11-21 Pioneer North, LLC +tools + +// top : 2014-03-20 Jiangsu Bangning Science & Technology Co.,Ltd. +top + +// toray : 2014-12-18 Toray Industries, Inc. +toray + +// toshiba : 2014-04-10 TOSHIBA Corporation +toshiba + +// tours : 2015-01-22 Sugar Station, LLC +tours + +// town : 2014-03-06 Koko Moon, LLC +town + +// toys : 2014-03-06 Pioneer Orchard, LLC +toys + +// trade : 2014-01-23 Elite Registry Limited +trade + +// trading : 2014-12-11 IG Group Holdings PLC +trading + +// training : 2013-11-07 Wild Willow, LLC +training + +// travelers : 2015-03-26 Travelers TLD, LLC +travelers + +// travelersinsurance : 2015-03-26 Travelers TLD, LLC +travelersinsurance + +// trust : 2014-10-16 +trust + +// trv : 2015-03-26 Travelers TLD, LLC +trv + +// tui : 2014-07-03 TUI AG +tui + +// tunes : 2015-02-26 Amazon EU S.à r.l. +tunes + +// tushu : 2014-12-18 Amazon EU S.à r.l. +tushu + +// tvs : 2015-02-19 T V SUNDRAM IYENGAR & SONS LIMITED +tvs + +// ubs : 2014-12-11 UBS AG +ubs + +// university : 2014-03-06 Little Station, LLC +university + +// uno : 2013-09-11 Dot Latin LLC +uno + +// uol : 2014-05-01 UBN INTERNET LTDA. +uol + +// vacations : 2013-12-05 Atomic Tigers, LLC +vacations + +// vana : 2014-12-11 Lifestyle Domain Holdings, Inc. +vana + +// vegas : 2014-01-16 Dot Vegas, Inc. +vegas + +// ventures : 2013-08-27 Binky Lake, LLC +ventures + +// versicherung : 2014-03-20 dotversicherung-registry GmbH +versicherung + +// vet : 2014-03-06 +vet + +// viajes : 2013-10-17 Black Madison, LLC +viajes + +// video : 2014-10-16 +video + +// viking : 2015-04-02 Viking River Cruises (Bermuda) Ltd. +viking + +// villas : 2013-12-05 New Sky, LLC +villas + +// vip : 2015-01-22 Minds + Machines Group Limited +vip + +// virgin : 2014-09-25 Virgin Enterprises Limited +virgin + +// vision : 2013-12-05 Koko Station, LLC +vision + +// vista : 2014-09-18 Vistaprint Limited +vista + +// vistaprint : 2014-09-18 Vistaprint Limited +vistaprint + +// viva : 2014-11-07 Saudi Telecom Company +viva + +// vlaanderen : 2014-02-06 DNS.be vzw +vlaanderen + +// vodka : 2013-12-19 Top Level Domain Holdings Limited +vodka + +// vote : 2013-11-21 Monolith Registry LLC +vote + +// voting : 2013-11-13 Valuetainment Corp. +voting + +// voto : 2013-11-21 Monolith Registry LLC +voto + +// voyage : 2013-08-27 Ruby House, LLC +voyage + +// vuelos : 2015-03-05 Travel Reservations SRL +vuelos + +// wales : 2014-05-08 Nominet UK +wales + +// walter : 2014-11-13 Sandvik AB +walter + +// wang : 2013-10-24 Zodiac Leo Limited +wang + +// wanggou : 2014-12-18 Amazon EU S.à r.l. +wanggou + +// watch : 2013-11-14 Sand Shadow, LLC +watch + +// watches : 2014-12-22 Richemont DNS Inc. +watches + +// weather : 2015-01-08 The Weather Channel, LLC +weather + +// weatherchannel : 2015-03-12 The Weather Channel, LLC +weatherchannel + +// webcam : 2014-01-23 dot Webcam Limited +webcam + +// website : 2014-04-03 DotWebsite Inc. +website + +// wed : 2013-10-01 Atgron, Inc. +wed + +// wedding : 2014-04-24 Top Level Domain Holdings Limited +wedding + +// weibo : 2015-03-05 Sina Corporation +weibo + +// weir : 2015-01-29 Weir Group IP Limited +weir + +// whoswho : 2014-02-20 Who's Who Registry +whoswho + +// wien : 2013-10-28 punkt.wien GmbH +wien + +// wiki : 2013-11-07 Top Level Design, LLC +wiki + +// williamhill : 2014-03-13 William Hill Organization Limited +williamhill + +// win : 2014-11-20 First Registry Limited +win + +// windows : 2014-12-18 Microsoft Corporation +windows + +// wme : 2014-02-13 William Morris Endeavor Entertainment, LLC +wme + +// work : 2013-12-19 Top Level Domain Holdings Limited +work + +// works : 2013-11-14 Little Dynamite, LLC +works + +// world : 2014-06-12 Bitter Fields, LLC +world + +// wtc : 2013-12-19 World Trade Centers Association, Inc. +wtc + +// wtf : 2014-03-06 Hidden Way, LLC +wtf + +// xbox : 2014-12-18 Microsoft Corporation +xbox + +// xerox : 2014-10-24 Xerox DNHC LLC +xerox + +// xihuan : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD. +xihuan + +// xin : 2014-12-11 Elegant Leader Limited +xin + +// xn--11b4c3d : 2015-01-15 VeriSign Sarl +कॉम + +// xn--1ck2e1b : 2015-02-26 Amazon EU S.à r.l. +セール + +// xn--1qqw23a : 2014-01-09 Guangzhou YU Wei Information Technology Co., Ltd. +佛山 + +// xn--30rr7y : 2014-06-12 Excellent First Limited +慈善 + +// xn--3bst00m : 2013-09-13 Eagle Horizon Limited +集团 + +// xn--3ds443g : 2013-09-08 TLD REGISTRY LIMITED +在线 + +// xn--3pxu8k : 2015-01-15 VeriSign Sarl +点看 + +// xn--42c2d9a : 2015-01-15 VeriSign Sarl +คอม + +// xn--45q11c : 2013-11-21 Zodiac Scorpio Limited +八卦 + +// xn--4gbrim : 2013-10-04 Suhub Electronic Establishment +موقع + +// xn--55qw42g : 2013-11-08 China Organizational Name Administration Center +公益 + +// xn--55qx5d : 2013-11-14 Computer Network Information Center of Chinese Academy of Sciences (China Internet Network Information Center) +公司 + +// xn--5tzm5g : 2014-12-22 Global Website TLD Asia Limited +网站 + +// xn--6frz82g : 2013-09-23 Afilias Limited +移动 + +// xn--6qq986b3xl : 2013-09-13 Tycoon Treasure Limited +我爱你 + +// xn--80adxhks : 2013-12-19 Foundation for Assistance for Internet Technologies and Infrastructure Development (FAITID) +москва + +// xn--80asehdb : 2013-07-14 CORE Association +онлайн + +// xn--80aswg : 2013-07-14 CORE Association +сайт + +// xn--8y0a063a : 2015-03-26 China United Network Communications Corporation Limited +联通 + +// xn--9dbq2a : 2015-01-15 VeriSign Sarl +קום + +// xn--9et52u : 2014-06-12 RISE VICTORY LIMITED +时尚 + +// xn--9krt00a : 2015-03-12 Sina Corporation +微博 + +// xn--b4w605ferd : 2014-08-07 Temasek Holdings (Private) Limited +淡马锡 + +// xn--bck1b9a5dre4c : 2015-02-26 Amazon EU S.à r.l. +ファッション + +// xn--c1avg : 2013-11-14 Public Interest Registry +орг + +// xn--c2br7g : 2015-01-15 VeriSign Sarl +नेट + +// xn--cck2b3b : 2015-02-26 Amazon EU S.à r.l. +ストア + +// xn--cg4bki : 2013-09-27 SAMSUNG SDS CO., LTD +삼성 + +// xn--czr694b : 2014-01-16 HU YI GLOBAL INFORMATION RESOURCES (HOLDING) COMPANY.HONGKONG LIMITED +商标 + +// xn--czrs0t : 2013-12-19 Wild Island, LLC +商店 + +// xn--czru2d : 2013-11-21 Zodiac Capricorn Limited +商城 + +// xn--d1acj3b : 2013-11-20 The Foundation for Network Initiatives “The Smart Internet” +дети + +// xn--eckvdtc9d : 2014-12-18 Amazon EU S.à r.l. +ポイント + +// xn--efvy88h : 2014-08-22 Xinhua News Agency Guangdong Branch 新华通讯社广东分社 +新闻 + +// xn--estv75g : 2015-02-19 Industrial and Commercial Bank of China Limited +工行 + +// xn--fhbei : 2015-01-15 VeriSign Sarl +كوم + +// xn--fiq228c5hs : 2013-09-08 TLD REGISTRY LIMITED +中文网 + +// xn--fiq64b : 2013-10-14 CITIC Group Corporation +中信 + +// xn--fjq720a : 2014-05-22 Will Bloom, LLC +娱乐 + +// xn--flw351e : 2014-07-31 Charleston Road Registry Inc. +谷歌 + +// xn--g2xx48c : 2015-01-30 Minds + Machines Group Limited +购物 + +// xn--gckr3f0f : 2015-02-26 Amazon EU S.à r.l. +クラウド + +// xn--hxt814e : 2014-05-15 Zodiac Libra Limited +网店 + +// xn--i1b6b1a6a2e : 2013-11-14 Public Interest Registry +संगठन + +// xn--imr513n : 2014-12-11 HU YI GLOBAL INFORMATION RESOURCES (HOLDING) COMPANY. HONGKONG LIMITED +餐厅 + +// xn--io0a7i : 2013-11-14 Computer Network Information Center of Chinese Academy of Sciences (China Internet Network Information Center) +网络 + +// xn--j1aef : 2015-01-15 VeriSign Sarl +ком + +// xn--jlq61u9w7b : 2015-01-08 Nokia Corporation +诺基亚 + +// xn--jvr189m : 2015-02-26 Amazon EU S.à r.l. +食品 + +// xn--kcrx77d1x4a : 2014-11-07 Koninklijke Philips N.V. +飞利浦 + +// xn--kpu716f : 2014-12-22 Richemont DNS Inc. +手表 + +// xn--kput3i : 2014-02-13 Beijing RITT-Net Technology Development Co., Ltd +手机 + +// xn--mgba3a3ejt : 2014-11-20 Aramco Services Company +ارامكو + +// xn--mgbab2bd : 2013-10-31 CORE Association +بازار + +// xn--mgbb9fbpob : 2014-12-18 GreenTech Consultancy Company W.L.L. +موبايلي + +// xn--mgbt3dhd : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti. +همراه + +// xn--mk1bu44c : 2015-01-15 VeriSign Sarl +닷컴 + +// xn--mxtq1m : 2014-03-06 Net-Chinese Co., Ltd. +政府 + +// xn--ngbc5azd : 2013-07-13 International Domain Registry Pty. Ltd. +شبكة + +// xn--ngbe9e0a : 2014-12-04 Kuwait Finance House +بيتك + +// xn--nqv7f : 2013-11-14 Public Interest Registry +机构 + +// xn--nqv7fs00ema : 2013-11-14 Public Interest Registry +组织机构 + +// xn--nyqy26a : 2014-11-07 Stable Tone Limited +健康 + +// xn--p1acf : 2013-12-12 Rusnames Limited +рус + +// xn--pbt977c : 2014-12-22 Richemont DNS Inc. +珠宝 + +// xn--pssy2u : 2015-01-15 VeriSign Sarl +大拿 + +// xn--q9jyb4c : 2013-09-17 Charleston Road Registry Inc. +みんな + +// xn--qcka1pmc : 2014-07-31 Charleston Road Registry Inc. +グーグル + +// xn--rhqv96g : 2013-09-11 Stable Tone Limited +世界 + +// xn--rovu88b : 2015-02-26 Amazon EU S.à r.l. +書籍 + +// xn--ses554g : 2014-01-16 +网址 + +// xn--t60b56a : 2015-01-15 VeriSign Sarl +닷넷 + +// xn--tckwe : 2015-01-15 VeriSign Sarl +コム + +// xn--unup4y : 2013-07-14 Spring Fields, LLC +游戏 + +// xn--vermgensberater-ctb : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG +vermögensberater + +// xn--vermgensberatung-pwb : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG +vermögensberatung + +// xn--vhquv : 2013-08-27 Dash McCook, LLC +企业 + +// xn--vuq861b : 2014-10-16 Beijing Tele-info Network Technology Co., Ltd. +信息 + +// xn--xhq521b : 2013-11-14 Guangzhou YU Wei Information Technology Co., Ltd. +广东 + +// xn--zfr164b : 2013-11-08 China Organizational Name Administration Center +政务 + +// xyz : 2013-12-05 XYZ.COM LLC +xyz + +// yachts : 2014-01-09 DERYachts, LLC +yachts + +// yahoo : 2015-04-02 Yahoo! Domain Services Inc. +yahoo + +// yamaxun : 2014-12-18 Amazon EU S.à r.l. +yamaxun + +// yandex : 2014-04-10 YANDEX, LLC +yandex + +// yodobashi : 2014-11-20 YODOBASHI CAMERA CO.,LTD. +yodobashi + +// yoga : 2014-05-29 Top Level Domain Holdings Limited +yoga + +// yokohama : 2013-12-12 GMO Registry, Inc. +yokohama + +// youtube : 2014-05-01 Charleston Road Registry Inc. +youtube + +// yun : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD. +yun + +// zara : 2014-11-07 Industria de Diseño Textil, S.A. (INDITEX, S.A.) +zara + +// zero : 2014-12-18 Amazon EU S.à r.l. +zero + +// zip : 2014-05-08 Charleston Road Registry Inc. +zip + +// zone : 2013-11-14 Outer Falls, LLC +zone + +// zuerich : 2014-11-07 Kanton Zürich (Canton of Zurich) +zuerich + + +// ===END ICANN DOMAINS=== +// ===BEGIN PRIVATE DOMAINS=== +// (Note: these are in alphabetical order by company name) + +// Amazon CloudFront : https://aws.amazon.com/cloudfront/ +// Submitted by Donavan Miller 2013-03-22 +cloudfront.net + +// Amazon Elastic Compute Cloud: https://aws.amazon.com/ec2/ +// Submitted by Osman Surkatty 2014-12-16 +ap-northeast-1.compute.amazonaws.com +ap-southeast-1.compute.amazonaws.com +ap-southeast-2.compute.amazonaws.com +cn-north-1.compute.amazonaws.cn +compute.amazonaws.cn +compute.amazonaws.com +compute-1.amazonaws.com +eu-west-1.compute.amazonaws.com +eu-central-1.compute.amazonaws.com +sa-east-1.compute.amazonaws.com +us-east-1.amazonaws.com +us-gov-west-1.compute.amazonaws.com +us-west-1.compute.amazonaws.com +us-west-2.compute.amazonaws.com +z-1.compute-1.amazonaws.com +z-2.compute-1.amazonaws.com + +// Amazon Elastic Beanstalk : https://aws.amazon.com/elasticbeanstalk/ +// Submitted by Adam Stein 2013-04-02 +elasticbeanstalk.com + +// Amazon Elastic Load Balancing : https://aws.amazon.com/elasticloadbalancing/ +// Submitted by Scott Vidmar 2013-03-27 +elb.amazonaws.com + +// Amazon S3 : https://aws.amazon.com/s3/ +// Submitted by Courtney Eckhardt 2013-03-22 +s3.amazonaws.com +s3-us-west-2.amazonaws.com +s3-us-west-1.amazonaws.com +s3-eu-west-1.amazonaws.com +s3-ap-southeast-1.amazonaws.com +s3-ap-southeast-2.amazonaws.com +s3-ap-northeast-1.amazonaws.com +s3-sa-east-1.amazonaws.com +s3-us-gov-west-1.amazonaws.com +s3-fips-us-gov-west-1.amazonaws.com +s3-website-us-east-1.amazonaws.com +s3-website-us-west-2.amazonaws.com +s3-website-us-west-1.amazonaws.com +s3-website-eu-west-1.amazonaws.com +s3-website-ap-southeast-1.amazonaws.com +s3-website-ap-southeast-2.amazonaws.com +s3-website-ap-northeast-1.amazonaws.com +s3-website-sa-east-1.amazonaws.com +s3-website-us-gov-west-1.amazonaws.com + +// BetaInABox +// Submitted by adrian@betainabox.com 2012-09-13 +betainabox.com + +// CentralNic : http://www.centralnic.com/names/domains +// Submitted by registry 2012-09-27 +ae.org +ar.com +br.com +cn.com +com.de +com.se +de.com +eu.com +gb.com +gb.net +hu.com +hu.net +jp.net +jpn.com +kr.com +mex.com +no.com +qc.com +ru.com +sa.com +se.com +se.net +uk.com +uk.net +us.com +uy.com +za.bz +za.com + +// Africa.com Web Solutions Ltd : https://registry.africa.com +// Submitted by Gavin Brown 2014-02-04 +africa.com + +// iDOT Services Limited : http://www.domain.gr.com +// Submitted by Gavin Brown 2014-02-04 +gr.com + +// Radix FZC : http://domains.in.net +// Submitted by Gavin Brown 2014-02-04 +in.net + +// US REGISTRY LLC : http://us.org +// Submitted by Gavin Brown 2014-02-04 +us.org + +// co.com Registry, LLC : https://registry.co.com +// Submitted by Gavin Brown 2014-02-04 +co.com + +// c.la : http://www.c.la/ +c.la + +// cloudControl : https://www.cloudcontrol.com/ +// Submitted by Tobias Wilken 2013-07-23 +cloudcontrolled.com +cloudcontrolapp.com + +// co.ca : http://registry.co.ca/ +co.ca + +// CoDNS B.V. +co.nl +co.no + +// Commerce Guys, SAS +// Submitted by Damien Tournoud 2015-01-22 +*.platform.sh + +// Cupcake : https://cupcake.io/ +// Submitted by Jonathan Rudenberg 2013-10-08 +cupcake.is + +// DreamHost : http://www.dreamhost.com/ +// Submitted by Andrew Farmer 2012-10-02 +dreamhosters.com + +// DynDNS.com : http://www.dyndns.com/services/dns/dyndns/ +dyndns-at-home.com +dyndns-at-work.com +dyndns-blog.com +dyndns-free.com +dyndns-home.com +dyndns-ip.com +dyndns-mail.com +dyndns-office.com +dyndns-pics.com +dyndns-remote.com +dyndns-server.com +dyndns-web.com +dyndns-wiki.com +dyndns-work.com +dyndns.biz +dyndns.info +dyndns.org +dyndns.tv +at-band-camp.net +ath.cx +barrel-of-knowledge.info +barrell-of-knowledge.info +better-than.tv +blogdns.com +blogdns.net +blogdns.org +blogsite.org +boldlygoingnowhere.org +broke-it.net +buyshouses.net +cechire.com +dnsalias.com +dnsalias.net +dnsalias.org +dnsdojo.com +dnsdojo.net +dnsdojo.org +does-it.net +doesntexist.com +doesntexist.org +dontexist.com +dontexist.net +dontexist.org +doomdns.com +doomdns.org +dvrdns.org +dyn-o-saur.com +dynalias.com +dynalias.net +dynalias.org +dynathome.net +dyndns.ws +endofinternet.net +endofinternet.org +endoftheinternet.org +est-a-la-maison.com +est-a-la-masion.com +est-le-patron.com +est-mon-blogueur.com +for-better.biz +for-more.biz +for-our.info +for-some.biz +for-the.biz +forgot.her.name +forgot.his.name +from-ak.com +from-al.com +from-ar.com +from-az.net +from-ca.com +from-co.net +from-ct.com +from-dc.com +from-de.com +from-fl.com +from-ga.com +from-hi.com +from-ia.com +from-id.com +from-il.com +from-in.com +from-ks.com +from-ky.com +from-la.net +from-ma.com +from-md.com +from-me.org +from-mi.com +from-mn.com +from-mo.com +from-ms.com +from-mt.com +from-nc.com +from-nd.com +from-ne.com +from-nh.com +from-nj.com +from-nm.com +from-nv.com +from-ny.net +from-oh.com +from-ok.com +from-or.com +from-pa.com +from-pr.com +from-ri.com +from-sc.com +from-sd.com +from-tn.com +from-tx.com +from-ut.com +from-va.com +from-vt.com +from-wa.com +from-wi.com +from-wv.com +from-wy.com +ftpaccess.cc +fuettertdasnetz.de +game-host.org +game-server.cc +getmyip.com +gets-it.net +go.dyndns.org +gotdns.com +gotdns.org +groks-the.info +groks-this.info +ham-radio-op.net +here-for-more.info +hobby-site.com +hobby-site.org +home.dyndns.org +homedns.org +homeftp.net +homeftp.org +homeip.net +homelinux.com +homelinux.net +homelinux.org +homeunix.com +homeunix.net +homeunix.org +iamallama.com +in-the-band.net +is-a-anarchist.com +is-a-blogger.com +is-a-bookkeeper.com +is-a-bruinsfan.org +is-a-bulls-fan.com +is-a-candidate.org +is-a-caterer.com +is-a-celticsfan.org +is-a-chef.com +is-a-chef.net +is-a-chef.org +is-a-conservative.com +is-a-cpa.com +is-a-cubicle-slave.com +is-a-democrat.com +is-a-designer.com +is-a-doctor.com +is-a-financialadvisor.com +is-a-geek.com +is-a-geek.net +is-a-geek.org +is-a-green.com +is-a-guru.com +is-a-hard-worker.com +is-a-hunter.com +is-a-knight.org +is-a-landscaper.com +is-a-lawyer.com +is-a-liberal.com +is-a-libertarian.com +is-a-linux-user.org +is-a-llama.com +is-a-musician.com +is-a-nascarfan.com +is-a-nurse.com +is-a-painter.com +is-a-patsfan.org +is-a-personaltrainer.com +is-a-photographer.com +is-a-player.com +is-a-republican.com +is-a-rockstar.com +is-a-socialist.com +is-a-soxfan.org +is-a-student.com +is-a-teacher.com +is-a-techie.com +is-a-therapist.com +is-an-accountant.com +is-an-actor.com +is-an-actress.com +is-an-anarchist.com +is-an-artist.com +is-an-engineer.com +is-an-entertainer.com +is-by.us +is-certified.com +is-found.org +is-gone.com +is-into-anime.com +is-into-cars.com +is-into-cartoons.com +is-into-games.com +is-leet.com +is-lost.org +is-not-certified.com +is-saved.org +is-slick.com +is-uberleet.com +is-very-bad.org +is-very-evil.org +is-very-good.org +is-very-nice.org +is-very-sweet.org +is-with-theband.com +isa-geek.com +isa-geek.net +isa-geek.org +isa-hockeynut.com +issmarterthanyou.com +isteingeek.de +istmein.de +kicks-ass.net +kicks-ass.org +knowsitall.info +land-4-sale.us +lebtimnetz.de +leitungsen.de +likes-pie.com +likescandy.com +merseine.nu +mine.nu +misconfused.org +mypets.ws +myphotos.cc +neat-url.com +office-on-the.net +on-the-web.tv +podzone.net +podzone.org +readmyblog.org +saves-the-whales.com +scrapper-site.net +scrapping.cc +selfip.biz +selfip.com +selfip.info +selfip.net +selfip.org +sells-for-less.com +sells-for-u.com +sells-it.net +sellsyourhome.org +servebbs.com +servebbs.net +servebbs.org +serveftp.net +serveftp.org +servegame.org +shacknet.nu +simple-url.com +space-to-rent.com +stuff-4-sale.org +stuff-4-sale.us +teaches-yoga.com +thruhere.net +traeumtgerade.de +webhop.biz +webhop.info +webhop.net +webhop.org +worse-than.tv +writesthisblog.com + +// Fastly Inc. http://www.fastly.com/ +// Submitted by Vladimir Vuksan 2013-05-31 +a.ssl.fastly.net +b.ssl.fastly.net +global.ssl.fastly.net +a.prod.fastly.net +global.prod.fastly.net + +// Firebase, Inc. +// Submitted by Chris Raynor 2014-01-21 +firebaseapp.com + +// Flynn : https://flynn.io +// Submitted by Jonathan Rudenberg 2014-07-12 +flynnhub.com + +// GDS : https://www.gov.uk/service-manual/operations/operating-servicegovuk-subdomains +// Submitted by David Illsley 2014-08-28 +service.gov.uk + +// GitHub, Inc. +// Submitted by Ben Toews 2014-02-06 +github.io +githubusercontent.com + +// GlobeHosting, Inc. +// Submitted by Zoltan Egresi 2013-07-12 +ro.com + +// Google, Inc. +// Submitted by Eduardo Vela 2014-12-19 +appspot.com +blogspot.ae +blogspot.be +blogspot.bj +blogspot.ca +blogspot.cf +blogspot.ch +blogspot.co.at +blogspot.co.il +blogspot.co.nz +blogspot.co.uk +blogspot.com +blogspot.com.ar +blogspot.com.au +blogspot.com.br +blogspot.com.es +blogspot.com.tr +blogspot.cv +blogspot.cz +blogspot.de +blogspot.dk +blogspot.fi +blogspot.fr +blogspot.gr +blogspot.hk +blogspot.hu +blogspot.ie +blogspot.in +blogspot.it +blogspot.jp +blogspot.kr +blogspot.mr +blogspot.mx +blogspot.nl +blogspot.no +blogspot.pt +blogspot.re +blogspot.ro +blogspot.ru +blogspot.se +blogspot.sg +blogspot.sk +blogspot.td +blogspot.tw +codespot.com +googleapis.com +googlecode.com +pagespeedmobilizer.com +withgoogle.com + +// Heroku : https://www.heroku.com/ +// Submitted by Tom Maher 2013-05-02 +herokuapp.com +herokussl.com + +// iki.fi +// Submitted by Hannu Aronsson 2009-11-05 +iki.fi + +// info.at : http://www.info.at/ +biz.at +info.at + +// Michau Enterprises Limited : http://www.co.pl/ +co.pl + +// Microsoft : http://microsoft.com +// Submitted by Barry Dorrans 2014-01-24 +azurewebsites.net +azure-mobile.net +cloudapp.net + +// NFSN, Inc. : https://www.NearlyFreeSpeech.NET/ +// Submitted by Jeff Wheelhouse 2014-02-02 +nfshost.com + +// NYC.mn : http://www.information.nyc.mn +// Submitted by Matthew Brown 2013-03-11 +nyc.mn + +// One Fold Media : http://www.onefoldmedia.com/ +// Submitted by Eddie Jones 2014-06-10 +nid.io + +// Opera Software, A.S.A. +// Submitted by Yngve Pettersen 2009-11-26 +operaunite.com + +// OutSystems +// Submitted by Duarte Santos 2014-03-11 +outsystemscloud.com + +// .pl domains (grandfathered) +art.pl +gliwice.pl +krakow.pl +poznan.pl +wroc.pl +zakopane.pl + +// priv.at : http://www.nic.priv.at/ +// Submitted by registry 2008-06-09 +priv.at + +// Red Hat, Inc. OpenShift : https://openshift.redhat.com/ +// Submitted by Tim Kramer 2012-10-24 +rhcloud.com + +// SinaAppEngine : http://sae.sina.com.cn/ +// Submitted by SinaAppEngine 2015-02-02 +sinaapp.com +vipsinaapp.com +1kapp.com + +// TASK geographical domains (www.task.gda.pl/uslugi/dns) +gda.pl +gdansk.pl +gdynia.pl +med.pl +sopot.pl + +// UDR Limited : http://www.udr.hk.com +// Submitted by registry 2014-11-07 +hk.com +hk.org +ltd.hk +inc.hk + +// Yola : https://www.yola.com/ +// Submitted by Stefano Rivera 2014-07-09 +yolasite.com + +// ZaNiC : http://www.za.net/ +// Submitted by registry 2009-10-03 +za.net +za.org + +// ===END PRIVATE DOMAINS=== diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/api_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/api_test.js new file mode 100644 index 0000000..b21326c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/api_test.js @@ -0,0 +1,372 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var async = require('async'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; +var CookieJar = tough.CookieJar; + + +var atNow = Date.now(); + +function at(offset) { + return {now: new Date(atNow + offset)}; +} + +vows + .describe('API') + .addBatch({ + "All defined": function () { + assert.ok(Cookie); + assert.ok(CookieJar); + } + }) + .addBatch({ + "Constructor": { + topic: function () { + return new Cookie({ + key: 'test', + value: 'b', + maxAge: 60 + }); + }, + 'check for key property': function (c) { + assert.ok(c); + assert.equal(c.key, 'test'); + }, + 'check for value property': function (c) { + assert.equal(c.value, 'b'); + }, + 'check for maxAge': function (c) { + assert.equal(c.maxAge, 60); + }, + 'check for default values for unspecified properties': function (c) { + assert.equal(c.expires, "Infinity"); + assert.equal(c.secure, false); + assert.equal(c.httpOnly, false); + } + } + }) + .addBatch({ + "expiry option": { + topic: function () { + var cb = this.callback; + var cj = new CookieJar(); + cj.setCookie('near=expiry; Domain=example.com; Path=/; Max-Age=1', 'http://www.example.com', at(-1), function (err, cookie) { + + cb(err, {cj: cj, cookie: cookie}); + }); + }, + "set the cookie": function (t) { + assert.ok(t.cookie, "didn't set?!"); + assert.equal(t.cookie.key, 'near'); + }, + "then, retrieving": { + topic: function (t) { + var cb = this.callback; + setTimeout(function () { + t.cj.getCookies('http://www.example.com', {http: true, expire: false}, function (err, cookies) { + t.cookies = cookies; + cb(err, t); + }); + }, 2000); + }, + "got the cookie": function (t) { + assert.lengthOf(t.cookies, 1); + assert.equal(t.cookies[0].key, 'near'); + } + } + } + }) + .addBatch({ + "allPaths option": { + topic: function () { + var cj = new CookieJar(); + var tasks = []; + tasks.push(cj.setCookie.bind(cj, 'nopath_dom=qq; Path=/; Domain=example.com', 'http://example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'path_dom=qq; Path=/foo; Domain=example.com', 'http://example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'nopath_host=qq; Path=/', 'http://www.example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'path_host=qq; Path=/foo', 'http://www.example.com', {})); + tasks.push(cj.setCookie.bind(cj, 'other=qq; Path=/', 'http://other.example.com/', {})); + tasks.push(cj.setCookie.bind(cj, 'other2=qq; Path=/foo', 'http://other.example.com/foo', {})); + var cb = this.callback; + async.parallel(tasks, function (err, results) { + cb(err, {cj: cj, cookies: results}); + }); + }, + "all set": function (t) { + assert.equal(t.cookies.length, 6); + assert.ok(t.cookies.every(function (c) { + return !!c + })); + }, + "getting without allPaths": { + topic: function (t) { + var cb = this.callback; + var cj = t.cj; + cj.getCookies('http://www.example.com/', {}, function (err, cookies) { + cb(err, {cj: cj, cookies: cookies}); + }); + }, + "found just two cookies": function (t) { + assert.equal(t.cookies.length, 2); + }, + "all are path=/": function (t) { + assert.ok(t.cookies.every(function (c) { + return c.path === '/' + })); + }, + "no 'other' cookies": function (t) { + assert.ok(!t.cookies.some(function (c) { + return (/^other/).test(c.name) + })); + } + }, + "getting without allPaths for /foo": { + topic: function (t) { + var cb = this.callback; + var cj = t.cj; + cj.getCookies('http://www.example.com/foo', {}, function (err, cookies) { + cb(err, {cj: cj, cookies: cookies}); + }); + }, + "found four cookies": function (t) { + assert.equal(t.cookies.length, 4); + }, + "no 'other' cookies": function (t) { + assert.ok(!t.cookies.some(function (c) { + return (/^other/).test(c.name) + })); + } + }, + "getting with allPaths:true": { + topic: function (t) { + var cb = this.callback; + var cj = t.cj; + cj.getCookies('http://www.example.com/', {allPaths: true}, function (err, cookies) { + cb(err, {cj: cj, cookies: cookies}); + }); + }, + "found four cookies": function (t) { + assert.equal(t.cookies.length, 4); + }, + "no 'other' cookies": function (t) { + assert.ok(!t.cookies.some(function (c) { + return (/^other/).test(c.name) + })); + } + } + } + }) + .addBatch({ + "Remove cookies": { + topic: function () { + var jar = new CookieJar(); + var cookie = Cookie.parse("a=b; Domain=example.com; Path=/"); + var cookie2 = Cookie.parse("a=b; Domain=foo.com; Path=/"); + var cookie3 = Cookie.parse("foo=bar; Domain=foo.com; Path=/"); + jar.setCookie(cookie, 'http://example.com/index.html', function () { + }); + jar.setCookie(cookie2, 'http://foo.com/index.html', function () { + }); + jar.setCookie(cookie3, 'http://foo.com/index.html', function () { + }); + return jar; + }, + "all from matching domain": function (jar) { + jar.store.removeCookies('example.com', null, function (err) { + assert(err == null); + + jar.store.findCookies('example.com', null, function (err, cookies) { + assert(err == null); + assert(cookies != null); + assert(cookies.length === 0, 'cookie was not removed'); + }); + + jar.store.findCookies('foo.com', null, function (err, cookies) { + assert(err == null); + assert(cookies != null); + assert(cookies.length === 2, 'cookies should not have been removed'); + }); + }); + }, + "from cookie store matching domain and key": function (jar) { + jar.store.removeCookie('foo.com', '/', 'foo', function (err) { + assert(err == null); + + jar.store.findCookies('foo.com', null, function (err, cookies) { + assert(err == null); + assert(cookies != null); + assert(cookies.length === 1, 'cookie was not removed correctly'); + assert(cookies[0].key === 'a', 'wrong cookie was removed'); + }); + }); + } + } + }) + .addBatch({ + "Synchronous CookieJar": { + "setCookieSync": { + topic: function () { + var jar = new CookieJar(); + var cookie = Cookie.parse("a=b; Domain=example.com; Path=/"); + cookie = jar.setCookieSync(cookie, 'http://example.com/index.html'); + return cookie; + }, + "returns a copy of the cookie": function (cookie) { + assert.instanceOf(cookie, Cookie); + } + }, + "getCookiesSync": { + topic: function () { + var jar = new CookieJar(); + var url = 'http://example.com/index.html'; + jar.setCookieSync("a=b; Domain=example.com; Path=/", url); + jar.setCookieSync("c=d; Domain=example.com; Path=/", url); + return jar.getCookiesSync(url); + }, + "returns the cookie array": function (err, cookies) { + assert.ok(!err); + assert.ok(Array.isArray(cookies)); + assert.lengthOf(cookies, 2); + cookies.forEach(function (cookie) { + assert.instanceOf(cookie, Cookie); + }); + } + }, + + "getCookieStringSync": { + topic: function () { + var jar = new CookieJar(); + var url = 'http://example.com/index.html'; + jar.setCookieSync("a=b; Domain=example.com; Path=/", url); + jar.setCookieSync("c=d; Domain=example.com; Path=/", url); + return jar.getCookieStringSync(url); + }, + "returns the cookie header string": function (err, str) { + assert.ok(!err); + assert.typeOf(str, 'string'); + } + }, + + "getSetCookieStringsSync": { + topic: function () { + var jar = new CookieJar(); + var url = 'http://example.com/index.html'; + jar.setCookieSync("a=b; Domain=example.com; Path=/", url); + jar.setCookieSync("c=d; Domain=example.com; Path=/", url); + return jar.getSetCookieStringsSync(url); + }, + "returns the cookie header string": function (err, headers) { + assert.ok(!err); + assert.ok(Array.isArray(headers)); + assert.lengthOf(headers, 2); + headers.forEach(function (header) { + assert.typeOf(header, 'string'); + }); + } + } + } + }) + .addBatch({ + "Synchronous API on async CookieJar": { + topic: function () { + return new tough.Store(); + }, + "setCookieSync": { + topic: function (store) { + var jar = new CookieJar(store); + try { + jar.setCookieSync("a=b", 'http://example.com/index.html'); + return false; + } catch (e) { + return e; + } + }, + "fails": function (err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + "getCookiesSync": { + topic: function (store) { + var jar = new CookieJar(store); + try { + jar.getCookiesSync('http://example.com/index.html'); + return false; + } catch (e) { + return e; + } + }, + "fails": function (err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + "getCookieStringSync": { + topic: function (store) { + var jar = new CookieJar(store); + try { + jar.getCookieStringSync('http://example.com/index.html'); + return false; + } catch (e) { + return e; + } + }, + "fails": function (err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + }, + "getSetCookieStringsSync": { + topic: function (store) { + var jar = new CookieJar(store); + try { + jar.getSetCookieStringsSync('http://example.com/index.html'); + return false; + } catch (e) { + return e; + } + }, + "fails": function (err) { + assert.instanceOf(err, Error); + assert.equal(err.message, + 'CookieJar store is not synchronous; use async API instead.'); + } + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_jar_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_jar_test.js new file mode 100644 index 0000000..689407b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_jar_test.js @@ -0,0 +1,468 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var async = require('async'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; +var CookieJar = tough.CookieJar; + +var atNow = Date.now(); + +function at(offset) { + return {now: new Date(atNow + offset)}; +} + +vows + .describe('CookieJar') + .addBatch({ + "Setting a basic cookie": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now() - 10000); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "works": function (c) { + assert.instanceOf(c, Cookie) + }, // C is for Cookie, good enough for me + "gets timestamped": function (c) { + assert.ok(c.creation); + assert.ok(Date.now() - c.creation.getTime() < 5000); // recently stamped + assert.ok(c.lastAccessed); + assert.equal(c.creation, c.lastAccessed); + assert.equal(c.TTL(), Infinity); + assert.ok(!c.isPersistent()); + } + }, + "Setting a no-path cookie": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now() - 10000); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "domain": function (c) { + assert.equal(c.domain, 'example.com') + }, + "path is /": function (c) { + assert.equal(c.path, '/') + }, + "path was derived": function (c) { + assert.strictEqual(c.pathIsDefault, true) + } + }, + "Setting a cookie already marked as host-only": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now() - 10000); + c.hostOnly = true; + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "domain": function (c) { + assert.equal(c.domain, 'example.com') + }, + "still hostOnly": function (c) { + assert.strictEqual(c.hostOnly, true) + } + }, + "Setting a session cookie": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b"); + assert.strictEqual(c.path, null); + cj.setCookie(c, 'http://www.example.com/dir/index.html', this.callback); + }, + "works": function (c) { + assert.instanceOf(c, Cookie) + }, + "gets the domain": function (c) { + assert.equal(c.domain, 'www.example.com') + }, + "gets the default path": function (c) { + assert.equal(c.path, '/dir') + }, + "is 'hostOnly'": function (c) { + assert.ok(c.hostOnly) + } + }, + "Setting wrong domain cookie": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=fooxample.com; Path=/"); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "fails": function (err, c) { + assert.ok(err.message.match(/domain/i)); + assert.ok(!c); + } + }, + "Setting sub-domain cookie": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=www.example.com; Path=/"); + cj.setCookie(c, 'http://example.com/index.html', this.callback); + }, + "fails": function (err, c) { + assert.ok(err.message.match(/domain/i)); + assert.ok(!c); + } + }, + "Setting super-domain cookie": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/"); + cj.setCookie(c, 'http://www.app.example.com/index.html', this.callback); + }, + "success": function (err, c) { + assert.ok(!err); + assert.equal(c.domain, 'example.com'); + } + }, + "Setting a sub-path cookie on a super-domain": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/subpath"); + assert.strictEqual(c.hostOnly, null); + assert.instanceOf(c.creation, Date); + assert.strictEqual(c.lastAccessed, null); + c.creation = new Date(Date.now() - 10000); + cj.setCookie(c, 'http://www.example.com/index.html', this.callback); + }, + "domain is super-domain": function (c) { + assert.equal(c.domain, 'example.com') + }, + "path is /subpath": function (c) { + assert.equal(c.path, '/subpath') + }, + "path was NOT derived": function (c) { + assert.strictEqual(c.pathIsDefault, null) + } + }, + "Setting HttpOnly cookie over non-HTTP API": { + topic: function () { + var cj = new CookieJar(); + var c = Cookie.parse("a=b; Domain=example.com; Path=/; HttpOnly"); + cj.setCookie(c, 'http://example.com/index.html', {http: false}, this.callback); + }, + "fails": function (err, c) { + assert.match(err.message, /HttpOnly/i); + assert.ok(!c); + } + } + }) + .addBatch({ + "Store eight cookies": { + topic: function () { + var cj = new CookieJar(); + var ex = 'http://example.com/index.html'; + var tasks = []; + tasks.push(function (next) { + cj.setCookie('a=1; Domain=example.com; Path=/', ex, at(0), next); + }); + tasks.push(function (next) { + cj.setCookie('b=2; Domain=example.com; Path=/; HttpOnly', ex, at(1000), next); + }); + tasks.push(function (next) { + cj.setCookie('c=3; Domain=example.com; Path=/; Secure', ex, at(2000), next); + }); + tasks.push(function (next) { // path + cj.setCookie('d=4; Domain=example.com; Path=/foo', ex, at(3000), next); + }); + tasks.push(function (next) { // host only + cj.setCookie('e=5', ex, at(4000), next); + }); + tasks.push(function (next) { // other domain + cj.setCookie('f=6; Domain=nodejs.org; Path=/', 'http://nodejs.org', at(5000), next); + }); + tasks.push(function (next) { // expired + cj.setCookie('g=7; Domain=example.com; Path=/; Expires=Tue, 18 Oct 2011 00:00:00 GMT', ex, at(6000), next); + }); + tasks.push(function (next) { // expired via Max-Age + cj.setCookie('h=8; Domain=example.com; Path=/; Max-Age=1', ex, next); + }); + var cb = this.callback; + async.parallel(tasks, function (err, results) { + setTimeout(function () { + cb(err, cj, results); + }, 2000); // so that 'h=8' expires + }); + }, + "setup ok": function (err, cj, results) { + assert.ok(!err); + assert.ok(cj); + assert.ok(results); + }, + "then retrieving for http://nodejs.org": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('http://nodejs.org', this.callback); + }, + "get a nodejs cookie": function (cookies) { + assert.lengthOf(cookies, 1); + var cookie = cookies[0]; + assert.equal(cookie.domain, 'nodejs.org'); + } + }, + "then retrieving for https://example.com": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('https://example.com', {secure: true}, this.callback); + }, + "get a secure example cookie with others": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['a', 'b', 'c', 'e']); + } + }, + "then retrieving for https://example.com (missing options)": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('https://example.com', this.callback); + }, + "get a secure example cookie with others": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['a', 'b', 'c', 'e']); + } + }, + "then retrieving for http://example.com": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('http://example.com', this.callback); + }, + "get a bunch of cookies": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['a', 'b', 'e']); + } + }, + "then retrieving for http://EXAMPlE.com": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('http://EXAMPlE.com', this.callback); + }, + "get a bunch of cookies": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['a', 'b', 'e']); + } + }, + "then retrieving for http://example.com, non-HTTP": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('http://example.com', {http: false}, this.callback); + }, + "get a bunch of cookies": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['a', 'e']); + } + }, + "then retrieving for http://example.com/foo/bar": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('http://example.com/foo/bar', this.callback); + }, + "get a bunch of cookies": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['d', 'a', 'b', 'e']); + } + }, + "then retrieving for http://example.com as a string": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookieString('http://example.com', this.callback); + }, + "get a single string": function (cookieHeader) { + assert.equal(cookieHeader, "a=1; b=2; e=5"); + } + }, + "then retrieving for http://example.com as a set-cookie header": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getSetCookieStrings('http://example.com', this.callback); + }, + "get a single string": function (cookieHeaders) { + assert.lengthOf(cookieHeaders, 3); + assert.equal(cookieHeaders[0], "a=1; Domain=example.com; Path=/"); + assert.equal(cookieHeaders[1], "b=2; Domain=example.com; Path=/; HttpOnly"); + assert.equal(cookieHeaders[2], "e=5; Path=/"); + } + }, + "then retrieving for http://www.example.com/": { + topic: function (cj, oldResults) { + assert.ok(oldResults); + cj.getCookies('http://www.example.com/foo/bar', this.callback); + }, + "get a bunch of cookies": function (cookies) { + var names = cookies.map(function (c) { + return c.key + }); + assert.deepEqual(names, ['d', 'a', 'b']); // note lack of 'e' + } + } + } + }) + .addBatch({ + "Repeated names": { + topic: function () { + var cb = this.callback; + var cj = new CookieJar(); + var ex = 'http://www.example.com/'; + var sc = cj.setCookie; + var tasks = []; + var now = Date.now(); + tasks.push(sc.bind(cj, 'aaaa=xxxx', ex, at(0))); + tasks.push(sc.bind(cj, 'aaaa=1111; Domain=www.example.com', ex, at(1000))); + tasks.push(sc.bind(cj, 'aaaa=2222; Domain=example.com', ex, at(2000))); + tasks.push(sc.bind(cj, 'aaaa=3333; Domain=www.example.com; Path=/pathA', ex, at(3000))); + async.series(tasks, function (err, results) { + results = results.filter(function (e) { + return e !== undefined + }); + cb(err, {cj: cj, cookies: results, now: now}); + }); + }, + "all got set": function (err, t) { + assert.lengthOf(t.cookies, 4); + }, + "then getting 'em back": { + topic: function (t) { + var cj = t.cj; + cj.getCookies('http://www.example.com/pathA', this.callback); + }, + "there's just three": function (err, cookies) { + var vals = cookies.map(function (c) { + return c.value + }); + // may break with sorting; sorting should put 3333 first due to longest path: + assert.deepEqual(vals, ['3333', '1111', '2222']); + } + } + } + }) + .addBatch({ + "CookieJar setCookie errors": { + "public-suffix domain": { + topic: function () { + var cj = new CookieJar(); + cj.setCookie('i=9; Domain=kyoto.jp; Path=/', 'kyoto.jp', this.callback); + }, + "errors": function (err, cookie) { + assert.ok(err); + assert.ok(!cookie); + assert.match(err.message, /public suffix/i); + } + }, + "wrong domain": { + topic: function () { + var cj = new CookieJar(); + cj.setCookie('j=10; Domain=google.com; Path=/', 'http://google.ca', this.callback); + }, + "errors": function (err, cookie) { + assert.ok(err); + assert.ok(!cookie); + assert.match(err.message, /not in this host's domain/i); + } + }, + "old cookie is HttpOnly": { + topic: function () { + var cb = this.callback; + var next = function (err, c) { + c = null; + return cb(err, cj); + }; + var cj = new CookieJar(); + cj.setCookie('k=11; Domain=example.ca; Path=/; HttpOnly', 'http://example.ca', {http: true}, next); + }, + "initial cookie is set": function (err, cj) { + assert.ok(!err); + assert.ok(cj); + }, + "but when trying to overwrite": { + topic: function (cj) { + var cb = this.callback; + var next = function (err, c) { + c = null; + cb(null, err); + }; + cj.setCookie('k=12; Domain=example.ca; Path=/', 'http://example.ca', {http: false}, next); + }, + "it's an error": function (err) { + assert.ok(err); + }, + "then, checking the original": { + topic: function (ignored, cj) { + assert.ok(cj instanceof CookieJar); + cj.getCookies('http://example.ca', {http: true}, this.callback); + }, + "cookie has original value": function (err, cookies) { + assert.equal(err, null); + assert.lengthOf(cookies, 1); + assert.equal(cookies[0].value, 11); + } + } + } + }, + "similar to public suffix": { + topic: function () { + var cj = new CookieJar(); + var url = 'http://www.foonet.net'; + assert.isTrue(cj.rejectPublicSuffixes); + cj.setCookie('l=13; Domain=foonet.net; Path=/', url, this.callback); + }, + "doesn't error": function (err, cookie) { + assert.ok(!err); + assert.ok(cookie); + } + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_sorting_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_sorting_test.js new file mode 100644 index 0000000..8cc9842 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_sorting_test.js @@ -0,0 +1,90 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; + +function toKeyArray(cookies) { + return cookies.map(function (c) { + return c.key + }); +} + +vows + .describe('Cookie sorting') + .addBatch({ + "Cookie Sorting": { + topic: function () { + var cookies = []; + cookies.push(Cookie.parse("a=0; Domain=example.com")); + cookies.push(Cookie.parse("b=1; Domain=www.example.com")); + cookies.push(Cookie.parse("c=2; Domain=example.com; Path=/pathA")); + cookies.push(Cookie.parse("d=3; Domain=www.example.com; Path=/pathA")); + cookies.push(Cookie.parse("e=4; Domain=example.com; Path=/pathA/pathB")); + cookies.push(Cookie.parse("f=5; Domain=www.example.com; Path=/pathA/pathB")); + + // weak shuffle: + cookies = cookies.sort(function () { + return Math.random() - 0.5 + }); + + cookies = cookies.sort(tough.cookieCompare); + return cookies; + }, + "got": function (cookies) { + assert.lengthOf(cookies, 6); + assert.deepEqual(toKeyArray(cookies), ['e', 'f', 'c', 'd', 'a', 'b']); + } + } + }) + .addBatch({ + "Changing creation date affects sorting": { + topic: function () { + var cookies = []; + var now = Date.now(); + cookies.push(Cookie.parse("a=0;")); + cookies.push(Cookie.parse("b=1;")); + cookies.push(Cookie.parse("c=2;")); + + cookies.forEach(function (cookie, idx) { + cookie.creation = new Date(now - 100 * idx); + }); + + return cookies.sort(tough.cookieCompare); + }, + "got": function (cookies) { + assert.deepEqual(toKeyArray(cookies), ['c', 'b', 'a']); + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_json_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_json_test.js new file mode 100644 index 0000000..cc3f1fc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_json_test.js @@ -0,0 +1,164 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; + +vows + .describe('Cookie.toJSON()') + .addBatch({ + "JSON": { + "serialization": { + topic: function() { + var c = Cookie.parse('alpha=beta; Domain=example.com; Path=/foo; Expires=Tue, 19 Jan 2038 03:14:07 GMT; HttpOnly'); + return JSON.stringify(c); + }, + "gives a string": function(str) { + assert.equal(typeof str, "string"); + }, + "date is in ISO format": function(str) { + assert.match(str, /"expires":"2038-01-19T03:14:07\.000Z"/, 'expires is in ISO format'); + } + }, + "deserialization": { + topic: function() { + var json = '{"key":"alpha","value":"beta","domain":"example.com","path":"/foo","expires":"2038-01-19T03:14:07.000Z","httpOnly":true,"lastAccessed":2000000000123}'; + return Cookie.fromJSON(json); + }, + "works": function(c) { + assert.ok(c); + }, + "key": function(c) { assert.equal(c.key, "alpha") }, + "value": function(c) { assert.equal(c.value, "beta") }, + "domain": function(c) { assert.equal(c.domain, "example.com") }, + "path": function(c) { assert.equal(c.path, "/foo") }, + "httpOnly": function(c) { assert.strictEqual(c.httpOnly, true) }, + "secure": function(c) { assert.strictEqual(c.secure, false) }, + "hostOnly": function(c) { assert.strictEqual(c.hostOnly, null) }, + "expires is a date object": function(c) { + assert.equal(c.expires.getTime(), 2147483647000); + }, + "lastAccessed is a date object": function(c) { + assert.equal(c.lastAccessed.getTime(), 2000000000123); + }, + "creation defaulted": function(c) { + assert.ok(c.creation.getTime()); + } + }, + "null deserialization": { + topic: function() { + return Cookie.fromJSON(null); + }, + "is null": function(cookie) { + assert.equal(cookie,null); + } + } + }, + "expiry deserialization": { + "Infinity": { + topic: Cookie.fromJSON.bind(null, '{"expires":"Infinity"}'), + "is infinite": function(c) { + assert.strictEqual(c.expires, "Infinity"); + assert.equal(c.expires, Infinity); + } + } + }, + "maxAge serialization": { + topic: function() { + return function(toSet) { + var c = new Cookie(); + c.key = 'foo'; c.value = 'bar'; + c.setMaxAge(toSet); + return JSON.stringify(c); + }; + }, + "zero": { + topic: function(f) { return f(0) }, + "looks good": function(str) { + assert.match(str, /"maxAge":0/); + } + }, + "Infinity": { + topic: function(f) { return f(Infinity) }, + "looks good": function(str) { + assert.match(str, /"maxAge":"Infinity"/); + } + }, + "-Infinity": { + topic: function(f) { return f(-Infinity) }, + "looks good": function(str) { + assert.match(str, /"maxAge":"-Infinity"/); + } + }, + "null": { + topic: function(f) { return f(null) }, + "looks good": function(str) { + assert.match(str, /"maxAge":null/); + } + } + }, + "maxAge deserialization": { + "number": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":123}'), + "is the number": function(c) { + assert.strictEqual(c.maxAge, 123); + } + }, + "null": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":null}'), + "is null": function(c) { + assert.strictEqual(c.maxAge, null); + } + }, + "less than zero": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":-123}'), + "is -123": function(c) { + assert.strictEqual(c.maxAge, -123); + } + }, + "Infinity": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":"Infinity"}'), + "is inf-as-string": function(c) { + assert.strictEqual(c.maxAge, "Infinity"); + } + }, + "-Infinity": { + topic: Cookie.fromJSON.bind(null,'{"key":"foo","value":"bar","maxAge":"-Infinity"}'), + "is inf-as-string": function(c) { + assert.strictEqual(c.maxAge, "-Infinity"); + } + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_string_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_string_test.js new file mode 100644 index 0000000..b7ad10d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/cookie_to_string_test.js @@ -0,0 +1,162 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; + +vows + .describe('Cookie.toString()') + .addBatch({ + "a simple cookie": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + return c; + }, + "validates": function (c) { + assert.ok(c.validate()); + }, + "to string": function (c) { + assert.equal(c.toString(), 'a=b'); + } + }, + "a cookie with spaces in the value": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'beta gamma'; + return c; + }, + "doesn't validate": function (c) { + assert.ok(!c.validate()); + }, + "'garbage in, garbage out'": function (c) { + assert.equal(c.toString(), 'a=beta gamma'); + } + }, + "with an empty value and HttpOnly": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.httpOnly = true; + return c; + }, + "to string": function (c) { + assert.equal(c.toString(), 'a=; HttpOnly'); + } + }, + "with an expiry": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.setExpires("Oct 18 2011 07:05:03 GMT"); + return c; + }, + "validates": function (c) { + assert.ok(c.validate()); + }, + "to string": function (c) { + assert.equal(c.toString(), 'a=b; Expires=Tue, 18 Oct 2011 07:05:03 GMT'); + }, + "to short string": function (c) { + assert.equal(c.cookieString(), 'a=b'); + } + }, + "with a max-age": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.setExpires("Oct 18 2011 07:05:03 GMT"); + c.maxAge = 12345; + return c; + }, + "validates": function (c) { + assert.ok(c.validate()); // mabe this one *shouldn't*? + }, + "to string": function (c) { + assert.equal(c.toString(), 'a=b; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Max-Age=12345'); + } + }, + "with a bunch of things": function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.setExpires("Oct 18 2011 07:05:03 GMT"); + c.maxAge = 12345; + c.domain = 'example.com'; + c.path = '/foo'; + c.secure = true; + c.httpOnly = true; + c.extensions = ['MyExtension']; + assert.equal(c.toString(), 'a=b; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Max-Age=12345; Domain=example.com; Path=/foo; Secure; HttpOnly; MyExtension'); + }, + "a host-only cookie": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.hostOnly = true; + c.domain = 'shouldnt-stringify.example.com'; + c.path = '/should-stringify'; + return c; + }, + "validates": function (c) { + assert.ok(c.validate()); + }, + "to string": function (c) { + assert.equal(c.toString(), 'a=b; Path=/should-stringify'); + } + }, + "minutes are '10'": { + topic: function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.expires = new Date(1284113410000); + return c; + }, + "validates": function (c) { + assert.ok(c.validate()); + }, + "to string": function (c) { + var str = c.toString(); + assert.notEqual(str, 'a=b; Expires=Fri, 010 Sep 2010 010:010:010 GMT'); + assert.equal(str, 'a=b; Expires=Fri, 10 Sep 2010 10:10:10 GMT'); + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/date_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/date_test.js new file mode 100644 index 0000000..afd989c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/date_test.js @@ -0,0 +1,79 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); + +function dateVows(table) { + var theVows = {}; + Object.keys(table).forEach(function (date) { + var expect = table[date]; + theVows[date] = function () { + var got = tough.parseDate(date) ? 'valid' : 'invalid'; + assert.equal(got, expect ? 'valid' : 'invalid'); + }; + }); + return {"date parsing": theVows}; +} + +vows + .describe('Date') + .addBatch(dateVows({ + "Wed, 09 Jun 2021 10:18:14 GMT": true, + "Wed, 09 Jun 2021 22:18:14 GMT": true, + "Tue, 18 Oct 2011 07:42:42.123 GMT": true, + "18 Oct 2011 07:42:42 GMT": true, + "8 Oct 2011 7:42:42 GMT": true, + "8 Oct 2011 7:2:42 GMT": true, + "Oct 18 2011 07:42:42 GMT": true, + "Tue Oct 18 2011 07:05:03 GMT+0000 (GMT)": true, + "09 Jun 2021 10:18:14 GMT": true, + "99 Jix 3038 48:86:72 ZMT": false, + '01 Jan 1970 00:00:00 GMT': true, + '01 Jan 1600 00:00:00 GMT': false, // before 1601 + '01 Jan 1601 00:00:00 GMT': true, + '10 Feb 81 13:00:00 GMT': true, // implicit year + 'Thu, 17-Apr-2014 02:12:29 GMT': true, // dashes + 'Thu, 17-Apr-2014 02:12:29 UTC': true // dashes and UTC + })) + .addBatch({ + "strict date parse of Thu, 01 Jan 1970 00:00:010 GMT": { + topic: function () { + return tough.parseDate('Thu, 01 Jan 1970 00:00:010 GMT', true) ? true : false; + }, + "invalid": function (date) { + assert.equal(date, false); + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/domain_and_path_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/domain_and_path_test.js new file mode 100644 index 0000000..36b85b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/domain_and_path_test.js @@ -0,0 +1,201 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; + +function matchVows(func, table) { + var theVows = {}; + table.forEach(function (item) { + var str = item[0]; + var dom = item[1]; + var expect = item[2]; + var label = str + (expect ? " matches " : " doesn't match ") + dom; + theVows[label] = function () { + assert.equal(func(str, dom), expect); + }; + }); + return theVows; +} + +function defaultPathVows(table) { + var theVows = {}; + table.forEach(function (item) { + var str = item[0]; + var expect = item[1]; + var label = str + " gives " + expect; + theVows[label] = function () { + assert.equal(tough.defaultPath(str), expect); + }; + }); + return theVows; +} + +vows + .describe('Domain and Path') + .addBatch({ + "domain normalization": { + "simple": function () { + var c = new Cookie(); + c.domain = "EXAMPLE.com"; + assert.equal(c.canonicalizedDomain(), "example.com"); + }, + "extra dots": function () { + var c = new Cookie(); + c.domain = ".EXAMPLE.com"; + assert.equal(c.cdomain(), "example.com"); + }, + "weird trailing dot": function () { + var c = new Cookie(); + c.domain = "EXAMPLE.ca."; + assert.equal(c.canonicalizedDomain(), "example.ca."); + }, + "weird internal dots": function () { + var c = new Cookie(); + c.domain = "EXAMPLE...ca."; + assert.equal(c.canonicalizedDomain(), "example...ca."); + }, + "IDN": function () { + var c = new Cookie(); + c.domain = "δοκιμή.δοκιμή"; // "test.test" in greek + assert.equal(c.canonicalizedDomain(), "xn--jxalpdlp.xn--jxalpdlp"); + } + } + }) + .addBatch({ + "Domain Match": matchVows(tough.domainMatch, [ + // str, dom, expect + ["example.com", "example.com", true], + ["eXaMpLe.cOm", "ExAmPlE.CoM", true], + ["no.ca", "yes.ca", false], + ["wwwexample.com", "example.com", false], + ["www.example.com", "example.com", true], + ["example.com", "www.example.com", false], + ["www.subdom.example.com", "example.com", true], + ["www.subdom.example.com", "subdom.example.com", true], + ["example.com", "example.com.", false], // RFC6265 S4.1.2.3 + ["192.168.0.1", "168.0.1", false], // S5.1.3 "The string is a host name" + [null, "example.com", null], + ["example.com", null, null], + [null, null, null], + [undefined, undefined, null], + ]) + }) + + .addBatch({ + "default-path": defaultPathVows([ + [null, "/"], + ["/", "/"], + ["/file", "/"], + ["/dir/file", "/dir"], + ["noslash", "/"], + ]) + }) + .addBatch({ + "Path-Match": matchVows(tough.pathMatch, [ + // request, cookie, match + ["/", "/", true], + ["/dir", "/", true], + ["/", "/dir", false], + ["/dir/", "/dir/", true], + ["/dir/file", "/dir/", true], + ["/dir/file", "/dir", true], + ["/directory", "/dir", false], + ]) + }) + .addBatch({ + "permuteDomain": { + "base case": { + topic: tough.permuteDomain.bind(null, 'example.com'), + "got the domain": function (list) { + assert.deepEqual(list, ['example.com']); + } + }, + "two levels": { + topic: tough.permuteDomain.bind(null, 'foo.bar.example.com'), + "got three things": function (list) { + assert.deepEqual(list, ['example.com', 'bar.example.com', 'foo.bar.example.com']); + } + }, + "local domain": { + topic: tough.permuteDomain.bind(null, 'foo.bar.example.localduhmain'), + "got three things": function (list) { + assert.deepEqual(list, ['example.localduhmain', 'bar.example.localduhmain', 'foo.bar.example.localduhmain']); + } + } + }, + "permutePath": { + "base case": { + topic: tough.permutePath.bind(null, '/'), + "just slash": function (list) { + assert.deepEqual(list, ['/']); + } + }, + "single case": { + topic: tough.permutePath.bind(null, '/foo'), + "two things": function (list) { + assert.deepEqual(list, ['/foo', '/']); + }, + "path matching": function (list) { + list.forEach(function (e) { + assert.ok(tough.pathMatch('/foo', e)); + }); + } + }, + "double case": { + topic: tough.permutePath.bind(null, '/foo/bar'), + "four things": function (list) { + assert.deepEqual(list, ['/foo/bar', '/foo', '/']); + }, + "path matching": function (list) { + list.forEach(function (e) { + assert.ok(tough.pathMatch('/foo/bar', e)); + }); + } + }, + "trailing slash": { + topic: tough.permutePath.bind(null, '/foo/bar/'), + "three things": function (list) { + assert.deepEqual(list, ['/foo/bar', '/foo', '/']); + }, + "path matching": function (list) { + list.forEach(function (e) { + assert.ok(tough.pathMatch('/foo/bar/', e)); + }); + } + } + } + }) + .export(module); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/bsd-examples.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/bsd-examples.json new file mode 100644 index 0000000..bc43160 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/bsd-examples.json @@ -0,0 +1,168 @@ +[ + { + "test": "Sat, 15-Apr-17 21:01:22 GMT", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Thu, 19-Apr-2007 16:00:00 GMT", + "expected": "Thu, 19 Apr 2007 16:00:00 GMT" + }, { + "test": "Wed, 25 Apr 2007 21:02:13 GMT", + "expected": "Wed, 25 Apr 2007 21:02:13 GMT" + }, { + "test": "Thu, 19/Apr\\2007 16:00:00 GMT", + "expected": "Thu, 19 Apr 2007 16:00:00 GMT" + }, { + "test": "Fri, 1 Jan 2010 01:01:50 GMT", + "expected": "Fri, 01 Jan 2010 01:01:50 GMT" + }, { + "test": "Wednesday, 1-Jan-2003 00:00:00 GMT", + "expected": "Wed, 01 Jan 2003 00:00:00 GMT" + }, { + "test": ", 1-Jan-2003 00:00:00 GMT", + "expected": "Wed, 01 Jan 2003 00:00:00 GMT" + }, { + "test": " 1-Jan-2003 00:00:00 GMT", + "expected": "Wed, 01 Jan 2003 00:00:00 GMT" + }, { + "test": "1-Jan-2003 00:00:00 GMT", + "expected": "Wed, 01 Jan 2003 00:00:00 GMT" + }, { + "test": "Wed,18-Apr-07 22:50:12 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "WillyWonka , 18-Apr-07 22:50:12 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "WillyWonka , 18-Apr-07 22:50:12", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "WillyWonka , 18-apr-07 22:50:12", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Mon, 18-Apr-1977 22:50:13 GMT", + "expected": "Mon, 18 Apr 1977 22:50:13 GMT" + }, { + "test": "Mon, 18-Apr-77 22:50:13 GMT", + "expected": "Mon, 18 Apr 1977 22:50:13 GMT" + }, { + "test": "\"Sat, 15-Apr-17\\\"21:01:22\\\"GMT\"", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Partyday, 18- April-07 22:50:12", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Partyday, 18 - Apri-07 22:50:12", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Wednes, 1-Januar-2003 00:00:00 GMT", + "expected": "Wed, 01 Jan 2003 00:00:00 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 GMT-2", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 GMT BLAH", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 GMT-0400", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 GMT-0400 (EDT)", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 DST", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 -0400", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 (hello there)", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 11:22:33", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 ::00 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 boink:z 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Sat, 15-Apr-17 91:22:33 21:01:22", + "expected": null + }, { + "test": "Thu Apr 18 22:50:12 2007 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "22:50:12 Thu Apr 18 2007 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Thu 22:50:12 Apr 18 2007 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Thu Apr 22:50:12 18 2007 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Thu Apr 18 22:50:12 2007 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Thu Apr 18 2007 22:50:12 GMT", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Thu Apr 18 2007 GMT 22:50:12", + "expected": "Wed, 18 Apr 2007 22:50:12 GMT" + }, { + "test": "Sat, 15-Apr-17 21:01:22 GMT", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "15-Sat, Apr-17 21:01:22 GMT", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "15-Sat, Apr 21:01:22 GMT 17", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "15-Sat, Apr 21:01:22 GMT 2017", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "15 Apr 21:01:22 2017", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "15 17 Apr 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Apr 15 17 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "Apr 15 21:01:22 17", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "2017 April 15 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "15 April 2017 21:01:22", + "expected": "Sat, 15 Apr 2017 21:01:22 GMT" + }, { + "test": "98 April 17 21:01:22", + "expected": null + }, { + "test": "Thu, 012-Aug-2008 20:49:07 GMT", + "expected": null + }, { + "test": "Thu, 12-Aug-31841 20:49:07 GMT", + "expected": null + }, { + "test": "Thu, 12-Aug-9999999999 20:49:07 GMT", + "expected": null + }, { + "test": "Thu, 999999999999-Aug-2007 20:49:07 GMT", + "expected": null + }, { + "test": "Thu, 12-Aug-2007 20:61:99999999999 GMT", + "expected": null + }, { + "test": "IAintNoDateFool", + "expected": null + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/examples.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/examples.json new file mode 100644 index 0000000..61e674d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/dates/examples.json @@ -0,0 +1,48 @@ +[ + { + "test": "Mon, 10-Dec-2007 17:02:24 GMT", + "expected": "Mon, 10 Dec 2007 17:02:24 GMT" + }, { + "test": "Wed, 09 Dec 2009 16:27:23 GMT", + "expected": "Wed, 09 Dec 2009 16:27:23 GMT" + }, { + "test": "Thursday, 01-Jan-1970 00:00:00 GMT", + "expected": "Thu, 01 Jan 1970 00:00:00 GMT" + }, { + "test": "Mon Dec 10 16:32:30 2007 GMT", + "expected": "Mon, 10 Dec 2007 16:32:30 GMT" + }, { + "test": "Wednesday, 01-Jan-10 00:00:00 GMT", + "expected": "Fri, 01 Jan 2010 00:00:00 GMT" + }, { + "test": "Mon, 10-Dec-07 20:35:03 GMT", + "expected": "Mon, 10 Dec 2007 20:35:03 GMT" + }, { + "test": "Wed, 1 Jan 2020 00:00:00 GMT", + "expected": "Wed, 01 Jan 2020 00:00:00 GMT" + }, { + "test": "Saturday, 8-Dec-2012 21:24:09 GMT", + "expected": "Sat, 08 Dec 2012 21:24:09 GMT" + }, { + "test": "Thu, 31 Dec 23:55:55 2037 GMT", + "expected": "Thu, 31 Dec 2037 23:55:55 GMT" + }, { + "test": "Sun, 9 Dec 2012 13:42:05 GMT", + "expected": "Sun, 09 Dec 2012 13:42:05 GMT" + }, { + "test": "Wed Dec 12 2007 08:44:07 GMT-0500 (EST)", + "expected": "Wed, 12 Dec 2007 08:44:07 GMT" + }, { + "test": "Mon, 01-Jan-2011 00: 00:00 GMT", + "expected": null + }, { + "test": "Sun, 1-Jan-1995 00:00:00 GMT", + "expected": "Sun, 01 Jan 1995 00:00:00 GMT" + }, { + "test": "Wednesday, 01-Jan-10 0:0:00 GMT", + "expected": "Fri, 01 Jan 2010 00:00:00 GMT" + }, { + "test": "Thu, 10 Dec 2009 13:57:2 GMT", + "expected": "Thu, 10 Dec 2009 13:57:02 GMT" + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/parser.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/parser.json new file mode 100644 index 0000000..783f660 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_data/parser.json @@ -0,0 +1,1959 @@ +[ + { + "test": "0001", + "received": [ + "foo=bar" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0002", + "received": [ + "foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0003", + "received": [ + "foo=bar; Expires=Fri, 07 Aug 2007 08:04:19 GMT", + "foo2=bar2; Expires=Fri, 07 Aug 2017 08:04:19 GMT" + ], + "sent": [ + { "name": "foo2", "value": "bar2" } + ] + }, + { + "test": "0004", + "received": [ + "foo" + ], + "sent": [] + }, + { + "test": "0005", + "received": [ + "foo=bar; max-age=10000;" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0006", + "received": [ + "foo=bar; max-age=0;" + ], + "sent": [] + }, + { + "test": "0007", + "received": [ + "foo=bar; version=1;" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0008", + "received": [ + "foo=bar; version=1000;" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0009", + "received": [ + "foo=bar; customvalue=1000;" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0010", + "received": [ + "foo=bar; secure;" + ], + "sent": [] + }, + { + "test": "0011", + "received": [ + "foo=bar; customvalue=\"1000 or more\";" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0012", + "received": [ + "foo=bar; customvalue=\"no trailing semicolon\"" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "0013", + "received": [ + "foo=bar", + "foo=qux" + ], + "sent": [ + { "name": "foo", "value": "qux" } + ] + }, + { + "test": "0014", + "received": [ + "foo1=bar", + "foo2=qux" + ], + "sent": [ + { "name": "foo1", "value": "bar" }, + { "name": "foo2", "value": "qux" } + ] + }, + { + "test": "0015", + "received": [ + "a=b", + "z=y" + ], + "sent": [ + { "name": "a", "value": "b" }, + { "name": "z", "value": "y" } + ] + }, + { + "test": "0016", + "received": [ + "z=y", + "a=b" + ], + "sent": [ + { "name": "z", "value": "y" }, + { "name": "a", "value": "b" } + ] + }, + { + "test": "0017", + "received": [ + "z=y, a=b" + ], + "sent": [ + { "name": "z", "value": "y, a=b" } + ] + }, + { + "test": "0018", + "received": [ + "z=y; foo=bar, a=b" + ], + "sent": [ + { "name": "z", "value": "y" } + ] + }, + { + "test": "0019", + "received": [ + "foo=b;max-age=3600, c=d;path=/" + ], + "sent": [ + { "name": "foo", "value": "b" } + ] + }, + { + "test": "0020", + "received": [ + "a=b", + "=", + "c=d" + ], + "sent": [ + { "name": "a", "value": "b" }, + { "name": "c", "value": "d" } + ] + }, + { + "test": "0021", + "received": [ + "a=b", + "=x", + "c=d" + ], + "sent": [ + { "name": "a", "value": "b" }, + { "name": "c", "value": "d" } + ] + }, + { + "test": "0022", + "received": [ + "a=b", + "x=", + "c=d" + ], + "sent": [ + { "name": "a", "value": "b" }, + { "name": "x", "value": "" }, + { "name": "c", "value": "d" } + ] + }, + { + "test": "0023", + "received": [ + "foo", + "" + ], + "sent": [] + }, + { + "test": "0024", + "received": [ + "foo", + "=" + ], + "sent": [] + }, + { + "test": "0025", + "received": [ + "foo", + "; bar" + ], + "sent": [] + }, + { + "test": "0026", + "received": [ + "foo", + " " + ], + "sent": [] + }, + { + "test": "0027", + "received": [ + "foo", + "bar" + ], + "sent": [] + }, + { + "test": "0028", + "received": [ + "foo", + "\t" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0001", + "received": [ + "foo=bar; Secure" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0002", + "received": [ + "foo=bar; seCURe" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0003", + "received": [ + "foo=bar; \"Secure\"" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0004", + "received": [ + "foo=bar; Secure=" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0005", + "received": [ + "foo=bar; Secure=aaaa" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0006", + "received": [ + "foo=bar; Secure qux" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0007", + "received": [ + "foo=bar; Secure =aaaaa" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0008", + "received": [ + "foo=bar; Secure= aaaaa" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0009", + "received": [ + "foo=bar; Secure; qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0010", + "received": [ + "foo=bar; Secure;qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0011", + "received": [ + "foo=bar; Secure ; qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0012", + "received": [ + "foo=bar; Secure" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0013", + "received": [ + "foo=bar; Secure ;" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0014", + "received": [ + "foo=bar; Path" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0015", + "received": [ + "foo=bar; Path=" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0016", + "received": [ + "foo=bar; Path=/" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0017", + "received": [ + "foo=bar; Path=/qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0018", + "received": [ + "foo=bar; Path =/qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0019", + "received": [ + "foo=bar; Path= /qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0020", + "received": [ + "foo=bar; Path=/qux ; taz" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0021", + "received": [ + "foo=bar; Path=/qux; Path=/" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0022", + "received": [ + "foo=bar; Path=/; Path=/qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0023", + "received": [ + "foo=bar; Path=/qux; Path=/cookie-parser-result" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "ATTRIBUTE0024", + "received": [ + "foo=bar; Path=/cookie-parser-result; Path=/qux" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0025", + "received": [ + "foo=bar; qux; Secure" + ], + "sent": [] + }, + { + "test": "ATTRIBUTE0026", + "received": [ + "foo=bar; qux=\"aaa;bbb\"; Secure" + ], + "sent": [] + }, + { + "test": "CHARSET0001", + "received": [ + "foo=\u6625\u8282\u56de\u5bb6\u8def\u00b7\u6625\u8fd0\u5b8c\u5168\u624b\u518c" + ], + "sent": [ + { "name": "foo", "value": "\u6625\u8282\u56de\u5bb6\u8def\u00b7\u6625\u8fd0\u5b8c\u5168\u624b\u518c" } + ] + }, + { + "test": "CHARSET0002", + "received": [ + "\u6625\u8282\u56de=\u5bb6\u8def\u00b7\u6625\u8fd0\u5b8c\u5168\u624b\u518c" + ], + "sent": [ + { "name": "\u6625\u8282\u56de", "value": "\u5bb6\u8def\u00b7\u6625\u8fd0\u5b8c\u5168\u624b\u518c" } + ] + }, + { + "test": "CHARSET0003", + "received": [ + "\u6625\u8282\u56de=\u5bb6\u8def\u00b7\u6625\u8fd0; \u5b8c\u5168\u624b\u518c" + ], + "sent": [ + { "name": "\u6625\u8282\u56de", "value": "\u5bb6\u8def\u00b7\u6625\u8fd0" } + ] + }, + { + "test": "CHARSET0004", + "received": [ + "foo=\"\u6625\u8282\u56de\u5bb6\u8def\u00b7\u6625\u8fd0\u5b8c\u5168\u624b\u518c\"" + ], + "sent": [ + { "name": "foo", "value": "\"\u6625\u8282\u56de\u5bb6\u8def\u00b7\u6625\u8fd0\u5b8c\u5168\u624b\u518c\"" } + ] + }, + { + "test": "CHROMIUM0001", + "received": [ + "a=b" + ], + "sent": [ + { "name": "a", "value": "b" } + ] + }, + { + "test": "CHROMIUM0002", + "received": [ + "aBc=\"zzz \" ;" + ], + "sent": [ + { "name": "aBc", "value": "\"zzz \"" } + ] + }, + { + "test": "CHROMIUM0003", + "received": [ + "aBc=\"zzz \" ;" + ], + "sent": [ + { "name": "aBc", "value": "\"zzz \"" } + ] + }, + { + "test": "CHROMIUM0004", + "received": [ + "aBc=\"zz;pp\" ; ;" + ], + "sent": [ + { "name": "aBc", "value": "\"zz" } + ] + }, + { + "test": "CHROMIUM0005", + "received": [ + "aBc=\"zz ;" + ], + "sent": [ + { "name": "aBc", "value": "\"zz" } + ] + }, + { + "test": "CHROMIUM0006", + "received": [ + "aBc=\"zzz \" \"ppp\" ;" + ], + "sent": [ + { "name": "aBc", "value": "\"zzz \" \"ppp\"" } + ] + }, + { + "test": "CHROMIUM0007", + "received": [ + "aBc=\"zzz \" \"ppp\" ;" + ], + "sent": [ + { "name": "aBc", "value": "\"zzz \" \"ppp\"" } + ] + }, + { + "test": "CHROMIUM0008", + "received": [ + "aBc=A\"B ;" + ], + "sent": [ + { "name": "aBc", "value": "A\"B" } + ] + }, + { + "test": "CHROMIUM0009", + "received": [ + "BLAHHH; path=/;" + ], + "sent": [] + }, + { + "test": "CHROMIUM0010", + "received": [ + "\"BLA\\\"HHH\"; path=/;" + ], + "sent": [] + }, + { + "test": "CHROMIUM0011", + "received": [ + "a=\"B" + ], + "sent": [ + { "name": "a", "value": "\"B" } + ] + }, + { + "test": "CHROMIUM0012", + "received": [ + "=ABC" + ], + "sent": [] + }, + { + "test": "CHROMIUM0013", + "received": [ + "ABC=; path = /" + ], + "sent": [ + { "name": "ABC", "value": "" } + ] + }, + { + "test": "CHROMIUM0014", + "received": [ + " A = BC ;foo;;; bar" + ], + "sent": [ + { "name": "A", "value": "BC" } + ] + }, + { + "test": "CHROMIUM0015", + "received": [ + " A=== BC ;foo;;; bar" + ], + "sent": [ + { "name": "A", "value": "== BC" } + ] + }, + { + "test": "CHROMIUM0016", + "received": [ + "foo=\"zohNumRKgI0oxyhSsV3Z7D\" ; expires=Sun, 18-Apr-2027 21:06:29 GMT ; path=/ ; " + ], + "sent": [ + { "name": "foo", "value": "\"zohNumRKgI0oxyhSsV3Z7D\"" } + ] + }, + { + "test": "CHROMIUM0017", + "received": [ + "foo=zohNumRKgI0oxyhSsV3Z7D ; expires=Sun, 18-Apr-2027 21:06:29 GMT ; path=/ ; " + ], + "sent": [ + { "name": "foo", "value": "zohNumRKgI0oxyhSsV3Z7D" } + ] + }, + { + "test": "CHROMIUM0018", + "received": [ + " " + ], + "sent": [] + }, + { + "test": "CHROMIUM0019", + "received": [ + "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ], + "sent": [ + { "name": "a", "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } + ] + }, + { + "test": "CHROMIUM0021", + "received": [ + "" + ], + "sent": [] + }, + { + "test": "COMMA0001", + "received": [ + "foo=bar, baz=qux" + ], + "sent": [ + { "name": "foo", "value": "bar, baz=qux" } + ] + }, + { + "test": "COMMA0002", + "received": [ + "foo=\"bar, baz=qux\"" + ], + "sent": [ + { "name": "foo", "value": "\"bar, baz=qux\"" } + ] + }, + { + "test": "COMMA0003", + "received": [ + "foo=bar; b,az=qux" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "COMMA0004", + "received": [ + "foo=bar; baz=q,ux" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "COMMA0005", + "received": [ + "foo=bar; Max-Age=50,399" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "COMMA0006", + "received": [ + "foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "COMMA0007", + "received": [ + "foo=bar; Expires=Fri 07 Aug 2019 08:04:19 GMT, baz=qux" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DISABLED_CHROMIUM0020", + "received": [ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ], + "sent": [] + }, + { + "test": "DISABLED_CHROMIUM0022", + "received": [ + "AAA=BB\u0000ZYX" + ], + "sent": [ + { "name": "AAA", "value": "BB" } + ] + }, + { + "test": "DISABLED_CHROMIUM0023", + "received": [ + "AAA=BB\rZYX" + ], + "sent": [ + { "name": "AAA", "value": "BB" } + ] + }, + { + "test": "DISABLED_PATH0029", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/bar" + ], + "sent-to": "/cookie-parser-result/f%6Fo/bar?disabled-path0029", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0001", + "received": [ + "foo=bar; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0001", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0002", + "received": [ + "foo=bar; domain=home.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0002", + "sent": [] + }, + { + "test": "DOMAIN0003", + "received": [ + "foo=bar; domain=.home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0003", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0004", + "received": [ + "foo=bar; domain=home.example.org" + ], + "sent-to": "http://subdomain.home.example.org:8888/cookie-parser-result?domain0004", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0005", + "received": [ + "foo=bar; domain=.home.example.org" + ], + "sent-to": "http://subdomain.home.example.org:8888/cookie-parser-result?domain0005", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0006", + "received": [ + "foo=bar; domain=.home.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0006", + "sent": [] + }, + { + "test": "DOMAIN0007", + "received": [ + "foo=bar; domain=sibling.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0007", + "sent": [] + }, + { + "test": "DOMAIN0008", + "received": [ + "foo=bar; domain=.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0008", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0009", + "received": [ + "foo=bar; domain=example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0009", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0010", + "received": [ + "foo=bar; domain=..home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0010", + "sent": [] + }, + { + "test": "DOMAIN0011", + "received": [ + "foo=bar; domain=home..example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0011", + "sent": [] + }, + { + "test": "DOMAIN0012", + "received": [ + "foo=bar; domain= .home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0012", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0013", + "received": [ + "foo=bar; domain= . home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0013", + "sent": [] + }, + { + "test": "DOMAIN0014", + "received": [ + "foo=bar; domain=home.example.org." + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0014", + "sent": [] + }, + { + "test": "DOMAIN0015", + "received": [ + "foo=bar; domain=home.example.org.." + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0015", + "sent": [] + }, + { + "test": "DOMAIN0016", + "received": [ + "foo=bar; domain=home.example.org ." + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0016", + "sent": [] + }, + { + "test": "DOMAIN0017", + "received": [ + "foo=bar; domain=.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0017", + "sent": [] + }, + { + "test": "DOMAIN0018", + "received": [ + "foo=bar; domain=.org." + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0018", + "sent": [] + }, + { + "test": "DOMAIN0019", + "received": [ + "foo=bar; domain=home.example.org", + "foo2=bar2; domain=.home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0019", + "sent": [ + { "name": "foo", "value": "bar" }, + { "name": "foo2", "value": "bar2" } + ] + }, + { + "test": "DOMAIN0020", + "received": [ + "foo2=bar2; domain=.home.example.org", + "foo=bar; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0020", + "sent": [ + { "name": "foo2", "value": "bar2" }, + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0021", + "received": [ + "foo=bar; domain=\"home.example.org\"" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0021", + "sent": [] + }, + { + "test": "DOMAIN0022", + "received": [ + "foo=bar; domain=home.example.org", + "foo2=bar2; domain=.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0022", + "sent": [ + { "name": "foo", "value": "bar" }, + { "name": "foo2", "value": "bar2" } + ] + }, + { + "test": "DOMAIN0023", + "received": [ + "foo2=bar2; domain=.example.org", + "foo=bar; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0023", + "sent": [ + { "name": "foo2", "value": "bar2" }, + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0024", + "received": [ + "foo=bar; domain=.example.org; domain=home.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0024", + "sent": [] + }, + { + "test": "DOMAIN0025", + "received": [ + "foo=bar; domain=home.example.org; domain=.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0025", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0026", + "received": [ + "foo=bar; domain=home.eXaMpLe.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0026", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0027", + "received": [ + "foo=bar; domain=home.example.org:8888" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0027", + "sent": [] + }, + { + "test": "DOMAIN0028", + "received": [ + "foo=bar; domain=subdomain.home.example.org" + ], + "sent-to": "http://subdomain.home.example.org:8888/cookie-parser-result?domain0028", + "sent": [] + }, + { + "test": "DOMAIN0029", + "received": [ + "foo=bar" + ], + "sent-to": "http://subdomain.home.example.org:8888/cookie-parser-result?domain0029", + "sent": [] + }, + { + "test": "DOMAIN0031", + "received": [ + "foo=bar; domain=home.example.org; domain=.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0031", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0033", + "received": [ + "foo=bar; domain=home.example.org" + ], + "sent-to": "http://hoMe.eXaMplE.org:8888/cookie-parser-result?domain0033", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0034", + "received": [ + "foo=bar; domain=home.example.org; domain=home.example.com" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0034", + "sent": [] + }, + { + "test": "DOMAIN0035", + "received": [ + "foo=bar; domain=home.example.com; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0035", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0036", + "received": [ + "foo=bar; domain=home.example.org; domain=home.example.com; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0036", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0037", + "received": [ + "foo=bar; domain=home.example.com; domain=home.example.org; domain=home.example.com" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0037", + "sent": [] + }, + { + "test": "DOMAIN0038", + "received": [ + "foo=bar; domain=home.example.org; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0038", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0039", + "received": [ + "foo=bar; domain=home.example.org; domain=example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0039", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0040", + "received": [ + "foo=bar; domain=example.org; domain=home.example.org" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?domain0040", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "DOMAIN0041", + "received": [ + "foo=bar; domain=.sibling.example.org" + ], + "sent-to": "http://sibling.example.org:8888/cookie-parser-result?domain0041", + "sent": [] + }, + { + "test": "DOMAIN0042", + "received": [ + "foo=bar; domain=.sibling.home.example.org" + ], + "sent-to": "http://sibling.home.example.org:8888/cookie-parser-result?domain0042", + "sent": [] + }, + { + "test": "MOZILLA0001", + "received": [ + "foo=bar; max-age=-1" + ], + "sent": [] + }, + { + "test": "MOZILLA0002", + "received": [ + "foo=bar; max-age=0" + ], + "sent": [] + }, + { + "test": "MOZILLA0003", + "received": [ + "foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT" + ], + "sent": [] + }, + { + "test": "MOZILLA0004", + "received": [ + "foo=bar; max-age=60" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "MOZILLA0005", + "received": [ + "foo=bar; max-age=-20" + ], + "sent": [] + }, + { + "test": "MOZILLA0006", + "received": [ + "foo=bar; max-age=60" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "MOZILLA0007", + "received": [ + "foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT" + ], + "sent": [] + }, + { + "test": "MOZILLA0008", + "received": [ + "foo=bar; max-age=60", + "foo1=bar; max-age=60" + ], + "sent": [ + { "name": "foo", "value": "bar" }, + { "name": "foo1", "value": "bar" } + ] + }, + { + "test": "MOZILLA0009", + "received": [ + "foo=bar; max-age=60", + "foo1=bar; max-age=60", + "foo=differentvalue; max-age=0" + ], + "sent": [ + { "name": "foo1", "value": "bar" } + ] + }, + { + "test": "MOZILLA0010", + "received": [ + "foo=bar; max-age=60", + "foo1=bar; max-age=60", + "foo=differentvalue; max-age=0", + "foo2=evendifferentvalue; max-age=0" + ], + "sent": [ + { "name": "foo1", "value": "bar" } + ] + }, + { + "test": "MOZILLA0011", + "received": [ + "test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! max-age=20;=;;" + ], + "sent": [] + }, + { + "test": "MOZILLA0012", + "received": [ + "test=\"fubar! = foo;bar\\\";\" parser; max-age=6", + "five; max-age=2.63," + ], + "sent": [ + { "name": "test", "value": "\"fubar! = foo" } + ] + }, + { + "test": "MOZILLA0013", + "received": [ + "test=kill; max-age=0", + "five; max-age=0" + ], + "sent": [] + }, + { + "test": "MOZILLA0014", + "received": [ + "six" + ], + "sent": [] + }, + { + "test": "MOZILLA0015", + "received": [ + "six", + "seven" + ], + "sent": [] + }, + { + "test": "MOZILLA0016", + "received": [ + "six", + "seven", + " =eight" + ], + "sent": [] + }, + { + "test": "MOZILLA0017", + "received": [ + "six", + "seven", + " =eight", + "test=six" + ], + "sent": [ + { "name": "test", "value": "six" } + ] + }, + { + "test": "NAME0001", + "received": [ + "a=bar" + ], + "sent": [ + { "name": "a", "value": "bar" } + ] + }, + { + "test": "NAME0002", + "received": [ + "1=bar" + ], + "sent": [ + { "name": "1", "value": "bar" } + ] + }, + { + "test": "NAME0003", + "received": [ + "$=bar" + ], + "sent": [ + { "name": "$", "value": "bar" } + ] + }, + { + "test": "NAME0004", + "received": [ + "!a=bar" + ], + "sent": [ + { "name": "!a", "value": "bar" } + ] + }, + { + "test": "NAME0005", + "received": [ + "@a=bar" + ], + "sent": [ + { "name": "@a", "value": "bar" } + ] + }, + { + "test": "NAME0006", + "received": [ + "#a=bar" + ], + "sent": [ + { "name": "#a", "value": "bar" } + ] + }, + { + "test": "NAME0007", + "received": [ + "$a=bar" + ], + "sent": [ + { "name": "$a", "value": "bar" } + ] + }, + { + "test": "NAME0008", + "received": [ + "%a=bar" + ], + "sent": [ + { "name": "%a", "value": "bar" } + ] + }, + { + "test": "NAME0009", + "received": [ + "^a=bar" + ], + "sent": [ + { "name": "^a", "value": "bar" } + ] + }, + { + "test": "NAME0010", + "received": [ + "&a=bar" + ], + "sent": [ + { "name": "&a", "value": "bar" } + ] + }, + { + "test": "NAME0011", + "received": [ + "*a=bar" + ], + "sent": [ + { "name": "*a", "value": "bar" } + ] + }, + { + "test": "NAME0012", + "received": [ + "(a=bar" + ], + "sent": [ + { "name": "(a", "value": "bar" } + ] + }, + { + "test": "NAME0013", + "received": [ + ")a=bar" + ], + "sent": [ + { "name": ")a", "value": "bar" } + ] + }, + { + "test": "NAME0014", + "received": [ + "-a=bar" + ], + "sent": [ + { "name": "-a", "value": "bar" } + ] + }, + { + "test": "NAME0015", + "received": [ + "_a=bar" + ], + "sent": [ + { "name": "_a", "value": "bar" } + ] + }, + { + "test": "NAME0016", + "received": [ + "+=bar" + ], + "sent": [ + { "name": "+", "value": "bar" } + ] + }, + { + "test": "NAME0017", + "received": [ + "=a=bar" + ], + "sent": [] + }, + { + "test": "NAME0018", + "received": [ + "a =bar" + ], + "sent": [ + { "name": "a", "value": "bar" } + ] + }, + { + "test": "NAME0019", + "received": [ + "\"a=bar" + ], + "sent": [ + { "name": "\"a", "value": "bar" } + ] + }, + { + "test": "NAME0020", + "received": [ + "\"a=b\"=bar" + ], + "sent": [ + { "name": "\"a", "value": "b\"=bar" } + ] + }, + { + "test": "NAME0021", + "received": [ + "\"a=b\"=bar", + "\"a=qux" + ], + "sent": [ + { "name": "\"a", "value": "qux" } + ] + }, + { + "test": "NAME0022", + "received": [ + " foo=bar" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "NAME0023", + "received": [ + "foo;bar=baz" + ], + "sent": [] + }, + { + "test": "NAME0024", + "received": [ + "$Version=1; foo=bar" + ], + "sent": [ + { "name": "$Version", "value": "1" } + ] + }, + { + "test": "NAME0025", + "received": [ + "===a=bar" + ], + "sent": [] + }, + { + "test": "NAME0026", + "received": [ + "foo=bar " + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "NAME0027", + "received": [ + "foo=bar ;" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "NAME0028", + "received": [ + "=a" + ], + "sent": [] + }, + { + "test": "NAME0029", + "received": [ + "=" + ], + "sent": [] + }, + { + "test": "NAME0030", + "received": [ + "foo bar=baz" + ], + "sent": [ + { "name": "foo bar", "value": "baz" } + ] + }, + { + "test": "NAME0031", + "received": [ + "\"foo;bar\"=baz" + ], + "sent": [] + }, + { + "test": "NAME0032", + "received": [ + "\"foo\\\"bar;baz\"=qux" + ], + "sent": [] + }, + { + "test": "NAME0033", + "received": [ + "=foo=bar", + "aaa" + ], + "sent": [] + }, + { + "test": "OPTIONAL_DOMAIN0030", + "received": [ + "foo=bar; domain=" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?optional-domain0030", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "OPTIONAL_DOMAIN0041", + "received": [ + "foo=bar; domain=example.org; domain=" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?optional-domain0041", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "OPTIONAL_DOMAIN0042", + "received": [ + "foo=bar; domain=foo.example.org; domain=" + ], + "sent-to": "http://home.example.org:8888/cookie-parser-result?optional-domain0042", + "sent": [] + }, + { + "test": "OPTIONAL_DOMAIN0043", + "received": [ + "foo=bar; domain=foo.example.org; domain=" + ], + "sent-to": "http://subdomain.home.example.org:8888/cookie-parser-result?optional-domain0043", + "sent": [] + }, + { + "test": "ORDERING0001", + "received": [ + "key=val0;", + "key=val1; path=/cookie-parser-result", + "key=val2; path=/", + "key=val3; path=/bar", + "key=val4; domain=.example.org", + "key=val5; domain=.example.org; path=/cookie-parser-result/foo" + ], + "sent-to": "/cookie-parser-result/foo/baz?ordering0001", + "sent": [ + { "name": "key", "value": "val5" }, + { "name": "key", "value": "val1" }, + { "name": "key", "value": "val2" }, + { "name": "key", "value": "val4" } + ] + }, + { + "test": "PATH0001", + "received": [ + "a=b; path=/", + "x=y; path=/cookie-parser-result" + ], + "sent": [ + { "name": "x", "value": "y" }, + { "name": "a", "value": "b" } + ] + }, + { + "test": "PATH0002", + "received": [ + "a=b; path=/cookie-parser-result", + "x=y; path=/" + ], + "sent": [ + { "name": "a", "value": "b" }, + { "name": "x", "value": "y" } + ] + }, + { + "test": "PATH0003", + "received": [ + "x=y; path=/", + "a=b; path=/cookie-parser-result" + ], + "sent": [ + { "name": "a", "value": "b" }, + { "name": "x", "value": "y" } + ] + }, + { + "test": "PATH0004", + "received": [ + "x=y; path=/cookie-parser-result", + "a=b; path=/" + ], + "sent": [ + { "name": "x", "value": "y" }, + { "name": "a", "value": "b" } + ] + }, + { + "test": "PATH0005", + "received": [ + "foo=bar; path=/cookie-parser-result/foo" + ], + "sent": [] + }, + { + "test": "PATH0006", + "received": [ + "foo=bar", + "foo=qux; path=/cookie-parser-result/foo" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0007", + "received": [ + "foo=bar; path=/cookie-parser-result/foo" + ], + "sent-to": "/cookie-parser-result/foo?path0007", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0008", + "received": [ + "foo=bar; path=/cookie-parser-result/foo" + ], + "sent-to": "/cookie-parser-result/bar?path0008", + "sent": [] + }, + { + "test": "PATH0009", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux" + ], + "sent-to": "/cookie-parser-result/foo?path0009", + "sent": [] + }, + { + "test": "PATH0010", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0010", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0011", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux" + ], + "sent-to": "/cookie-parser-result/bar/qux?path0011", + "sent": [] + }, + { + "test": "PATH0012", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux" + ], + "sent-to": "/cookie-parser-result/foo/baz?path0012", + "sent": [] + }, + { + "test": "PATH0013", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux/" + ], + "sent-to": "/cookie-parser-result/foo/baz?path0013", + "sent": [] + }, + { + "test": "PATH0014", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux/" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0014", + "sent": [] + }, + { + "test": "PATH0015", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux/" + ], + "sent-to": "/cookie-parser-result/foo/qux/?path0015", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0016", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0016", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0017", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/" + ], + "sent-to": "/cookie-parser-result/foo//qux?path0017", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0018", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/" + ], + "sent-to": "/cookie-parser-result/fooqux?path0018", + "sent": [] + }, + { + "test": "PATH0019", + "received": [ + "foo=bar; path" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0020", + "received": [ + "foo=bar; path=" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0021", + "received": [ + "foo=bar; path=/" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0022", + "received": [ + "foo=bar; path= /" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0023", + "received": [ + "foo=bar; Path=/cookie-PARSER-result" + ], + "sent": [] + }, + { + "test": "PATH0024", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux?" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0024", + "sent": [] + }, + { + "test": "PATH0025", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux#" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0025", + "sent": [] + }, + { + "test": "PATH0026", + "received": [ + "foo=bar; path=/cookie-parser-result/foo/qux;" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0026", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0027", + "received": [ + "foo=bar; path=\"/cookie-parser-result/foo/qux;\"" + ], + "sent-to": "/cookie-parser-result/foo/qux?path0027", + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0028", + "received": [ + "foo=bar; path=/cookie-parser-result/f%6Fo/bar" + ], + "sent-to": "/cookie-parser-result/foo/bar?path0028", + "sent": [] + }, + { + "test": "PATH0029", + "received": [ + "a=b; \tpath\t=\t/cookie-parser-result\t", + "x=y; \tpath\t=\t/book\t" + ], + "sent": [ + { "name": "a", "value": "b" } + ] + }, + { + "test": "PATH0030", + "received": [ + "foo=bar; path=/dog; path=" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "PATH0031", + "received": [ + "foo=bar; path=; path=/dog" + ], + "sent": [] + }, + { + "test": "PATH0032", + "received": [ + "foo=bar; path=/cookie-parser-result", + "foo=qux; path=/cookie-parser-result/" + ], + "sent-to": "/cookie-parser-result/dog?path0032", + "sent": [ + { "name": "foo", "value": "qux" }, + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "VALUE0001", + "received": [ + "foo= bar" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + }, + { + "test": "VALUE0002", + "received": [ + "foo=\"bar\"" + ], + "sent": [ + { "name": "foo", "value": "\"bar\"" } + ] + }, + { + "test": "VALUE0003", + "received": [ + "foo=\" bar \"" + ], + "sent": [ + { "name": "foo", "value": "\" bar \"" } + ] + }, + { + "test": "VALUE0004", + "received": [ + "foo=\"bar;baz\"" + ], + "sent": [ + { "name": "foo", "value": "\"bar" } + ] + }, + { + "test": "VALUE0005", + "received": [ + "foo=\"bar=baz\"" + ], + "sent": [ + { "name": "foo", "value": "\"bar=baz\"" } + ] + }, + { + "test": "VALUE0006", + "received": [ + "\tfoo\t=\tbar\t \t;\tttt" + ], + "sent": [ + { "name": "foo", "value": "bar" } + ] + } +] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_test.js new file mode 100644 index 0000000..fac2e3e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/ietf_test.js @@ -0,0 +1,106 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var fs = require('fs'); +var path = require('path'); +var url = require('url'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; +var CookieJar = tough.CookieJar; + +function readJson(filePath) { + filePath = path.join(__dirname, filePath); + return JSON.parse(fs.readFileSync(filePath).toString()); +} + +function setGetCookieVows() { + var theVows = {}; + var data = readJson('./ietf_data/parser.json'); + + data.forEach(function (testCase) { + theVows[testCase.test] = function () { + var jar = new CookieJar(); + var expected = testCase['sent'] + var sentFrom = 'http://home.example.org/cookie-parser?' + testCase.test; + var sentTo = testCase['sent-to'] ? + url.resolve('http://home.example.org', testCase['sent-to']) : + 'http://home.example.org/cookie-parser-result?' + testCase.test; + + testCase['received'].forEach(function (cookieStr) { + jar.setCookieSync(cookieStr, sentFrom, {ignoreError: true}); + }); + + var actual = jar.getCookiesSync(sentTo); + actual = actual.sort(tough.cookieCompare); + + assert.strictEqual(actual.length, expected.length); + + actual.forEach(function (actualCookie, idx) { + var expectedCookie = expected[idx]; + assert.strictEqual(actualCookie.key, expectedCookie.name); + assert.strictEqual(actualCookie.value, expectedCookie.value); + }); + }; + }); + + return {'Set/get cookie tests': theVows}; +} + +function dateVows() { + var theVows = {}; + + [ + './ietf_data/dates/bsd-examples.json', + './ietf_data/dates/examples.json' + ].forEach(function (filePath) { + var data = readJson(filePath); + var fileName = path.basename(filePath); + + data.forEach(function (testCase) { + theVows[fileName + ' : ' + testCase.test] = function () { + var actual = tough.parseDate(testCase.test); + actual = actual ? actual.toUTCString() : null; + assert.strictEqual(actual, testCase.expected); + }; + }); + }); + + return {'Date': theVows}; +} + +vows + .describe('IETF http state tests') + .addBatch(setGetCookieVows()) + .addBatch(dateVows()) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/lifetime_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/lifetime_test.js new file mode 100644 index 0000000..e66a22b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/lifetime_test.js @@ -0,0 +1,97 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; + +vows + .describe('Lifetime') + .addBatch({ + "TTL with max-age": function () { + var c = new Cookie(); + c.maxAge = 123; + assert.equal(c.TTL(), 123000); + assert.equal(c.expiryTime(new Date(9000000)), 9123000); + }, + "TTL with zero max-age": function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.maxAge = 0; // should be treated as "earliest representable" + assert.equal(c.TTL(), 0); + assert.equal(c.expiryTime(new Date(9000000)), -Infinity); + assert.ok(!c.validate()); // not valid, really: non-zero-digit *DIGIT + }, + "TTL with negative max-age": function () { + var c = new Cookie(); + c.key = 'a'; + c.value = 'b'; + c.maxAge = -1; // should be treated as "earliest representable" + assert.equal(c.TTL(), 0); + assert.equal(c.expiryTime(new Date(9000000)), -Infinity); + assert.ok(!c.validate()); // not valid, really: non-zero-digit *DIGIT + }, + "TTL with max-age and expires": function () { + var c = new Cookie(); + c.maxAge = 123; + c.expires = new Date(Date.now() + 9000); + assert.equal(c.TTL(), 123000); + assert.ok(c.isPersistent()); + }, + "TTL with expires": function () { + var c = new Cookie(); + var now = Date.now(); + c.expires = new Date(now + 9000); + assert.equal(c.TTL(now), 9000); + assert.equal(c.expiryTime(), c.expires.getTime()); + }, + "TTL with old expires": function () { + var c = new Cookie(); + c.setExpires('17 Oct 2010 00:00:00 GMT'); + assert.ok(c.TTL() < 0); + assert.ok(c.isPersistent()); + }, + "default TTL": { + topic: function () { + return new Cookie(); + }, + "is Infinite-future": function (c) { + assert.equal(c.TTL(), Infinity) + }, + "is a 'session' cookie": function (c) { + assert.ok(!c.isPersistent()) + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/parsing_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/parsing_test.js new file mode 100644 index 0000000..cb37c63 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/parsing_test.js @@ -0,0 +1,294 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; + +vows + .describe('Parsing') + .addBatch({ + "simple": { + topic: function() { + return Cookie.parse('a=bcd') || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'bcd') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) } + }, + "with expiry": { + topic: function() { + return Cookie.parse('a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT') || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'bcd') }, + "has expires": function(c) { + assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be'); + assert.equal(c.expires.getTime(), 1318921503000); + } + }, + "with expiry and path": { + topic: function() { + return Cookie.parse('abc="xyzzy!"; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Path=/aBc') || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'abc') }, + "value": function(c) { assert.equal(c.value, '"xyzzy!"') }, + "has expires": function(c) { + assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be'); + assert.equal(c.expires.getTime(), 1318921503000); + }, + "has path": function(c) { assert.equal(c.path, '/aBc'); }, + "no httponly or secure": function(c) { + assert.ok(!c.httpOnly); + assert.ok(!c.secure); + } + }, + "with everything": { + topic: function() { + return Cookie.parse('abc="xyzzy!"; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Path=/aBc; Domain=example.com; Secure; HTTPOnly; Max-Age=1234; Foo=Bar; Baz') || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'abc') }, + "value": function(c) { assert.equal(c.value, '"xyzzy!"') }, + "has expires": function(c) { + assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be'); + assert.equal(c.expires.getTime(), 1318921503000); + }, + "has path": function(c) { assert.equal(c.path, '/aBc'); }, + "has domain": function(c) { assert.equal(c.domain, 'example.com'); }, + "has httponly": function(c) { assert.equal(c.httpOnly, true); }, + "has secure": function(c) { assert.equal(c.secure, true); }, + "has max-age": function(c) { assert.equal(c.maxAge, 1234); }, + "has extensions": function(c) { + assert.ok(c.extensions); + assert.equal(c.extensions[0], 'Foo=Bar'); + assert.equal(c.extensions[1], 'Baz'); + } + }, + "invalid expires": function() { + var c = Cookie.parse("a=b; Expires=xyzzy"); + assert.ok(c); + assert.equal(c.expires, Infinity); + }, + "zero max-age": function() { + var c = Cookie.parse("a=b; Max-Age=0"); + assert.ok(c); + assert.equal(c.maxAge, 0); + }, + "negative max-age": function() { + var c = Cookie.parse("a=b; Max-Age=-1"); + assert.ok(c); + assert.equal(c.maxAge, -1); + }, + "empty domain": function() { + var c = Cookie.parse("a=b; domain="); + assert.ok(c); + assert.equal(c.domain, null); + }, + "dot domain": function() { + var c = Cookie.parse("a=b; domain=."); + assert.ok(c); + assert.equal(c.domain, null); + }, + "uppercase domain": function() { + var c = Cookie.parse("a=b; domain=EXAMPLE.COM"); + assert.ok(c); + assert.equal(c.domain, 'example.com'); + }, + "trailing dot in domain": { + topic: function() { + return Cookie.parse("a=b; Domain=example.com.", true) || null; + }, + "has the domain": function(c) { assert.equal(c.domain,"example.com.") }, + "but doesn't validate": function(c) { assert.equal(c.validate(),false) } + }, + "empty path": function() { + var c = Cookie.parse("a=b; path="); + assert.ok(c); + assert.equal(c.path, null); + }, + "no-slash path": function() { + var c = Cookie.parse("a=b; path=xyzzy"); + assert.ok(c); + assert.equal(c.path, null); + }, + "trailing semi-colons after path": { + topic: function () { + return [ + "a=b; path=/;", + "c=d;;;;" + ]; + }, + "strips semi-colons": function (t) { + var c1 = Cookie.parse(t[0]); + var c2 = Cookie.parse(t[1]); + assert.ok(c1); + assert.ok(c2); + assert.equal(c1.path, '/'); + } + }, + "secure-with-value": function() { + var c = Cookie.parse("a=b; Secure=xyzzy"); + assert.ok(c); + assert.equal(c.secure, true); + }, + "httponly-with-value": function() { + var c = Cookie.parse("a=b; HttpOnly=xyzzy"); + assert.ok(c); + assert.equal(c.httpOnly, true); + }, + "garbage": { + topic: function() { + return Cookie.parse("\x08", true) || null; + }, + "doesn't parse": function(c) { assert.equal(c,null) } + }, + "public suffix domain": { + topic: function() { + return Cookie.parse("a=b; domain=kyoto.jp", true) || null; + }, + "parses fine": function(c) { + assert.ok(c); + assert.equal(c.domain, 'kyoto.jp'); + }, + "but fails validation": function(c) { + assert.ok(c); + assert.ok(!c.validate()); + } + }, + "public suffix foonet.net": { + "top level": { + topic: function() { + return Cookie.parse("a=b; domain=foonet.net") || null; + }, + "parses and is valid": function(c) { + assert.ok(c); + assert.equal(c.domain, 'foonet.net'); + assert.ok(c.validate()); + } + }, + "www": { + topic: function() { + return Cookie.parse("a=b; domain=www.foonet.net") || null; + }, + "parses and is valid": function(c) { + assert.ok(c); + assert.equal(c.domain, 'www.foonet.net'); + assert.ok(c.validate()); + } + }, + "with a dot": { + topic: function() { + return Cookie.parse("a=b; domain=.foonet.net") || null; + }, + "parses and is valid": function(c) { + assert.ok(c); + assert.equal(c.domain, 'foonet.net'); + assert.ok(c.validate()); + } + } + }, + "Ironically, Google 'GAPS' cookie has very little whitespace": { + topic: function() { + return Cookie.parse("GAPS=1:A1aaaaAaAAa1aaAaAaaAAAaaa1a11a:aaaAaAaAa-aaaA1-;Path=/;Expires=Thu, 17-Apr-2014 02:12:29 GMT;Secure;HttpOnly"); + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'GAPS') }, + "value": function(c) { assert.equal(c.value, '1:A1aaaaAaAAa1aaAaAaaAAAaaa1a11a:aaaAaAaAa-aaaA1-') }, + "path": function(c) { + assert.notEqual(c.path, '/;Expires'); // BUG + assert.equal(c.path, '/'); + }, + "expires": function(c) { + assert.notEqual(c.expires, Infinity); + assert.equal(c.expires.getTime(), 1397700749000); + }, + "secure": function(c) { assert.ok(c.secure) }, + "httponly": function(c) { assert.ok(c.httpOnly) } + }, + "lots of equal signs": { + topic: function() { + return Cookie.parse("queryPref=b=c&d=e; Path=/f=g; Expires=Thu, 17 Apr 2014 02:12:29 GMT; HttpOnly"); + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'queryPref') }, + "value": function(c) { assert.equal(c.value, 'b=c&d=e') }, + "path": function(c) { + assert.equal(c.path, '/f=g'); + }, + "expires": function(c) { + assert.notEqual(c.expires, Infinity); + assert.equal(c.expires.getTime(), 1397700749000); + }, + "httponly": function(c) { assert.ok(c.httpOnly) } + }, + "spaces in value": { + topic: function() { + return Cookie.parse('a=one two three',false) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, 'one two three') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) } + }, + "quoted spaces in value": { + topic: function() { + return Cookie.parse('a="one two three"',false) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'a') }, + "value": function(c) { assert.equal(c.value, '"one two three"') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) } + }, + "non-ASCII in value": { + topic: function() { + return Cookie.parse('farbe=weiß',false) || null; + }, + "parsed": function(c) { assert.ok(c) }, + "key": function(c) { assert.equal(c.key, 'farbe') }, + "value": function(c) { assert.equal(c.value, 'weiß') }, + "no path": function(c) { assert.equal(c.path, null) }, + "no domain": function(c) { assert.equal(c.domain, null) }, + "no extensions": function(c) { assert.ok(!c.extensions) } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/regression_test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/regression_test.js new file mode 100644 index 0000000..4edb609 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tough-cookie/test/regression_test.js @@ -0,0 +1,143 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +'use strict'; +var vows = require('vows'); +var assert = require('assert'); +var async = require('async'); +var tough = require('../lib/cookie'); +var Cookie = tough.Cookie; +var CookieJar = tough.CookieJar; + +var atNow = Date.now(); + +function at(offset) { + return {now: new Date(atNow + offset)}; +} + +vows + .describe('Regression tests') + .addBatch({ + "Issue 1": { + topic: function () { + var cj = new CookieJar(); + cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function (err, cookie) { + this.callback(err, {cj: cj, cookie: cookie}); + }.bind(this)); + }, + "stored a cookie": function (t) { + assert.ok(t.cookie); + }, + "getting it back": { + topic: function (t) { + t.cj.getCookies('http://domain/some/path/file', function (err, cookies) { + this.callback(err, {cj: t.cj, cookies: cookies || []}); + }.bind(this)); + }, + "got one cookie": function (t) { + assert.lengthOf(t.cookies, 1); + }, + "it's the right one": function (t) { + var c = t.cookies[0]; + assert.equal(c.key, 'hello'); + assert.equal(c.value, 'world'); + } + } + } + }) + .addBatch({ + "trailing semi-colon set into cj": { + topic: function () { + var cb = this.callback; + var cj = new CookieJar(); + var ex = 'http://www.example.com'; + var tasks = []; + tasks.push(function (next) { + cj.setCookie('broken_path=testme; path=/;', ex, at(-1), next); + }); + tasks.push(function (next) { + cj.setCookie('b=2; Path=/;;;;', ex, at(-1), next); + }); + async.parallel(tasks, function (err, cookies) { + cb(null, { + cj: cj, + cookies: cookies + }); + }); + }, + "check number of cookies": function (t) { + assert.lengthOf(t.cookies, 2, "didn't set"); + }, + "check *broken_path* was set properly": function (t) { + assert.equal(t.cookies[0].key, "broken_path"); + assert.equal(t.cookies[0].value, "testme"); + assert.equal(t.cookies[0].path, "/"); + }, + "check *b* was set properly": function (t) { + assert.equal(t.cookies[1].key, "b"); + assert.equal(t.cookies[1].value, "2"); + assert.equal(t.cookies[1].path, "/"); + }, + "retrieve the cookie": { + topic: function (t) { + var cb = this.callback; + t.cj.getCookies('http://www.example.com', {}, function (err, cookies) { + t.cookies = cookies; + cb(err, t); + }); + }, + "get the cookie": function (t) { + assert.lengthOf(t.cookies, 2); + assert.equal(t.cookies[0].key, 'broken_path'); + assert.equal(t.cookies[0].value, 'testme'); + assert.equal(t.cookies[1].key, "b"); + assert.equal(t.cookies[1].value, "2"); + assert.equal(t.cookies[1].path, "/"); + } + } + } + }) + .addBatch({ + "tough-cookie throws exception on malformed URI (GH-32)": { + topic: function () { + var url = "http://www.example.com/?test=100%"; + var cj = new CookieJar(); + + cj.setCookieSync("Test=Test", url); + + return cj.getCookieStringSync(url); + }, + "cookies are set": function (cookieStr) { + assert.strictEqual(cookieStr, "Test=Test"); + } + } + }) + .export(module); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/.jshintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/.jshintrc new file mode 100644 index 0000000..4c1c8d4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/.jshintrc @@ -0,0 +1,5 @@ +{ + "node": true, + "asi": true, + "laxcomma": true +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/LICENSE @@ -0,0 +1,55 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/README.md new file mode 100644 index 0000000..bb533d5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/README.md @@ -0,0 +1,4 @@ +tunnel-agent +============ + +HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/index.js new file mode 100644 index 0000000..13c0427 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/index.js @@ -0,0 +1,236 @@ +'use strict' + +var net = require('net') + , tls = require('tls') + , http = require('http') + , https = require('https') + , events = require('events') + , assert = require('assert') + , util = require('util') + ; + +exports.httpOverHttp = httpOverHttp +exports.httpsOverHttp = httpsOverHttp +exports.httpOverHttps = httpOverHttps +exports.httpsOverHttps = httpsOverHttps + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options) + agent.request = http.request + return agent +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options) + agent.request = http.request + agent.createSocket = createSecureSocket + return agent +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options) + agent.request = https.request + return agent +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options) + agent.request = https.request + agent.createSocket = createSecureSocket + return agent +} + + +function TunnelingAgent(options) { + var self = this + self.options = options || {} + self.proxyOptions = self.options.proxy || {} + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets + self.requests = [] + self.sockets = [] + + self.on('free', function onFree(socket, host, port) { + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i] + if (pending.host === host && pending.port === port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1) + pending.request.onSocket(socket) + return + } + } + socket.destroy() + self.removeSocket(socket) + }) +} +util.inherits(TunnelingAgent, events.EventEmitter) + +TunnelingAgent.prototype.addRequest = function addRequest(req, options) { + var self = this + + // Legacy API: addRequest(req, host, port, path) + if (typeof options === 'string') { + options = { + host: options, + port: arguments[2], + path: arguments[3] + }; + } + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push({host: host, port: port, request: req}) + return + } + + // If we are under maxSockets create a new one. + self.createSocket({host: options.host, port: options.port, request: req}, function(socket) { + socket.on('free', onFree) + socket.on('close', onCloseOrRemove) + socket.on('agentRemove', onCloseOrRemove) + req.onSocket(socket) + + function onFree() { + self.emit('free', socket, options.host, options.port) + } + + function onCloseOrRemove(err) { + self.removeSocket() + socket.removeListener('free', onFree) + socket.removeListener('close', onCloseOrRemove) + socket.removeListener('agentRemove', onCloseOrRemove) + } + }) +} + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this + var placeholder = {} + self.sockets.push(placeholder) + + var connectOptions = mergeOptions({}, self.proxyOptions, + { method: 'CONNECT' + , path: options.host + ':' + options.port + , agent: false + } + ) + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {} + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64') + } + + debug('making CONNECT request') + var connectReq = self.request(connectOptions) + connectReq.useChunkedEncodingByDefault = false // for v0.6 + connectReq.once('response', onResponse) // for v0.6 + connectReq.once('upgrade', onUpgrade) // for v0.6 + connectReq.once('connect', onConnect) // for v0.7 or later + connectReq.once('error', onError) + connectReq.end() + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head) + }) + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners() + socket.removeAllListeners() + + if (res.statusCode === 200) { + assert.equal(head.length, 0) + debug('tunneling connection has established') + self.sockets[self.sockets.indexOf(placeholder)] = socket + cb(socket) + } else { + debug('tunneling socket could not be established, statusCode=%d', res.statusCode) + var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode) + error.code = 'ECONNRESET' + options.request.emit('error', error) + self.removeSocket(placeholder) + } + } + + function onError(cause) { + connectReq.removeAllListeners() + + debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack) + var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message) + error.code = 'ECONNRESET' + options.request.emit('error', error) + self.removeSocket(placeholder) + } +} + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) return + + this.sockets.splice(pos, 1) + + var pending = this.requests.shift() + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket) + }) + } +} + +function createSecureSocket(options, cb) { + var self = this + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, mergeOptions({}, self.options, + { servername: options.host + , socket: socket + } + )) + cb(secureSocket) + }) +} + + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i] + if (typeof overrides === 'object') { + var keys = Object.keys(overrides) + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j] + if (overrides[k] !== undefined) { + target[k] = overrides[k] + } + } + } + } + return target +} + + +var debug +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments) + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0] + } else { + args.unshift('TUNNEL:') + } + console.error.apply(console, args) + } +} else { + debug = function() {} +} +exports.debug = debug // for test diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/package.json new file mode 100644 index 0000000..e2bc2f0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/node_modules/tunnel-agent/package.json @@ -0,0 +1,30 @@ +{ + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "name": "tunnel-agent", + "description": "HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.", + "version": "0.4.0", + "repository": { + "url": "git+https://github.com/mikeal/tunnel-agent.git" + }, + "main": "index.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "readme": "tunnel-agent\n============\n\nHTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mikeal/tunnel-agent/issues" + }, + "homepage": "https://github.com/mikeal/tunnel-agent#readme", + "_id": "tunnel-agent@0.4.0", + "_shasum": "b1184e312ffbcf70b3b4c78e8c219de7ebb1c550", + "_resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.4.0.tgz", + "_from": "tunnel-agent@>=0.4.0 <0.5.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/package.json new file mode 100644 index 0000000..9854d10 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/package.json @@ -0,0 +1,107 @@ +{ + "name": "request", + "description": "Simplified HTTP request client.", + "tags": [ + "http", + "simple", + "util", + "utility" + ], + "version": "2.57.0", + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/request/request.git" + }, + "bugs": { + "url": "http://github.com/request/request/issues" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + }, + "main": "index.js", + "dependencies": { + "bl": "~0.9.0", + "caseless": "~0.10.0", + "forever-agent": "~0.6.0", + "form-data": "~0.2.0", + "json-stringify-safe": "~5.0.0", + "mime-types": "~2.0.1", + "node-uuid": "~1.4.0", + "qs": "~3.1.0", + "tunnel-agent": "~0.4.0", + "tough-cookie": ">=0.12.0", + "http-signature": "~0.11.0", + "oauth-sign": "~0.8.0", + "hawk": "~2.3.0", + "aws-sign2": "~0.5.0", + "stringstream": "~0.0.4", + "combined-stream": "~1.0.1", + "isstream": "~0.1.1", + "har-validator": "^1.6.1" + }, + "scripts": { + "test": "npm run lint && node node_modules/.bin/taper tests/test-*.js && npm run test-browser", + "test-browser": "node tests/browser/start.js", + "lint": "node node_modules/.bin/eslint lib/ *.js tests/ && echo Lint passed." + }, + "devDependencies": { + "browserify": "~5.9.1", + "browserify-istanbul": "~0.1.3", + "buffer-equal": "0.0.1", + "coveralls": "~2.11.2", + "eslint": "0.18.0", + "function-bind": "~1.0.0", + "istanbul": "~0.3.2", + "karma": "~0.12.21", + "karma-browserify": "~3.0.1", + "karma-cli": "0.0.4", + "karma-coverage": "0.2.6", + "karma-phantomjs-launcher": "~0.1.4", + "karma-tap": "~1.0.1", + "rimraf": "~2.2.8", + "server-destroy": "~1.0.0", + "tape": "~3.0.0", + "taper": "~0.4.0", + "bluebird": "~2.9.21" + }, + "gitHead": "1fafe0dc387e5efa9ae95b40aa80c43e83e1b98f", + "homepage": "https://github.com/request/request#readme", + "_id": "request@2.57.0", + "_shasum": "d445105a42d009b9d724289633b449a6d723d989", + "_from": "request@>=2.0.0 <3.0.0", + "_npmVersion": "2.10.1", + "_nodeVersion": "0.12.4", + "_npmUser": { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + }, + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "nylen", + "email": "jnylen@gmail.com" + }, + { + "name": "fredkschott", + "email": "fkschott@gmail.com" + }, + { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + } + ], + "dist": { + "shasum": "d445105a42d009b9d724289633b449a6d723d989", + "tarball": "http://registry.npmjs.org/request/-/request-2.57.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/request/-/request-2.57.0.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/release.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/release.sh new file mode 100755 index 0000000..7678bf8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/release.sh @@ -0,0 +1,45 @@ +#!/bin/sh + +if [ -z "`which github-changes`" ]; then + # specify version because github-changes "is under heavy development. Things + # may break between releases" until 0.1.0 + echo "First, do: [sudo] npm install -g github-changes@0.0.14" + exit 1 +fi + +if [ -d .git/refs/remotes/upstream ]; then + remote=upstream +else + remote=origin +fi + +# Increment v2.x.y -> v2.x+1.0 +npm version minor || exit 1 + +# Generate changelog from pull requests +github-changes -o request -r request \ + --auth --verbose \ + --file CHANGELOG.md \ + --only-pulls --use-commit-body \ + --date-format '(YYYY/MM/DD)' \ + || exit 1 + +# Since the tag for the new version hasn't been pushed yet, any changes in it +# will be marked as "upcoming" +version="$(grep '"version"' package.json | cut -d'"' -f4)" +sed -i -e "s/^### upcoming/### v$version/" CHANGELOG.md + +# This may fail if no changelog updates +# TODO: would this ever actually happen? handle it better? +git add CHANGELOG.md; git commit -m 'Update changelog' + +# Publish the new version to npm +npm publish || exit 1 + +# Increment v2.x.0 -> v2.x.1 +# For rationale, see: +# https://github.com/request/oauth-sign/issues/10#issuecomment-58917018 +npm version patch || exit 1 + +# Push back to the main repo +git push $remote master --tags || exit 1 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/request.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/request.js new file mode 100644 index 0000000..21b4f52 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/request/request.js @@ -0,0 +1,1556 @@ +'use strict' + +var http = require('http') + , https = require('https') + , url = require('url') + , util = require('util') + , stream = require('stream') + , zlib = require('zlib') + , helpers = require('./lib/helpers') + , bl = require('bl') + , hawk = require('hawk') + , aws = require('aws-sign2') + , httpSignature = require('http-signature') + , mime = require('mime-types') + , tunnel = require('tunnel-agent') + , stringstream = require('stringstream') + , caseless = require('caseless') + , ForeverAgent = require('forever-agent') + , FormData = require('form-data') + , cookies = require('./lib/cookies') + , copy = require('./lib/copy') + , getProxyFromURI = require('./lib/getProxyFromURI') + , Querystring = require('./lib/querystring').Querystring + , Har = require('./lib/har').Har + , Auth = require('./lib/auth').Auth + , OAuth = require('./lib/oauth').OAuth + , Multipart = require('./lib/multipart').Multipart + , Redirect = require('./lib/redirect').Redirect + +var safeStringify = helpers.safeStringify + , isReadStream = helpers.isReadStream + , toBase64 = helpers.toBase64 + , defer = helpers.defer + , globalCookieJar = cookies.jar() + + +var globalPool = {} + +var defaultProxyHeaderWhiteList = [ + 'accept', + 'accept-charset', + 'accept-encoding', + 'accept-language', + 'accept-ranges', + 'cache-control', + 'content-encoding', + 'content-language', + 'content-length', + 'content-location', + 'content-md5', + 'content-range', + 'content-type', + 'connection', + 'date', + 'expect', + 'max-forwards', + 'pragma', + 'referer', + 'te', + 'transfer-encoding', + 'user-agent', + 'via' +] + +var defaultProxyHeaderExclusiveList = [ + 'proxy-authorization' +] + +function filterForNonReserved(reserved, options) { + // Filter out properties that are not reserved. + // Reserved values are passed in at call site. + + var object = {} + for (var i in options) { + var notReserved = (reserved.indexOf(i) === -1) + if (notReserved) { + object[i] = options[i] + } + } + return object +} + +function filterOutReservedFunctions(reserved, options) { + // Filter out properties that are functions and are reserved. + // Reserved values are passed in at call site. + + var object = {} + for (var i in options) { + var isReserved = !(reserved.indexOf(i) === -1) + var isFunction = (typeof options[i] === 'function') + if (!(isReserved && isFunction)) { + object[i] = options[i] + } + } + return object + +} + +function constructProxyHost(uriObject) { + var port = uriObject.portA + , protocol = uriObject.protocol + , proxyHost = uriObject.hostname + ':' + + if (port) { + proxyHost += port + } else if (protocol === 'https:') { + proxyHost += '443' + } else { + proxyHost += '80' + } + + return proxyHost +} + +function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) { + var whiteList = proxyHeaderWhiteList + .reduce(function (set, header) { + set[header.toLowerCase()] = true + return set + }, {}) + + return Object.keys(headers) + .filter(function (header) { + return whiteList[header.toLowerCase()] + }) + .reduce(function (set, header) { + set[header] = headers[header] + return set + }, {}) +} + +function getTunnelOption(self, options) { + // Tunnel HTTPS by default, or if a previous request in the redirect chain + // was tunneled. Allow the user to override this setting. + + // If self.tunnel is already set (because this is a redirect), use the + // existing value. + if (typeof self.tunnel !== 'undefined') { + return self.tunnel + } + + // If options.tunnel is set (the user specified a value), use it. + if (typeof options.tunnel !== 'undefined') { + return options.tunnel + } + + // If the destination is HTTPS, tunnel. + if (self.uri.protocol === 'https:') { + return true + } + + // Otherwise, leave tunnel unset, because if a later request in the redirect + // chain is HTTPS then that request (and any subsequent ones) should be + // tunneled. + return undefined +} + +function constructTunnelOptions(request) { + var proxy = request.proxy + + var tunnelOptions = { + proxy : { + host : proxy.hostname, + port : +proxy.port, + proxyAuth : proxy.auth, + headers : request.proxyHeaders + }, + headers : request.headers, + ca : request.ca, + cert : request.cert, + key : request.key, + passphrase : request.passphrase, + pfx : request.pfx, + ciphers : request.ciphers, + rejectUnauthorized : request.rejectUnauthorized, + secureOptions : request.secureOptions, + secureProtocol : request.secureProtocol + } + + return tunnelOptions +} + +function constructTunnelFnName(uri, proxy) { + var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http') + var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http') + return [uriProtocol, proxyProtocol].join('Over') +} + +function getTunnelFn(request) { + var uri = request.uri + var proxy = request.proxy + var tunnelFnName = constructTunnelFnName(uri, proxy) + return tunnel[tunnelFnName] +} + +// Function for properly handling a connection error +function connectionErrorHandler(error) { + var socket = this + if (socket.res) { + if (socket.res.request) { + socket.res.request.emit('error', error) + } else { + socket.res.emit('error', error) + } + } else { + socket._httpMessage.emit('error', error) + } +} + +// Return a simpler request object to allow serialization +function requestToJSON() { + var self = this + return { + uri: self.uri, + method: self.method, + headers: self.headers + } +} + +// Return a simpler response object to allow serialization +function responseToJSON() { + var self = this + return { + statusCode: self.statusCode, + body: self.body, + headers: self.headers, + request: requestToJSON.call(self.request) + } +} + +function Request (options) { + // if given the method property in options, set property explicitMethod to true + + // extend the Request instance with any non-reserved properties + // remove any reserved functions from the options object + // set Request instance to be readable and writable + // call init + + var self = this + + // start with HAR, then override with additional options + if (options.har) { + self._har = new Har(self) + options = self._har.options(options) + } + + stream.Stream.call(self) + var reserved = Object.keys(Request.prototype) + var nonReserved = filterForNonReserved(reserved, options) + + stream.Stream.call(self) + util._extend(self, nonReserved) + options = filterOutReservedFunctions(reserved, options) + + self.readable = true + self.writable = true + if (options.method) { + self.explicitMethod = true + } + self._qs = new Querystring(self) + self._auth = new Auth(self) + self._oauth = new OAuth(self) + self._multipart = new Multipart(self) + self._redirect = new Redirect(self) + self.init(options) +} + +util.inherits(Request, stream.Stream) + +// Debugging +Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) +function debug() { + if (Request.debug) { + console.error('REQUEST %s', util.format.apply(util, arguments)) + } +} +Request.prototype.debug = debug + +Request.prototype.setupTunnel = function () { + var self = this + + if (typeof self.proxy === 'string') { + self.proxy = url.parse(self.proxy) + } + + if (!self.proxy || !self.tunnel) { + return false + } + + // Setup Proxy Header Exclusive List and White List + self.proxyHeaderExclusiveList = self.proxyHeaderExclusiveList || [] + self.proxyHeaderWhiteList = self.proxyHeaderWhiteList || defaultProxyHeaderWhiteList + var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList) + var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList) + + // Setup Proxy Headers and Proxy Headers Host + // Only send the Proxy White Listed Header names + self.proxyHeaders = constructProxyHeaderWhiteList(self.headers, proxyHeaderWhiteList) + self.proxyHeaders.host = constructProxyHost(self.uri) + proxyHeaderExclusiveList.forEach(self.removeHeader, self) + + // Set Agent from Tunnel Data + var tunnelFn = getTunnelFn(self) + var tunnelOptions = constructTunnelOptions(self) + self.agent = tunnelFn(tunnelOptions) + + return true +} + +Request.prototype.init = function (options) { + // init() contains all the code to setup the request object. + // the actual outgoing request is not started until start() is called + // this function is called from both the constructor and on redirect. + var self = this + if (!options) { + options = {} + } + self.headers = self.headers ? copy(self.headers) : {} + + // Delete headers with value undefined since they break + // ClientRequest.OutgoingMessage.setHeader in node 0.12 + for (var headerName in self.headers) { + if (typeof self.headers[headerName] === 'undefined') { + delete self.headers[headerName] + } + } + + caseless.httpify(self, self.headers) + + if (!self.method) { + self.method = options.method || 'GET' + } + if (!self.localAddress) { + self.localAddress = options.localAddress + } + + self._qs.init(options) + + debug(options) + if (!self.pool && self.pool !== false) { + self.pool = globalPool + } + self.dests = self.dests || [] + self.__isRequestRequest = true + + // Protect against double callback + if (!self._callback && self.callback) { + self._callback = self.callback + self.callback = function () { + if (self._callbackCalled) { + return // Print a warning maybe? + } + self._callbackCalled = true + self._callback.apply(self, arguments) + } + self.on('error', self.callback.bind()) + self.on('complete', self.callback.bind(self, null)) + } + + // People use this property instead all the time, so support it + if (!self.uri && self.url) { + self.uri = self.url + delete self.url + } + + // If there's a baseUrl, then use it as the base URL (i.e. uri must be + // specified as a relative path and is appended to baseUrl). + if (self.baseUrl) { + if (typeof self.baseUrl !== 'string') { + return self.emit('error', new Error('options.baseUrl must be a string')) + } + + if (typeof self.uri !== 'string') { + return self.emit('error', new Error('options.uri must be a string when using options.baseUrl')) + } + + if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) { + return self.emit('error', new Error('options.uri must be a path when using options.baseUrl')) + } + + // Handle all cases to make sure that there's only one slash between + // baseUrl and uri. + var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1 + var uriStartsWithSlash = self.uri.indexOf('/') === 0 + + if (baseUrlEndsWithSlash && uriStartsWithSlash) { + self.uri = self.baseUrl + self.uri.slice(1) + } else if (baseUrlEndsWithSlash || uriStartsWithSlash) { + self.uri = self.baseUrl + self.uri + } else if (self.uri === '') { + self.uri = self.baseUrl + } else { + self.uri = self.baseUrl + '/' + self.uri + } + delete self.baseUrl + } + + // A URI is needed by this point, emit error if we haven't been able to get one + if (!self.uri) { + return self.emit('error', new Error('options.uri is a required argument')) + } + + // If a string URI/URL was given, parse it into a URL object + if (typeof self.uri === 'string') { + self.uri = url.parse(self.uri) + } + + // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme + if (self.uri.protocol === 'unix:') { + return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`')) + } + + // Support Unix Sockets + if (self.uri.host === 'unix') { + // Get the socket & request paths from the URL + var unixParts = self.uri.path.split(':') + , host = unixParts[0] + , path = unixParts[1] + // Apply unix properties to request + self.socketPath = host + self.uri.pathname = path + self.uri.path = path + self.uri.host = host + self.uri.hostname = host + self.uri.isUnix = true + } + + if (self.strictSSL === false) { + self.rejectUnauthorized = false + } + + if (!self.uri.pathname) {self.uri.pathname = '/'} + + if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { + // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar + // Detect and reject it as soon as possible + var faultyUri = url.format(self.uri) + var message = 'Invalid URI "' + faultyUri + '"' + if (Object.keys(options).length === 0) { + // No option ? This can be the sign of a redirect + // As this is a case where the user cannot do anything (they didn't call request directly with this URL) + // they should be warned that it can be caused by a redirection (can save some hair) + message += '. This can be caused by a crappy redirection.' + } + // This error was fatal + return self.emit('error', new Error(message)) + } + + if (!self.hasOwnProperty('proxy')) { + self.proxy = getProxyFromURI(self.uri) + } + + self.tunnel = getTunnelOption(self, options) + if (self.proxy) { + self.setupTunnel() + } + + self._redirect.onRequest(options) + + self.setHost = false + if (!self.hasHeader('host')) { + var hostHeaderName = self.originalHostHeaderName || 'host' + self.setHeader(hostHeaderName, self.uri.hostname) + if (self.uri.port) { + if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') && + !(self.uri.port === 443 && self.uri.protocol === 'https:') ) { + self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) ) + } + } + self.setHost = true + } + + self.jar(self._jar || options.jar) + + if (!self.uri.port) { + if (self.uri.protocol === 'http:') {self.uri.port = 80} + else if (self.uri.protocol === 'https:') {self.uri.port = 443} + } + + if (self.proxy && !self.tunnel) { + self.port = self.proxy.port + self.host = self.proxy.hostname + } else { + self.port = self.uri.port + self.host = self.uri.hostname + } + + if (options.form) { + self.form(options.form) + } + + if (options.formData) { + var formData = options.formData + var requestForm = self.form() + var appendFormValue = function (key, value) { + if (value.hasOwnProperty('value') && value.hasOwnProperty('options')) { + requestForm.append(key, value.value, value.options) + } else { + requestForm.append(key, value) + } + } + for (var formKey in formData) { + if (formData.hasOwnProperty(formKey)) { + var formValue = formData[formKey] + if (formValue instanceof Array) { + for (var j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]) + } + } else { + appendFormValue(formKey, formValue) + } + } + } + } + + if (options.qs) { + self.qs(options.qs) + } + + if (self.uri.path) { + self.path = self.uri.path + } else { + self.path = self.uri.pathname + (self.uri.search || '') + } + + if (self.path.length === 0) { + self.path = '/' + } + + // Auth must happen last in case signing is dependent on other headers + if (options.aws) { + self.aws(options.aws) + } + + if (options.hawk) { + self.hawk(options.hawk) + } + + if (options.httpSignature) { + self.httpSignature(options.httpSignature) + } + + if (options.auth) { + if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) { + options.auth.user = options.auth.username + } + if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) { + options.auth.pass = options.auth.password + } + + self.auth( + options.auth.user, + options.auth.pass, + options.auth.sendImmediately, + options.auth.bearer + ) + } + + if (self.gzip && !self.hasHeader('accept-encoding')) { + self.setHeader('accept-encoding', 'gzip') + } + + if (self.uri.auth && !self.hasHeader('authorization')) { + var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)}) + self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) + } + + if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { + var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)}) + var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) + self.setHeader('proxy-authorization', authHeader) + } + + if (self.proxy && !self.tunnel) { + self.path = (self.uri.protocol + '//' + self.uri.host + self.path) + } + + if (options.json) { + self.json(options.json) + } + if (options.multipart) { + self.multipart(options.multipart) + } + + if (options.time) { + self.timing = true + self.elapsedTime = self.elapsedTime || 0 + } + + if (self.body) { + var length = 0 + if (!Buffer.isBuffer(self.body)) { + if (Array.isArray(self.body)) { + for (var i = 0; i < self.body.length; i++) { + length += self.body[i].length + } + } else { + self.body = new Buffer(self.body) + length = self.body.length + } + } else { + length = self.body.length + } + if (length) { + if (!self.hasHeader('content-length')) { + self.setHeader('content-length', length) + } + } else { + self.emit('error', new Error('Argument error, options.body.')) + } + } + + if (options.oauth) { + self.oauth(options.oauth) + } else if (self._oauth.params && self.hasHeader('authorization')) { + self.oauth(self._oauth.params) + } + + var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol + , defaultModules = {'http:':http, 'https:':https} + , httpModules = self.httpModules || {} + + self.httpModule = httpModules[protocol] || defaultModules[protocol] + + if (!self.httpModule) { + return self.emit('error', new Error('Invalid protocol: ' + protocol)) + } + + if (options.ca) { + self.ca = options.ca + } + + if (!self.agent) { + if (options.agentOptions) { + self.agentOptions = options.agentOptions + } + + if (options.agentClass) { + self.agentClass = options.agentClass + } else if (options.forever) { + self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL + } else { + self.agentClass = self.httpModule.Agent + } + } + + if (self.pool === false) { + self.agent = false + } else { + self.agent = self.agent || self.getNewAgent() + } + + self.on('pipe', function (src) { + if (self.ntick && self._started) { + self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.')) + } + self.src = src + if (isReadStream(src)) { + if (!self.hasHeader('content-type')) { + self.setHeader('content-type', mime.lookup(src.path)) + } + } else { + if (src.headers) { + for (var i in src.headers) { + if (!self.hasHeader(i)) { + self.setHeader(i, src.headers[i]) + } + } + } + if (self._json && !self.hasHeader('content-type')) { + self.setHeader('content-type', 'application/json') + } + if (src.method && !self.explicitMethod) { + self.method = src.method + } + } + + // self.on('pipe', function () { + // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') + // }) + }) + + defer(function () { + if (self._aborted) { + return + } + + var end = function () { + if (self._form) { + if (!self._auth.hasAuth) { + self._form.pipe(self) + } + else if (self._auth.hasAuth && self._auth.sentAuth) { + self._form.pipe(self) + } + } + if (self._multipart && self._multipart.chunked) { + self._multipart.body.pipe(self) + } + if (self.body) { + if (Array.isArray(self.body)) { + self.body.forEach(function (part) { + self.write(part) + }) + } else { + self.write(self.body) + } + self.end() + } else if (self.requestBodyStream) { + console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.') + self.requestBodyStream.pipe(self) + } else if (!self.src) { + if (self._auth.hasAuth && !self._auth.sentAuth) { + self.end() + return + } + if (self.method !== 'GET' && typeof self.method !== 'undefined') { + self.setHeader('content-length', 0) + } + self.end() + } + } + + if (self._form && !self.hasHeader('content-length')) { + // Before ending the request, we had to compute the length of the whole form, asyncly + self.setHeader(self._form.getHeaders()) + self._form.getLength(function (err, length) { + if (!err) { + self.setHeader('content-length', length) + } + end() + }) + } else { + end() + } + + self.ntick = true + }) + +} + +// Must call this when following a redirect from https to http or vice versa +// Attempts to keep everything as identical as possible, but update the +// httpModule, Tunneling agent, and/or Forever Agent in use. +Request.prototype._updateProtocol = function () { + var self = this + var protocol = self.uri.protocol + + if (protocol === 'https:' || self.tunnel) { + // previously was doing http, now doing https + // if it's https, then we might need to tunnel now. + if (self.proxy) { + if (self.setupTunnel()) { + return + } + } + + self.httpModule = https + switch (self.agentClass) { + case ForeverAgent: + self.agentClass = ForeverAgent.SSL + break + case http.Agent: + self.agentClass = https.Agent + break + default: + // nothing we can do. Just hope for the best. + return + } + + // if there's an agent, we need to get a new one. + if (self.agent) { + self.agent = self.getNewAgent() + } + + } else { + // previously was doing https, now doing http + self.httpModule = http + switch (self.agentClass) { + case ForeverAgent.SSL: + self.agentClass = ForeverAgent + break + case https.Agent: + self.agentClass = http.Agent + break + default: + // nothing we can do. just hope for the best + return + } + + // if there's an agent, then get a new one. + if (self.agent) { + self.agent = null + self.agent = self.getNewAgent() + } + } +} + +Request.prototype.getNewAgent = function () { + var self = this + var Agent = self.agentClass + var options = {} + if (self.agentOptions) { + for (var i in self.agentOptions) { + options[i] = self.agentOptions[i] + } + } + if (self.ca) { + options.ca = self.ca + } + if (self.ciphers) { + options.ciphers = self.ciphers + } + if (self.secureProtocol) { + options.secureProtocol = self.secureProtocol + } + if (self.secureOptions) { + options.secureOptions = self.secureOptions + } + if (typeof self.rejectUnauthorized !== 'undefined') { + options.rejectUnauthorized = self.rejectUnauthorized + } + + if (self.cert && self.key) { + options.key = self.key + options.cert = self.cert + } + + if (self.pfx) { + options.pfx = self.pfx + } + + if (self.passphrase) { + options.passphrase = self.passphrase + } + + var poolKey = '' + + // different types of agents are in different pools + if (Agent !== self.httpModule.Agent) { + poolKey += Agent.name + } + + // ca option is only relevant if proxy or destination are https + var proxy = self.proxy + if (typeof proxy === 'string') { + proxy = url.parse(proxy) + } + var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' + + if (isHttps) { + if (options.ca) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.ca + } + + if (typeof options.rejectUnauthorized !== 'undefined') { + if (poolKey) { + poolKey += ':' + } + poolKey += options.rejectUnauthorized + } + + if (options.cert) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.cert.toString('ascii') + options.key.toString('ascii') + } + + if (options.pfx) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.pfx.toString('ascii') + } + + if (options.ciphers) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.ciphers + } + + if (options.secureProtocol) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.secureProtocol + } + + if (options.secureOptions) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.secureOptions + } + } + + if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) { + // not doing anything special. Use the globalAgent + return self.httpModule.globalAgent + } + + // we're using a stored agent. Make sure it's protocol-specific + poolKey = self.uri.protocol + poolKey + + // generate a new agent for this setting if none yet exists + if (!self.pool[poolKey]) { + self.pool[poolKey] = new Agent(options) + // properly set maxSockets on new agents + if (self.pool.maxSockets) { + self.pool[poolKey].maxSockets = self.pool.maxSockets + } + } + + return self.pool[poolKey] +} + +Request.prototype.start = function () { + // start() is called once we are ready to send the outgoing HTTP request. + // this is usually called on the first write(), end() or on nextTick() + var self = this + + if (self._aborted) { + return + } + + self._started = true + self.method = self.method || 'GET' + self.href = self.uri.href + + if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { + self.setHeader('content-length', self.src.stat.size) + } + if (self._aws) { + self.aws(self._aws, true) + } + + // We have a method named auth, which is completely different from the http.request + // auth option. If we don't remove it, we're gonna have a bad time. + var reqOptions = copy(self) + delete reqOptions.auth + + debug('make request', self.uri.href) + + self.req = self.httpModule.request(reqOptions) + + if (self.timing) { + self.startTime = new Date().getTime() + } + + if (self.timeout && !self.timeoutTimer) { + var timeout = self.timeout < 0 ? 0 : self.timeout + self.timeoutTimer = setTimeout(function () { + self.abort() + var e = new Error('ETIMEDOUT') + e.code = 'ETIMEDOUT' + self.emit('error', e) + }, timeout) + + // Set additional timeout on socket - in case if remote + // server freeze after sending headers + if (self.req.setTimeout) { // only works on node 0.6+ + self.req.setTimeout(timeout, function () { + if (self.req) { + self.req.abort() + var e = new Error('ESOCKETTIMEDOUT') + e.code = 'ESOCKETTIMEDOUT' + self.emit('error', e) + } + }) + } + } + + self.req.on('response', self.onRequestResponse.bind(self)) + self.req.on('error', self.onRequestError.bind(self)) + self.req.on('drain', function() { + self.emit('drain') + }) + self.req.on('socket', function(socket) { + self.emit('socket', socket) + }) + + self.on('end', function() { + if ( self.req.connection ) { + self.req.connection.removeListener('error', connectionErrorHandler) + } + }) + self.emit('request', self.req) +} + +Request.prototype.onRequestError = function (error) { + var self = this + if (self._aborted) { + return + } + if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' + && self.agent.addRequestNoreuse) { + self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } + self.start() + self.req.end() + return + } + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + self.emit('error', error) +} + +Request.prototype.onRequestResponse = function (response) { + var self = this + debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) + response.on('end', function() { + if (self.timing) { + self.elapsedTime += (new Date().getTime() - self.startTime) + debug('elapsed time', self.elapsedTime) + response.elapsedTime = self.elapsedTime + } + debug('response end', self.uri.href, response.statusCode, response.headers) + }) + + // The check on response.connection is a workaround for browserify. + if (response.connection && response.connection.listeners('error').indexOf(connectionErrorHandler) === -1) { + response.connection.setMaxListeners(0) + response.connection.once('error', connectionErrorHandler) + } + if (self._aborted) { + debug('aborted', self.uri.href) + response.resume() + return + } + + self.response = response + response.request = self + response.toJSON = responseToJSON + + // XXX This is different on 0.10, because SSL is strict by default + if (self.httpModule === https && + self.strictSSL && (!response.hasOwnProperty('socket') || + !response.socket.authorized)) { + debug('strict ssl error', self.uri.href) + var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' + self.emit('error', new Error('SSL Error: ' + sslErr)) + return + } + + // Save the original host before any redirect (if it changes, we need to + // remove any authorization headers). Also remember the case of the header + // name because lots of broken servers expect Host instead of host and we + // want the caller to be able to specify this. + self.originalHost = self.getHeader('host') + if (!self.originalHostHeaderName) { + self.originalHostHeaderName = self.hasHeader('host') + } + if (self.setHost) { + self.removeHeader('host') + } + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + + var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar + var addCookie = function (cookie) { + //set the cookie if it's domain in the href's domain. + try { + targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) + } catch (e) { + self.emit('error', e) + } + } + + response.caseless = caseless(response.headers) + + if (response.caseless.has('set-cookie') && (!self._disableCookies)) { + var headerName = response.caseless.has('set-cookie') + if (Array.isArray(response.headers[headerName])) { + response.headers[headerName].forEach(addCookie) + } else { + addCookie(response.headers[headerName]) + } + } + + if (self._redirect.onResponse(response)) { + return // Ignore the rest of the response + } else { + // Be a good stream and emit end when the response is finished. + // Hack to emit end on close because of a core bug that never fires end + response.on('close', function () { + if (!self._ended) { + self.response.emit('end') + } + }) + + response.on('end', function () { + self._ended = true + }) + + var responseContent + if (self.gzip) { + var contentEncoding = response.headers['content-encoding'] || 'identity' + contentEncoding = contentEncoding.trim().toLowerCase() + + if (contentEncoding === 'gzip') { + responseContent = zlib.createGunzip() + response.pipe(responseContent) + } else { + // Since previous versions didn't check for Content-Encoding header, + // ignore any invalid values to preserve backwards-compatibility + if (contentEncoding !== 'identity') { + debug('ignoring unrecognized Content-Encoding ' + contentEncoding) + } + responseContent = response + } + } else { + responseContent = response + } + + if (self.encoding) { + if (self.dests.length !== 0) { + console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') + } else if (responseContent.setEncoding) { + responseContent.setEncoding(self.encoding) + } else { + // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with + // zlib streams. + // If/When support for 0.9.4 is dropped, this should be unnecessary. + responseContent = responseContent.pipe(stringstream(self.encoding)) + } + } + + if (self._paused) { + responseContent.pause() + } + + self.responseContent = responseContent + + self.emit('response', response) + + self.dests.forEach(function (dest) { + self.pipeDest(dest) + }) + + responseContent.on('data', function (chunk) { + self._destdata = true + self.emit('data', chunk) + }) + responseContent.on('end', function (chunk) { + self.emit('end', chunk) + }) + responseContent.on('error', function (error) { + self.emit('error', error) + }) + responseContent.on('close', function () {self.emit('close')}) + + if (self.callback) { + var buffer = bl() + , strings = [] + + self.on('data', function (chunk) { + if (Buffer.isBuffer(chunk)) { + buffer.append(chunk) + } else { + strings.push(chunk) + } + }) + self.on('end', function () { + debug('end event', self.uri.href) + if (self._aborted) { + debug('aborted', self.uri.href) + return + } + + if (buffer.length) { + debug('has body', self.uri.href, buffer.length) + if (self.encoding === null) { + // response.body = buffer + // can't move to this until https://github.com/rvagg/bl/issues/13 + response.body = buffer.slice() + } else { + response.body = buffer.toString(self.encoding) + } + } else if (strings.length) { + // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. + // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). + if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') { + strings[0] = strings[0].substring(1) + } + response.body = strings.join('') + } + + if (self._json) { + try { + response.body = JSON.parse(response.body, self._jsonReviver) + } catch (e) { + // empty + } + } + debug('emitting complete', self.uri.href) + if (typeof response.body === 'undefined' && !self._json) { + response.body = self.encoding === null ? new Buffer(0) : '' + } + self.emit('complete', response, response.body) + }) + } + //if no callback + else { + self.on('end', function () { + if (self._aborted) { + debug('aborted', self.uri.href) + return + } + self.emit('complete', response) + }) + } + } + debug('finish init function', self.uri.href) +} + +Request.prototype.abort = function () { + var self = this + self._aborted = true + + if (self.req) { + self.req.abort() + } + else if (self.response) { + self.response.abort() + } + + self.emit('abort') +} + +Request.prototype.pipeDest = function (dest) { + var self = this + var response = self.response + // Called after the response is received + if (dest.headers && !dest.headersSent) { + if (response.caseless.has('content-type')) { + var ctname = response.caseless.has('content-type') + if (dest.setHeader) { + dest.setHeader(ctname, response.headers[ctname]) + } + else { + dest.headers[ctname] = response.headers[ctname] + } + } + + if (response.caseless.has('content-length')) { + var clname = response.caseless.has('content-length') + if (dest.setHeader) { + dest.setHeader(clname, response.headers[clname]) + } else { + dest.headers[clname] = response.headers[clname] + } + } + } + if (dest.setHeader && !dest.headersSent) { + for (var i in response.headers) { + // If the response content is being decoded, the Content-Encoding header + // of the response doesn't represent the piped content, so don't pass it. + if (!self.gzip || i !== 'content-encoding') { + dest.setHeader(i, response.headers[i]) + } + } + dest.statusCode = response.statusCode + } + if (self.pipefilter) { + self.pipefilter(response, dest) + } +} + +Request.prototype.qs = function (q, clobber) { + var self = this + var base + if (!clobber && self.uri.query) { + base = self._qs.parse(self.uri.query) + } else { + base = {} + } + + for (var i in q) { + base[i] = q[i] + } + + if (self._qs.stringify(base) === '') { + return self + } + + var qs = self._qs.stringify(base) + + self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs) + self.url = self.uri + self.path = self.uri.path + + return self +} +Request.prototype.form = function (form) { + var self = this + if (form) { + self.setHeader('content-type', 'application/x-www-form-urlencoded') + self.body = (typeof form === 'string') + ? self._qs.rfc3986(form.toString('utf8')) + : self._qs.stringify(form).toString('utf8') + return self + } + // create form-data object + self._form = new FormData() + self._form.on('error', function(err) { + err.message = 'form-data: ' + err.message + self.emit('error', err) + self.abort() + }) + return self._form +} +Request.prototype.multipart = function (multipart) { + var self = this + + self._multipart.onRequest(multipart) + + if (!self._multipart.chunked) { + self.body = self._multipart.body + } + + return self +} +Request.prototype.json = function (val) { + var self = this + + if (!self.hasHeader('accept')) { + self.setHeader('accept', 'application/json') + } + + self._json = true + if (typeof val === 'boolean') { + if (self.body !== undefined) { + if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { + self.body = safeStringify(self.body) + } else { + self.body = self._qs.rfc3986(self.body) + } + if (!self.hasHeader('content-type')) { + self.setHeader('content-type', 'application/json') + } + } + } else { + self.body = safeStringify(val) + if (!self.hasHeader('content-type')) { + self.setHeader('content-type', 'application/json') + } + } + + if (typeof self.jsonReviver === 'function') { + self._jsonReviver = self.jsonReviver + } + + return self +} +Request.prototype.getHeader = function (name, headers) { + var self = this + var result, re, match + if (!headers) { + headers = self.headers + } + Object.keys(headers).forEach(function (key) { + if (key.length !== name.length) { + return + } + re = new RegExp(name, 'i') + match = key.match(re) + if (match) { + result = headers[key] + } + }) + return result +} + +Request.prototype.auth = function (user, pass, sendImmediately, bearer) { + var self = this + + self._auth.onRequest(user, pass, sendImmediately, bearer) + + return self +} +Request.prototype.aws = function (opts, now) { + var self = this + + if (!now) { + self._aws = opts + return self + } + var date = new Date() + self.setHeader('date', date.toUTCString()) + var auth = + { key: opts.key + , secret: opts.secret + , verb: self.method.toUpperCase() + , date: date + , contentType: self.getHeader('content-type') || '' + , md5: self.getHeader('content-md5') || '' + , amazonHeaders: aws.canonicalizeHeaders(self.headers) + } + var path = self.uri.path + if (opts.bucket && path) { + auth.resource = '/' + opts.bucket + path + } else if (opts.bucket && !path) { + auth.resource = '/' + opts.bucket + } else if (!opts.bucket && path) { + auth.resource = path + } else if (!opts.bucket && !path) { + auth.resource = '/' + } + auth.resource = aws.canonicalizeResource(auth.resource) + self.setHeader('authorization', aws.authorization(auth)) + + return self +} +Request.prototype.httpSignature = function (opts) { + var self = this + httpSignature.signRequest({ + getHeader: function(header) { + return self.getHeader(header, self.headers) + }, + setHeader: function(header, value) { + self.setHeader(header, value) + }, + method: self.method, + path: self.path + }, opts) + debug('httpSignature authorization', self.getHeader('authorization')) + + return self +} +Request.prototype.hawk = function (opts) { + var self = this + self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field) +} +Request.prototype.oauth = function (_oauth) { + var self = this + + self._oauth.onRequest(_oauth) + + return self +} + +Request.prototype.jar = function (jar) { + var self = this + var cookies + + if (self._redirect.redirectsFollowed === 0) { + self.originalCookieHeader = self.getHeader('cookie') + } + + if (!jar) { + // disable cookies + cookies = false + self._disableCookies = true + } else { + var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar + var urihref = self.uri.href + //fetch cookie in the Specified host + if (targetCookieJar) { + cookies = targetCookieJar.getCookieString(urihref) + } + } + + //if need cookie and cookie is not empty + if (cookies && cookies.length) { + if (self.originalCookieHeader) { + // Don't overwrite existing Cookie header + self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies) + } else { + self.setHeader('cookie', cookies) + } + } + self._jar = jar + return self +} + + +// Stream API +Request.prototype.pipe = function (dest, opts) { + var self = this + + if (self.response) { + if (self._destdata) { + self.emit('error', new Error('You cannot pipe after data has been emitted from the response.')) + } else if (self._ended) { + self.emit('error', new Error('You cannot pipe after the response has been ended.')) + } else { + stream.Stream.prototype.pipe.call(self, dest, opts) + self.pipeDest(dest) + return dest + } + } else { + self.dests.push(dest) + stream.Stream.prototype.pipe.call(self, dest, opts) + return dest + } +} +Request.prototype.write = function () { + var self = this + if (!self._started) { + self.start() + } + return self.req.write.apply(self.req, arguments) +} +Request.prototype.end = function (chunk) { + var self = this + if (chunk) { + self.write(chunk) + } + if (!self._started) { + self.start() + } + self.req.end() +} +Request.prototype.pause = function () { + var self = this + if (!self.responseContent) { + self._paused = true + } else { + self.responseContent.pause.apply(self.responseContent, arguments) + } +} +Request.prototype.resume = function () { + var self = this + if (!self.responseContent) { + self._paused = false + } else { + self.responseContent.resume.apply(self.responseContent, arguments) + } +} +Request.prototype.destroy = function () { + var self = this + if (!self._ended) { + self.end() + } else if (self.response) { + self.response.destroy() + } +} + +Request.defaultProxyHeaderWhiteList = + defaultProxyHeaderWhiteList.slice() + +Request.defaultProxyHeaderExclusiveList = + defaultProxyHeaderExclusiveList.slice() + +// Exports + +Request.prototype.toJSON = requestToJSON +module.exports = Request diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/README.md new file mode 100644 index 0000000..58e7ac3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/README.md @@ -0,0 +1,36 @@ +The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, callback)` + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of + `opts.maxBusyTries` times before giving up, adding 100ms of wait + between each attempt. The default `maxBusyTries` is 3. +* `ENOENT` - If the file doesn't exist, rimraf will return + successfully, since your desired outcome is already the case. +* `EMFILE` - Since `readdir` requires opening a file descriptor, it's + possible to hit `EMFILE` if too many file descriptors are in use. + In the sync case, there's nothing to be done for this. But in the + async case, rimraf will gradually back off with timeouts up to + `opts.emfileWait` ms, which defaults to 1000. + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. + +## CLI + +If installed with `npm install rimraf -g` it can be used as a global +command `rimraf ` which is useful for cross platform support. + +## mkdirp + +If you need to create a directory recursively, check out +[mkdirp](https://github.com/substack/node-mkdirp). diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/bin.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/bin.js new file mode 100755 index 0000000..29bfa8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/bin.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var rimraf = require('./') + +var help = false +var dashdash = false +var args = process.argv.slice(2).filter(function(arg) { + if (dashdash) + return !!arg + else if (arg === '--') + dashdash = true + else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/)) + help = true + else + return !!arg +}); + +if (help || args.length === 0) { + // If they didn't ask for help, then this is not a "success" + var log = help ? console.log : console.error + log('Usage: rimraf ') + log('') + log(' Deletes all files and folders at "path" recursively.') + log('') + log('Options:') + log('') + log(' -h, --help Display this usage info') + process.exit(help ? 0 : 1) +} else { + args.forEach(function(arg) { + rimraf.sync(arg) + }) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/README.md new file mode 100644 index 0000000..258257e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/README.md @@ -0,0 +1,369 @@ +[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Dependency Status](https://david-dm.org/isaacs/node-glob.svg)](https://david-dm.org/isaacs/node-glob) [![devDependency Status](https://david-dm.org/isaacs/node-glob/dev-status.svg)](https://david-dm.org/isaacs/node-glob#info=devDependencies) [![optionalDependency Status](https://david-dm.org/isaacs/node-glob/optional-status.svg)](https://david-dm.org/isaacs/node-glob#info=optionalDependencies) + +# Glob + +Match files using the patterns the shell uses, like stars and stuff. + +This is a glob implementation in JavaScript. It uses the `minimatch` +library to do its matching. + +![](oh-my-glob.gif) + +## Usage + +```javascript +var glob = require("glob") + +// options is optional +glob("**/*.js", options, function (er, files) { + // files is an array of filenames. + // If the `nonull` option is set, and nothing + // was found, then files is ["**/*.js"] + // er is an error object or null. +}) +``` + +## Glob Primer + +"Globs" are the patterns you type when you do stuff like `ls *.js` on +the command line, or put `build/*` in a `.gitignore` file. + +Before parsing the path part patterns, braced sections are expanded +into a set. Braced sections start with `{` and end with `}`, with any +number of comma-delimited sections within. Braced sections may contain +slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in a +path portion: + +* `*` Matches 0 or more characters in a single path portion +* `?` Matches 1 character +* `[...]` Matches a range of characters, similar to a RegExp range. + If the first character of the range is `!` or `^` then it matches + any character not in the range. +* `!(pattern|pattern|pattern)` Matches anything that does not match + any of the patterns provided. +* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the + patterns provided. +* `+(pattern|pattern|pattern)` Matches one or more occurrences of the + patterns provided. +* `*(a|b|c)` Matches zero or more occurrences of the patterns provided +* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided +* `**` If a "globstar" is alone in a path portion, then it matches + zero or more directories and subdirectories searching for matches. + It does not crawl symlinked directories. + +### Dots + +If a file or directory path portion has a `.` as the first character, +then it will not match any glob pattern unless that pattern's +corresponding path part also has a `.` as its first character. + +For example, the pattern `a/.*/c` would match the file at `a/.b/c`. +However the pattern `a/*/c` would not, because `*` does not start with +a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has no +slashes in it, then it will seek for any file anywhere in the tree +with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Negation + +The intent for negation would be for a pattern starting with `!` to +match everything that *doesn't* match the supplied pattern. However, +the implementation is weird, and for the time being, this should be +avoided. The behavior will change or be deprecated in version 5. + +### Empty Sets + +If no matching files are found, then an empty array is returned. This +differs from the shell, where the pattern itself is returned. For +example: + + $ echo a*s*d*f + a*s*d*f + +To get the bash-style behavior, set the `nonull:true` in the options. + +### See Also: + +* `man sh` +* `man bash` (Search for "Pattern Matching") +* `man 3 fnmatch` +* `man 5 gitignore` +* [minimatch documentation](https://github.com/isaacs/minimatch) + +## glob.hasMagic(pattern, [options]) + +Returns `true` if there are any special characters in the pattern, and +`false` otherwise. + +Note that the options affect the results. If `noext:true` is set in +the options object, then `+(a|b)` will not be considered a magic +pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` +then that is considered magical, unless `nobrace:true` is set in the +options. + +## glob(pattern, [options], cb) + +* `pattern` {String} Pattern to be matched +* `options` {Object} +* `cb` {Function} + * `err` {Error | null} + * `matches` {Array} filenames found matching the pattern + +Perform an asynchronous glob search. + +## glob.sync(pattern, [options]) + +* `pattern` {String} Pattern to be matched +* `options` {Object} +* return: {Array} filenames found matching the pattern + +Perform a synchronous glob search. + +## Class: glob.Glob + +Create a Glob object by instantiating the `glob.Glob` class. + +```javascript +var Glob = require("glob").Glob +var mg = new Glob(pattern, options, cb) +``` + +It's an EventEmitter, and starts walking the filesystem to find matches +immediately. + +### new glob.Glob(pattern, [options], [cb]) + +* `pattern` {String} pattern to search for +* `options` {Object} +* `cb` {Function} Called when an error occurs, or matches are found + * `err` {Error | null} + * `matches` {Array} filenames found matching the pattern + +Note that if the `sync` flag is set in the options, then matches will +be immediately available on the `g.found` member. + +### Properties + +* `minimatch` The minimatch object that the glob uses. +* `options` The options object passed in. +* `aborted` Boolean which is set to true when calling `abort()`. There + is no way at this time to continue a glob search after aborting, but + you can re-use the statCache to avoid having to duplicate syscalls. +* `statCache` Collection of all the stat results the glob search + performed. +* `cache` Convenience object. Each field has the following possible + values: + * `false` - Path does not exist + * `true` - Path exists + * `'DIR'` - Path exists, and is not a directory + * `'FILE'` - Path exists, and is a directory + * `[file, entries, ...]` - Path exists, is a directory, and the + array value is the results of `fs.readdir` +* `statCache` Cache of `fs.stat` results, to prevent statting the same + path multiple times. +* `symlinks` A record of which paths are symbolic links, which is + relevant in resolving `**` patterns. +* `realpathCache` An optional object which is passed to `fs.realpath` + to minimize unnecessary syscalls. It is stored on the instantiated + Glob object, and may be re-used. + +### Events + +* `end` When the matching is finished, this is emitted with all the + matches found. If the `nonull` option is set, and no match was found, + then the `matches` list contains the original pattern. The matches + are sorted, unless the `nosort` flag is set. +* `match` Every time a match is found, this is emitted with the matched. +* `error` Emitted when an unexpected error is encountered, or whenever + any fs error occurs if `options.strict` is set. +* `abort` When `abort()` is called, this event is raised. + +### Methods + +* `pause` Temporarily stop the search +* `resume` Resume the search +* `abort` Stop the search forever + +### Options + +All the options that can be passed to Minimatch can also be passed to +Glob to change pattern matching behavior. Also, some have been added, +or have glob-specific ramifications. + +All options are false by default, unless otherwise noted. + +All options are added to the Glob object, as well. + +If you are running many `glob` operations, you can pass a Glob object +as the `options` argument to a subsequent operation to shortcut some +`stat` and `readdir` calls. At the very least, you may pass in shared +`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that +parallel glob operations will be sped up by sharing information about +the filesystem. + +* `cwd` The current working directory in which to search. Defaults + to `process.cwd()`. +* `root` The place where patterns starting with `/` will be mounted + onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix + systems, and `C:\` or some such on Windows.) +* `dot` Include `.dot` files in normal matches and `globstar` matches. + Note that an explicit dot in a portion of the pattern will always + match dot files. +* `nomount` By default, a pattern starting with a forward-slash will be + "mounted" onto the root setting, so that a valid filesystem path is + returned. Set this flag to disable that behavior. +* `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. +* `nosort` Don't sort the results. +* `stat` Set to true to stat *all* results. This reduces performance + somewhat, and is completely unnecessary, unless `readdir` is presumed + to be an untrustworthy indicator of file existence. +* `silent` When an unusual error is encountered when attempting to + read a directory, a warning will be printed to stderr. Set the + `silent` option to true to suppress these warnings. +* `strict` When an unusual error is encountered when attempting to + read a directory, the process will just continue on in search of + other matches. Set the `strict` option to raise an error in these + cases. +* `cache` See `cache` property above. Pass in a previously generated + cache object to save some fs calls. +* `statCache` A cache of results of filesystem information, to prevent + unnecessary stat calls. While it should not normally be necessary + to set this, you may pass the statCache from one glob() call to the + options object of another, if you know that the filesystem will not + change between calls. (See "Race Conditions" below.) +* `symlinks` A cache of known symbolic links. You may pass in a + previously generated `symlinks` object to save `lstat` calls when + resolving `**` matches. +* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. +* `nounique` In some cases, brace-expanded patterns can result in the + same file showing up multiple times in the result set. By default, + this implementation prevents duplicates in the result set. Set this + flag to disable that behavior. +* `nonull` Set to never return an empty set, instead returning a set + containing the pattern itself. This is the default in glob(3). +* `debug` Set to enable debug logging in minimatch and glob. +* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. +* `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) +* `noext` Do not match `+(a|b)` "extglob" patterns. +* `nocase` Perform a case-insensitive match. Note: on + case-insensitive filesystems, non-magic patterns will match by + default, since `stat` and `readdir` will not raise errors. +* `matchBase` Perform a basename-only match if the pattern does not + contain any slash characters. That is, `*.js` would be treated as + equivalent to `**/*.js`, matching all js files in all directories. +* `nonegate` Suppress `negate` behavior. (See below.) +* `nocomment` Suppress `comment` behavior. (See below.) +* `nonull` Return the pattern when no matches are found. +* `nodir` Do not match directories, only files. (Note: to match + *only* directories, simply put a `/` at the end of the pattern.) +* `ignore` Add a pattern or an array of patterns to exclude matches. +* `follow` Follow symlinked directories when expanding `**` patterns. + Note that this can result in a lot of duplicate references in the + presence of cyclic links. +* `realpath` Set to true to call `fs.realpath` on all of the results. + In the case of a symlink that cannot be resolved, the full absolute + path to the matched entry is returned (though it will usually be a + broken symlink) + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between node-glob and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.3, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +Note that symlinked directories are not crawled as part of a `**`, +though their contents may match against subsequent portions of the +pattern. This prevents infinite loops and duplicates and the like. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then glob returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will always +be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto the +root setting using `path.join`. On windows, this will by default result +in `/foo/*` matching `C:\foo\bar.txt`. + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race conditions, +since it relies on directory walking and such. + +As a result, it is possible that a file that exists when glob looks for +it may have been deleted or modified by the time it returns the result. + +As part of its internal implementation, this program caches all stat +and readdir calls that it makes, in order to cut down on system +overhead. However, this also makes it even more susceptible to races, +especially if the cache or statCache objects are reused between glob +calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast majority +of operations, this is never a problem. + +## Contributing + +Any change to behavior (including bugfixes) must come with a test. + +Patches that fail tests or reduce performance will be rejected. + +``` +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# to benchmark against bash/zsh +npm run bench + +# to profile javascript +npm run prof +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/common.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/common.js new file mode 100644 index 0000000..cd7c824 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/common.js @@ -0,0 +1,237 @@ +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.isAbsolute = process.platform === "win32" ? absWin : absUnix +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var path = require("path") +var minimatch = require("minimatch") +var Minimatch = minimatch.Minimatch + +function absWin (p) { + if (absUnix(p)) return true + // pull off the device/UNC bit from a windows path. + // from node's lib/path.js + var splitDeviceRe = + /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/ + var result = splitDeviceRe.exec(p) + var device = result[1] || '' + var isUnc = device && device.charAt(1) !== ':' + var isAbsolute = !!result[2] || isUnc // UNC paths are always absolute + + return isAbsolute +} + +function absUnix (p) { + return p.charAt(0) === "/" || p === "" +} + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { nonegate: true }) + } + + return { + matcher: new Minimatch(pattern, { nonegate: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = options.cwd + self.changedCwd = path.resolve(options.cwd) !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + self.nomount = !!options.nomount + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + return !(/\/$/.test(e)) + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (exports.isAbsolute(f)) { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else if (self.realpath) { + abs = path.resolve(f) + } + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/glob.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/glob.js new file mode 100644 index 0000000..eac0693 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/glob.js @@ -0,0 +1,740 @@ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var fs = require('fs') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var globSync = require('./sync.js') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var isAbsolute = common.isAbsolute +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +glob.hasMagic = function (pattern, options_) { + var options = util._extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + var n = this.minimatch.set.length + this._processing = 0 + this.matches = new Array(n) + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + + function done () { + --self._processing + if (self._processing <= 0) + self._finish() + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + fs.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (this.matches[index][e]) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = this._makeAbs(e) + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + if (this.mark) + e = this._mark(e) + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er) + return cb() + + var isSym = lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTDIR': // totally normal. means it *does* exist. + this.cache[this._makeAbs(f)] = 'FILE' + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) return this.emit('error', er) + if (!this.silent) console.error('glob error', er) + break + } + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && !stat.isDirectory()) + return cb(null, false, stat) + + var c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c !== 'DIR') + return cb() + + return cb(null, c, stat) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/.eslintrc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/.eslintrc new file mode 100644 index 0000000..b7a1550 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/.eslintrc @@ -0,0 +1,17 @@ +{ + "env" : { + "node" : true + }, + "rules" : { + "semi": [2, "never"], + "strict": 0, + "quotes": [1, "single", "avoid-escape"], + "no-use-before-define": 0, + "curly": 0, + "no-underscore-dangle": 0, + "no-lonely-if": 1, + "no-unused-vars": [2, {"vars" : "all", "args" : "after-used"}], + "no-mixed-requires": 0, + "space-infix-ops": 0 + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/README.md new file mode 100644 index 0000000..6dc8929 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/README.md @@ -0,0 +1,37 @@ +# inflight + +Add callbacks to requests in flight to avoid async duplication + +## USAGE + +```javascript +var inflight = require('inflight') + +// some request that does some stuff +function req(key, callback) { + // key is any random string. like a url or filename or whatever. + // + // will return either a falsey value, indicating that the + // request for this key is already in flight, or a new callback + // which when called will call all callbacks passed to inflightk + // with the same key + callback = inflight(key, callback) + + // If we got a falsey value back, then there's already a req going + if (!callback) return + + // this is where you'd fetch the url or whatever + // callback is also once()-ified, so it can safely be assigned + // to multiple events etc. First call wins. + setTimeout(function() { + callback(null, key) + }, 100) +} + +// only assigns a single setTimeout +// when it dings, all cbs get called +req('foo', cb1) +req('foo', cb2) +req('foo', cb3) +req('foo', cb4) +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/inflight.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/inflight.js new file mode 100644 index 0000000..8bc96cb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/inflight.js @@ -0,0 +1,44 @@ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/package.json new file mode 100644 index 0000000..2b8e311 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/package.json @@ -0,0 +1,36 @@ +{ + "name": "wrappy", + "version": "1.0.1", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^0.4.12" + }, + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/wrappy.git" + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy", + "readme": "# wrappy\n\nCallback wrapping utility\n\n## USAGE\n\n```javascript\nvar wrappy = require(\"wrappy\")\n\n// var wrapper = wrappy(wrapperFunction)\n\n// make sure a cb is called only once\n// See also: http://npm.im/once for this specific use case\nvar once = wrappy(function (cb) {\n var called = false\n return function () {\n if (called) return\n called = true\n return cb.apply(this, arguments)\n }\n})\n\nfunction printBoo () {\n console.log('boo')\n}\n// has some rando property\nprintBoo.iAmBooPrinter = true\n\nvar onlyPrintOnce = once(printBoo)\n\nonlyPrintOnce() // prints 'boo'\nonlyPrintOnce() // does nothing\n\n// random property is retained!\nassert.equal(onlyPrintOnce.iAmBooPrinter, true)\n```\n", + "readmeFilename": "README.md", + "_id": "wrappy@1.0.1", + "_shasum": "1e65969965ccbc2db4548c6b84a6f2c5aedd4739", + "_resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz", + "_from": "wrappy@>=1.0.0 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/test/basic.js new file mode 100644 index 0000000..5ed0fcd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/test/basic.js @@ -0,0 +1,51 @@ +var test = require('tap').test +var wrappy = require('../wrappy.js') + +test('basic', function (t) { + function onceifier (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } + } + onceifier.iAmOnce = {} + var once = wrappy(onceifier) + t.equal(once.iAmOnce, onceifier.iAmOnce) + + var called = 0 + function boo () { + t.equal(called, 0) + called++ + } + // has some rando property + boo.iAmBoo = true + + var onlyPrintOnce = once(boo) + + onlyPrintOnce() // prints 'boo' + onlyPrintOnce() // does nothing + t.equal(called, 1) + + // random property is retained! + t.equal(onlyPrintOnce.iAmBoo, true) + + var logs = [] + var logwrap = wrappy(function (msg, cb) { + logs.push(msg + ' wrapping cb') + return function () { + logs.push(msg + ' before cb') + var ret = cb.apply(this, arguments) + logs.push(msg + ' after cb') + } + }) + + var c = logwrap('foo', function () { + t.same(logs, [ 'foo wrapping cb', 'foo before cb' ]) + }) + c() + t.same(logs, [ 'foo wrapping cb', 'foo before cb', 'foo after cb' ]) + + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/wrappy.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/package.json new file mode 100644 index 0000000..20386c8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/package.json @@ -0,0 +1,36 @@ +{ + "name": "inflight", + "version": "1.0.4", + "description": "Add callbacks to requests in flight to avoid async duplication", + "main": "inflight.js", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + }, + "devDependencies": { + "tap": "^0.4.10" + }, + "scripts": { + "test": "tap test.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inflight.git" + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/inflight/issues" + }, + "homepage": "https://github.com/isaacs/inflight", + "license": "ISC", + "readme": "# inflight\n\nAdd callbacks to requests in flight to avoid async duplication\n\n## USAGE\n\n```javascript\nvar inflight = require('inflight')\n\n// some request that does some stuff\nfunction req(key, callback) {\n // key is any random string. like a url or filename or whatever.\n //\n // will return either a falsey value, indicating that the\n // request for this key is already in flight, or a new callback\n // which when called will call all callbacks passed to inflightk\n // with the same key\n callback = inflight(key, callback)\n\n // If we got a falsey value back, then there's already a req going\n if (!callback) return\n\n // this is where you'd fetch the url or whatever\n // callback is also once()-ified, so it can safely be assigned\n // to multiple events etc. First call wins.\n setTimeout(function() {\n callback(null, key)\n }, 100)\n}\n\n// only assigns a single setTimeout\n// when it dings, all cbs get called\nreq('foo', cb1)\nreq('foo', cb2)\nreq('foo', cb3)\nreq('foo', cb4)\n```\n", + "readmeFilename": "README.md", + "_id": "inflight@1.0.4", + "_shasum": "6cbb4521ebd51ce0ec0a936bfd7657ef7e9b172a", + "_resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.4.tgz", + "_from": "inflight@>=1.0.4 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/test.js new file mode 100644 index 0000000..2bb75b3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inflight/test.js @@ -0,0 +1,97 @@ +var test = require('tap').test +var inf = require('./inflight.js') + + +function req (key, cb) { + cb = inf(key, cb) + if (cb) setTimeout(function () { + cb(key) + cb(key) + }) + return cb +} + +test('basic', function (t) { + var calleda = false + var a = req('key', function (k) { + t.notOk(calleda) + calleda = true + t.equal(k, 'key') + if (calledb) t.end() + }) + t.ok(a, 'first returned cb function') + + var calledb = false + var b = req('key', function (k) { + t.notOk(calledb) + calledb = true + t.equal(k, 'key') + if (calleda) t.end() + }) + + t.notOk(b, 'second should get falsey inflight response') +}) + +test('timing', function (t) { + var expect = [ + 'method one', + 'start one', + 'end one', + 'two', + 'tick', + 'three' + ] + var i = 0 + + function log (m) { + t.equal(m, expect[i], m + ' === ' + expect[i]) + ++i + if (i === expect.length) + t.end() + } + + function method (name, cb) { + log('method ' + name) + process.nextTick(cb) + } + + var one = inf('foo', function () { + log('start one') + var three = inf('foo', function () { + log('three') + }) + if (three) method('three', three) + log('end one') + }) + + method('one', one) + + var two = inf('foo', function () { + log('two') + }) + if (two) method('one', two) + + process.nextTick(log.bind(null, 'tick')) +}) + +test('parameters', function (t) { + t.plan(8) + + var a = inf('key', function (first, second, third) { + t.equal(first, 1) + t.equal(second, 2) + t.equal(third, 3) + }) + t.ok(a, 'first returned cb function') + + var b = inf('key', function (first, second, third) { + t.equal(first, 1) + t.equal(second, 2) + t.equal(third, 3) + }) + t.notOk(b, 'second should get falsey inflight response') + + setTimeout(function () { + a(1, 2, 3) + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/package.json new file mode 100644 index 0000000..8c08a43 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.0 <3.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/README.md new file mode 100644 index 0000000..d458bc2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/README.md @@ -0,0 +1,216 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instanting the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +## Functions + +The top-level exported function has a `cache` property, which is an LRU +cache set to store 100 items. So, calling these methods repeatedly +with the same pattern and options will use the same Minimatch object, +saving the cost of parsing it multiple times. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/browser.js new file mode 100644 index 0000000..967b45c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/browser.js @@ -0,0 +1,1113 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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 require=="function"&&require;for(var o=0;o any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new Error('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var plType + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + plType = stateChar + patternListStack.push({ type: plType, start: i - 1, reStart: re.length }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + re += ')' + plType = patternListStack.pop().type + // negation is (?:(?!js)[^/]*) + // The others are (?:) + switch (plType) { + case '!': + re += '[^/]*?)' + break + case '?': + case '+': + case '*': + re += plType + break + case '@': break // the default anyway + } + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (var pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) re = '(?=.)' + re + + if (addPatternStart) re = patternStart + re + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + var regExp = new RegExp('^' + re + '$', flags) + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + +},{"brace-expansion":2,"path":undefined}],2:[function(require,module,exports){ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + var expansions = expand(escapeBraces(str)); + return expansions.filter(identity).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = /^(.*,)+(.+)?$/.test(m.body); + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0]).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + expansions.push([pre, N[j], post[k]].join('')) + } + } + + return expansions; +} + + +},{"balanced-match":3,"concat-map":4}],3:[function(require,module,exports){ +module.exports = balanced; +function balanced(a, b, str) { + var bal = 0; + var m = {}; + var ended = false; + + for (var i = 0; i < str.length; i++) { + if (a == str.substr(i, a.length)) { + if (!('start' in m)) m.start = i; + bal++; + } + else if (b == str.substr(i, b.length) && 'start' in m) { + ended = true; + bal--; + if (!bal) { + m.end = i; + m.pre = str.substr(0, m.start); + m.body = (m.end - m.start > 1) + ? str.substring(m.start + a.length, m.end) + : ''; + m.post = str.slice(m.end + b.length); + return m; + } + } + } + + // if we opened more than we closed, find the one we closed + if (bal && ended) { + var start = m.start + a.length; + m = balanced(a, b, str.substr(start)); + if (m) { + m.start += start; + m.end += start; + m.pre = str.slice(0, start) + m.pre; + } + return m; + } +} + +},{}],4:[function(require,module,exports){ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (Array.isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +},{}]},{},[1]); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/minimatch.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..5e13d6d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/minimatch.js @@ -0,0 +1,867 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new Error('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var plType + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + plType = stateChar + patternListStack.push({ type: plType, start: i - 1, reStart: re.length }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + re += ')' + plType = patternListStack.pop().type + // negation is (?:(?!js)[^/]*) + // The others are (?:) + switch (plType) { + case '!': + re += '[^/]*?)' + break + case '?': + case '+': + case '*': + re += plType + break + case '@': break // the default anyway + } + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (var pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) re = '(?=.)' + re + + if (addPatternStart) re = patternStart + re + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + var regExp = new RegExp('^' + re + '$', flags) + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.npmignore new file mode 100644 index 0000000..249bc20 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.npmignore @@ -0,0 +1,2 @@ +node_modules +*.sw* diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.travis.yml new file mode 100644 index 0000000..6e5919d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..62bc7ba --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/README.md @@ -0,0 +1,121 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma seperated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/example.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/example.js new file mode 100644 index 0000000..60ecfc7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/example.js @@ -0,0 +1,8 @@ +var expand = require('./'); + +console.log(expand('http://any.org/archive{1996..1999}/vol{1..4}/part{a,b,c}.html')); +console.log(expand('http://www.numericals.com/file{1..100..10}.txt')); +console.log(expand('http://www.letters.com/file{a..z..2}.txt')); +console.log(expand('mkdir /usr/local/src/bash/{old,new,dist,bugs}')); +console.log(expand('chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}')); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..a23104e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/index.js @@ -0,0 +1,191 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = /^(.*,)+(.+)?$/.test(m.body); + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore new file mode 100644 index 0000000..fd4f2b0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.npmignore @@ -0,0 +1,2 @@ +node_modules +.DS_Store diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile new file mode 100644 index 0000000..fa5da71 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test/*.js + +.PHONY: test + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md new file mode 100644 index 0000000..2aff0eb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/README.md @@ -0,0 +1,80 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js new file mode 100644 index 0000000..c02ad34 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/example.js @@ -0,0 +1,5 @@ +var balanced = require('./'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js new file mode 100644 index 0000000..d165ae8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/index.js @@ -0,0 +1,38 @@ +module.exports = balanced; +function balanced(a, b, str) { + var bal = 0; + var m = {}; + var ended = false; + + for (var i = 0; i < str.length; i++) { + if (a == str.substr(i, a.length)) { + if (!('start' in m)) m.start = i; + bal++; + } + else if (b == str.substr(i, b.length) && 'start' in m) { + ended = true; + bal--; + if (!bal) { + m.end = i; + m.pre = str.substr(0, m.start); + m.body = (m.end - m.start > 1) + ? str.substring(m.start + a.length, m.end) + : ''; + m.post = str.slice(m.end + b.length); + return m; + } + } + } + + // if we opened more than we closed, find the one we closed + if (bal && ended) { + var start = m.start + a.length; + m = balanced(a, b, str.substr(start)); + if (m) { + m.start += start; + m.end += start; + m.pre = str.slice(0, start) + m.pre; + } + return m; + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json new file mode 100644 index 0000000..35332a3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/package.json @@ -0,0 +1,56 @@ +{ + "name": "balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "0.2.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.1" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "readme": "# balanced-match\n\nMatch balanced string pairs, like `{` and `}` or `` and ``.\n\n[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)\n[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)\n\n[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)\n\n## Example\n\nGet the first matching pair of braces:\n\n```js\nvar balanced = require('balanced-match');\n\nconsole.log(balanced('{', '}', 'pre{in{nested}}post'));\nconsole.log(balanced('{', '}', 'pre{first}between{second}post'));\n```\n\nThe matches are:\n\n```bash\n$ node example.js\n{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }\n{ start: 3,\n end: 9,\n pre: 'pre',\n body: 'first',\n post: 'between{second}post' }\n```\n\n## API\n\n### var m = balanced(a, b, str)\n\nFor the first non-nested matching pair of `a` and `b` in `str`, return an\nobject with those keys:\n\n* **start** the index of the first match of `a`\n* **end** the index of the matching `b`\n* **pre** the preamble, `a` and `b` not included\n* **body** the match, `a` and `b` not included\n* **post** the postscript, `a` and `b` not included\n\nIf there's no match, `undefined` will be returned.\n\nIf the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']`.\n\n## Installation\n\nWith [npm](https://npmjs.org) do:\n\n```bash\nnpm install balanced-match\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies 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 THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "_id": "balanced-match@0.2.0", + "_shasum": "38f6730c03aab6d5edbb52bd934885e756d71674", + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.2.0.tgz", + "_from": "balanced-match@>=0.2.0 <0.3.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js new file mode 100644 index 0000000..36bfd39 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/balanced-match/test/balanced.js @@ -0,0 +1,56 @@ +var test = require('tape'); +var balanced = require('..'); + +test('balanced', function(t) { + t.deepEqual(balanced('{', '}', 'pre{in{nest}}post'), { + start: 3, + end: 12, + pre: 'pre', + body: 'in{nest}', + post: 'post' + }); + t.deepEqual(balanced('{', '}', '{{{{{{{{{in}post'), { + start: 8, + end: 11, + pre: '{{{{{{{{', + body: 'in', + post: 'post' + }); + t.deepEqual(balanced('{', '}', 'pre{body{in}post'), { + start: 8, + end: 11, + pre: 'pre{body', + body: 'in', + post: 'post' + }); + t.deepEqual(balanced('{', '}', 'pre}{in{nest}}post'), { + start: 4, + end: 13, + pre: 'pre}', + body: 'in{nest}', + post: 'post' + }); + t.deepEqual(balanced('{', '}', 'pre{body}between{body2}post'), { + start: 3, + end: 8, + pre: 'pre', + body: 'body', + post: 'between{body2}post' + }); + t.notOk(balanced('{', '}', 'nope'), 'should be notOk'); + t.deepEqual(balanced('', '', 'preinnestpost'), { + start: 3, + end: 19, + pre: 'pre', + body: 'innest', + post: 'post' + }); + t.deepEqual(balanced('', '', 'preinnestpost'), { + start: 7, + end: 23, + pre: 'pre', + body: 'innest', + post: 'post' + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown new file mode 100644 index 0000000..408f70a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js new file mode 100644 index 0000000..3365621 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js new file mode 100644 index 0000000..b29a781 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json new file mode 100644 index 0000000..50cc7b5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/package.json @@ -0,0 +1,69 @@ +{ + "name": "concat-map", + "description": "concatenative mapdashery", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/substack/node-concat-map.git" + }, + "main": "index.js", + "keywords": [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "directories": { + "example": "example", + "test": "test" + }, + "scripts": { + "test": "tape test/*.js" + }, + "devDependencies": { + "tape": "~2.4.0" + }, + "license": "MIT", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "readme": "concat-map\n==========\n\nConcatenative mapdashery.\n\n[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map)\n\n[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map)\n\nexample\n=======\n\n``` js\nvar concatMap = require('concat-map');\nvar xs = [ 1, 2, 3, 4, 5, 6 ];\nvar ys = concatMap(xs, function (x) {\n return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];\n});\nconsole.dir(ys);\n```\n\n***\n\n```\n[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]\n```\n\nmethods\n=======\n\n``` js\nvar concatMap = require('concat-map')\n```\n\nconcatMap(xs, fn)\n-----------------\n\nReturn an array of concatenated elements by calling `fn(x, i)` for each element\n`x` and each index `i` in the array `xs`.\n\nWhen `fn(x, i)` returns an array, its result will be concatenated with the\nresult array. If `fn(x, i)` returns anything else, that value will be pushed\nonto the end of the result array.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install concat-map\n```\n\nlicense\n=======\n\nMIT\n\nnotes\n=====\n\nThis module was written while sitting high above the ground in a tree.\n", + "readmeFilename": "README.markdown", + "bugs": { + "url": "https://github.com/substack/node-concat-map/issues" + }, + "homepage": "https://github.com/substack/node-concat-map#readme", + "_id": "concat-map@0.0.1", + "_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", + "_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "_from": "concat-map@0.0.1" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js new file mode 100644 index 0000000..fdbd702 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..ba78e62 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/package.json @@ -0,0 +1,54 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "1.1.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh" + }, + "dependencies": { + "balanced-match": "^0.2.0", + "concat-map": "0.0.1" + }, + "devDependencies": { + "tape": "^3.0.3" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "readme": "# brace-expansion\n\n[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), \nas known from sh/bash, in JavaScript.\n\n[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)\n\n[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)\n\n## Example\n\n```js\nvar expand = require('brace-expansion');\n\nexpand('file-{a,b,c}.jpg')\n// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']\n\nexpand('-v{,,}')\n// => ['-v', '-v', '-v']\n\nexpand('file{0..2}.jpg')\n// => ['file0.jpg', 'file1.jpg', 'file2.jpg']\n\nexpand('file-{a..c}.jpg')\n// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']\n\nexpand('file{2..0}.jpg')\n// => ['file2.jpg', 'file1.jpg', 'file0.jpg']\n\nexpand('file{0..4..2}.jpg')\n// => ['file0.jpg', 'file2.jpg', 'file4.jpg']\n\nexpand('file-{a..e..2}.jpg')\n// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']\n\nexpand('file{00..10..5}.jpg')\n// => ['file00.jpg', 'file05.jpg', 'file10.jpg']\n\nexpand('{{A..C},{a..c}}')\n// => ['A', 'B', 'C', 'a', 'b', 'c']\n\nexpand('ppp{,config,oe{,conf}}')\n// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']\n```\n\n## API\n\n```js\nvar expand = require('brace-expansion');\n```\n\n### var expanded = expand(str)\n\nReturn an array of all possible and valid expansions of `str`. If none are\nfound, `[str]` is returned.\n\nValid expansions are:\n\n```js\n/^(.*,)+(.+)?$/\n// {a,b,...}\n```\n\nA comma seperated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.\n\n```js\n/^-?\\d+\\.\\.-?\\d+(\\.\\.-?\\d+)?$/\n// {x..y[..incr]}\n```\n\nA numeric sequence from `x` to `y` inclusive, with optional increment.\nIf `x` or `y` start with a leading `0`, all the numbers will be padded\nto have equal length. Negative numbers and backwards iteration work too.\n\n```js\n/^-?\\d+\\.\\.-?\\d+(\\.\\.-?\\d+)?$/\n// {x..y[..incr]}\n```\n\nAn alphabetic sequence from `x` to `y` inclusive, with optional increment.\n`x` and `y` must be exactly one character, and if given, `incr` must be a\nnumber.\n\nFor compatibility reasons, the string `${` is not eligible for brace expansion.\n\n## Installation\n\nWith [npm](https://npmjs.org) do:\n\n```bash\nnpm install brace-expansion\n```\n\n## Contributors\n\n- [Julian Gruber](https://github.com/juliangruber)\n- [Isaac Z. Schlueter](https://github.com/isaacs)\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies 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 THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "_id": "brace-expansion@1.1.0", + "_shasum": "c9b7d03c03f37bc704be100e522b40db8f6cfcd9", + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.0.tgz", + "_from": "brace-expansion@>=1.0.0 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js new file mode 100644 index 0000000..5fe2b8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-comparison.js @@ -0,0 +1,32 @@ +var test = require('tape'); +var expand = require('..'); +var fs = require('fs'); +var resfile = __dirname + '/bash-results.txt'; +var cases = fs.readFileSync(resfile, 'utf8').split('><><><><'); + +// throw away the EOF marker +cases.pop() + +test('matches bash expansions', function(t) { + cases.forEach(function(testcase) { + var set = testcase.split('\n'); + var pattern = set.shift(); + var actual = expand(pattern); + + // If it expands to the empty string, then it's actually + // just nothing, but Bash is a singly typed language, so + // "nothing" is the same as "". + if (set.length === 1 && set[0] === '') { + set = [] + } else { + // otherwise, strip off the [] that were added so that + // "" expansions would be preserved properly. + set = set.map(function (s) { + return s.replace(/^\[|\]$/g, '') + }) + } + + t.same(actual, set, pattern); + }); + t.end(); +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt new file mode 100644 index 0000000..958148d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/bash-results.txt @@ -0,0 +1,1075 @@ +A{b,{d,e},{f,g}}Z +[AbZ] +[AdZ] +[AeZ] +[AfZ] +[AgZ]><><><><><><><\{a,b}{{a,b},a,b} +[{a,b}a] +[{a,b}b] +[{a,b}a] +[{a,b}b]><><><><{{a,b} +[{a] +[{b]><><><><{a,b}} +[a}] +[b}]><><><><{,} +><><><><><><><{,}b +[b] +[b]><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><{-01..5} +[-01] +[000] +[001] +[002] +[003] +[004] +[005]><><><><{-05..100..5} +[-05] +[000] +[005] +[010] +[015] +[020] +[025] +[030] +[035] +[040] +[045] +[050] +[055] +[060] +[065] +[070] +[075] +[080] +[085] +[090] +[095] +[100]><><><><{-05..100} +[-05] +[-04] +[-03] +[-02] +[-01] +[000] +[001] +[002] +[003] +[004] +[005] +[006] +[007] +[008] +[009] +[010] +[011] +[012] +[013] +[014] +[015] +[016] +[017] +[018] +[019] +[020] +[021] +[022] +[023] +[024] +[025] +[026] +[027] +[028] +[029] +[030] +[031] +[032] +[033] +[034] +[035] +[036] +[037] +[038] +[039] +[040] +[041] +[042] +[043] +[044] +[045] +[046] +[047] +[048] +[049] +[050] +[051] +[052] +[053] +[054] +[055] +[056] +[057] +[058] +[059] +[060] +[061] +[062] +[063] +[064] +[065] +[066] +[067] +[068] +[069] +[070] +[071] +[072] +[073] +[074] +[075] +[076] +[077] +[078] +[079] +[080] +[081] +[082] +[083] +[084] +[085] +[086] +[087] +[088] +[089] +[090] +[091] +[092] +[093] +[094] +[095] +[096] +[097] +[098] +[099] +[100]><><><><{0..5..2} +[0] +[2] +[4]><><><><{0001..05..2} +[0001] +[0003] +[0005]><><><><{0001..-5..2} +[0001] +[-001] +[-003] +[-005]><><><><{0001..-5..-2} +[0001] +[-001] +[-003] +[-005]><><><><{0001..5..-2} +[0001] +[0003] +[0005]><><><><{01..5} +[01] +[02] +[03] +[04] +[05]><><><><{1..05} +[01] +[02] +[03] +[04] +[05]><><><><{1..05..3} +[01] +[04]><><><><{05..100} +[005] +[006] +[007] +[008] +[009] +[010] +[011] +[012] +[013] +[014] +[015] +[016] +[017] +[018] +[019] +[020] +[021] +[022] +[023] +[024] +[025] +[026] +[027] +[028] +[029] +[030] +[031] +[032] +[033] +[034] +[035] +[036] +[037] +[038] +[039] +[040] +[041] +[042] +[043] +[044] +[045] +[046] +[047] +[048] +[049] +[050] +[051] +[052] +[053] +[054] +[055] +[056] +[057] +[058] +[059] +[060] +[061] +[062] +[063] +[064] +[065] +[066] +[067] +[068] +[069] +[070] +[071] +[072] +[073] +[074] +[075] +[076] +[077] +[078] +[079] +[080] +[081] +[082] +[083] +[084] +[085] +[086] +[087] +[088] +[089] +[090] +[091] +[092] +[093] +[094] +[095] +[096] +[097] +[098] +[099] +[100]><><><><{0a..0z} +[{0a..0z}]><><><><{a,b\}c,d} +[a] +[b}c] +[d]><><><><{a,b{c,d} +[{a,bc] +[{a,bd]><><><><{a,b}c,d} +[ac,d}] +[bc,d}]><><><><{a..F} +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z] +[Y] +[X] +[W] +[V] +[U] +[T] +[S] +[R] +[Q] +[P] +[O] +[N] +[M] +[L] +[K] +[J] +[I] +[H] +[G] +[F]><><><><{A..f} +[A] +[B] +[C] +[D] +[E] +[F] +[G] +[H] +[I] +[J] +[K] +[L] +[M] +[N] +[O] +[P] +[Q] +[R] +[S] +[T] +[U] +[V] +[W] +[X] +[Y] +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a] +[b] +[c] +[d] +[e] +[f]><><><><{a..Z} +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z]><><><><{A..z} +[A] +[B] +[C] +[D] +[E] +[F] +[G] +[H] +[I] +[J] +[K] +[L] +[M] +[N] +[O] +[P] +[Q] +[R] +[S] +[T] +[U] +[V] +[W] +[X] +[Y] +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a] +[b] +[c] +[d] +[e] +[f] +[g] +[h] +[i] +[j] +[k] +[l] +[m] +[n] +[o] +[p] +[q] +[r] +[s] +[t] +[u] +[v] +[w] +[x] +[y] +[z]><><><><{z..A} +[z] +[y] +[x] +[w] +[v] +[u] +[t] +[s] +[r] +[q] +[p] +[o] +[n] +[m] +[l] +[k] +[j] +[i] +[h] +[g] +[f] +[e] +[d] +[c] +[b] +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z] +[Y] +[X] +[W] +[V] +[U] +[T] +[S] +[R] +[Q] +[P] +[O] +[N] +[M] +[L] +[K] +[J] +[I] +[H] +[G] +[F] +[E] +[D] +[C] +[B] +[A]><><><><{Z..a} +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a]><><><><{a..F..2} +[a] +[_] +[]] +[[] +[Y] +[W] +[U] +[S] +[Q] +[O] +[M] +[K] +[I] +[G]><><><><{A..f..02} +[A] +[C] +[E] +[G] +[I] +[K] +[M] +[O] +[Q] +[S] +[U] +[W] +[Y] +[[] +[]] +[_] +[a] +[c] +[e]><><><><{a..Z..5} +[a] +[]><><><><><><><{A..z..10} +[A] +[K] +[U] +[_] +[i] +[s]><><><><{z..A..-2} +[z] +[x] +[v] +[t] +[r] +[p] +[n] +[l] +[j] +[h] +[f] +[d] +[b] +[`] +[^] +[] +[Z] +[X] +[V] +[T] +[R] +[P] +[N] +[L] +[J] +[H] +[F] +[D] +[B]><><><><{Z..a..20} +[Z]><><><><{a{,b} +[{a] +[{ab]><><><><{a},b} +[a}] +[b]><><><><{x,y{,}g} +[x] +[yg] +[yg]><><><><{x,y{}g} +[x] +[y{}g]><><><><{{a,b} +[{a] +[{b]><><><><{{a,b},c} +[a] +[b] +[c]><><><><{{a,b}c} +[{ac}] +[{bc}]><><><><{{a,b},} +[a] +[b]><><><><><><><{{a,b},}c +[ac] +[bc] +[c]><><><><{{a,b}.} +[{a.}] +[{b.}]><><><><{{a,b}} +[{a}] +[{b}]><><><><><><>< +><><><><{-10..00} +[-10] +[-09] +[-08] +[-07] +[-06] +[-05] +[-04] +[-03] +[-02] +[-01] +[000]><><><><{a,\\{a,b}c} +[a] +[\ac] +[\bc]><><><><{a,\{a,b}c} +[ac}] +[{ac}] +[bc}]><><><><><><><{-10.\.00} +[{-10..00}]><><><><><><><><><><{l,n,m}xyz +[lxyz] +[nxyz] +[mxyz]><><><><{abc\,def} +[{abc,def}]><><><><{abc} +[{abc}]><><><><{x\,y,\{abc\},trie} +[x,y] +[{abc}] +[trie]><><><><{} +[{}]><><><><} +[}]><><><><{ +[{]><><><><><><><{1..10} +[1] +[2] +[3] +[4] +[5] +[6] +[7] +[8] +[9] +[10]><><><><{0..10,braces} +[0..10] +[braces]><><><><{{0..10},braces} +[0] +[1] +[2] +[3] +[4] +[5] +[6] +[7] +[8] +[9] +[10] +[braces]><><><><><><><{3..3} +[3]><><><><><><><{10..1} +[10] +[9] +[8] +[7] +[6] +[5] +[4] +[3] +[2] +[1]><><><><{10..1}y +[10y] +[9y] +[8y] +[7y] +[6y] +[5y] +[4y] +[3y] +[2y] +[1y]><><><><><><><{a..f} +[a] +[b] +[c] +[d] +[e] +[f]><><><><{f..a} +[f] +[e] +[d] +[c] +[b] +[a]><><><><{a..A} +[a] +[`] +[_] +[^] +[]] +[] +[[] +[Z] +[Y] +[X] +[W] +[V] +[U] +[T] +[S] +[R] +[Q] +[P] +[O] +[N] +[M] +[L] +[K] +[J] +[I] +[H] +[G] +[F] +[E] +[D] +[C] +[B] +[A]><><><><{A..a} +[A] +[B] +[C] +[D] +[E] +[F] +[G] +[H] +[I] +[J] +[K] +[L] +[M] +[N] +[O] +[P] +[Q] +[R] +[S] +[T] +[U] +[V] +[W] +[X] +[Y] +[Z] +[[] +[] +[]] +[^] +[_] +[`] +[a]><><><><{f..f} +[f]><><><><{1..f} +[{1..f}]><><><><{f..1} +[{f..1}]><><><><{-1..-10} +[-1] +[-2] +[-3] +[-4] +[-5] +[-6] +[-7] +[-8] +[-9] +[-10]><><><><{-20..0} +[-20] +[-19] +[-18] +[-17] +[-16] +[-15] +[-14] +[-13] +[-12] +[-11] +[-10] +[-9] +[-8] +[-7] +[-6] +[-5] +[-4] +[-3] +[-2] +[-1] +[0]><><><><><><><><><><{klklkl}{1,2,3} +[{klklkl}1] +[{klklkl}2] +[{klklkl}3]><><><><{1..10..2} +[1] +[3] +[5] +[7] +[9]><><><><{-1..-10..2} +[-1] +[-3] +[-5] +[-7] +[-9]><><><><{-1..-10..-2} +[-1] +[-3] +[-5] +[-7] +[-9]><><><><{10..1..-2} +[10] +[8] +[6] +[4] +[2]><><><><{10..1..2} +[10] +[8] +[6] +[4] +[2]><><><><{1..20..2} +[1] +[3] +[5] +[7] +[9] +[11] +[13] +[15] +[17] +[19]><><><><{1..20..20} +[1]><><><><{100..0..5} +[100] +[95] +[90] +[85] +[80] +[75] +[70] +[65] +[60] +[55] +[50] +[45] +[40] +[35] +[30] +[25] +[20] +[15] +[10] +[5] +[0]><><><><{100..0..-5} +[100] +[95] +[90] +[85] +[80] +[75] +[70] +[65] +[60] +[55] +[50] +[45] +[40] +[35] +[30] +[25] +[20] +[15] +[10] +[5] +[0]><><><><{a..z} +[a] +[b] +[c] +[d] +[e] +[f] +[g] +[h] +[i] +[j] +[k] +[l] +[m] +[n] +[o] +[p] +[q] +[r] +[s] +[t] +[u] +[v] +[w] +[x] +[y] +[z]><><><><{a..z..2} +[a] +[c] +[e] +[g] +[i] +[k] +[m] +[o] +[q] +[s] +[u] +[w] +[y]><><><><{z..a..-2} +[z] +[x] +[v] +[t] +[r] +[p] +[n] +[l] +[j] +[h] +[f] +[d] +[b]><><><><{2147483645..2147483649} +[2147483645] +[2147483646] +[2147483647] +[2147483648] +[2147483649]><><><><{10..0..2} +[10] +[8] +[6] +[4] +[2] +[0]><><><><{10..0..-2} +[10] +[8] +[6] +[4] +[2] +[0]><><><><{-50..-0..5} +[-50] +[-45] +[-40] +[-35] +[-30] +[-25] +[-20] +[-15] +[-10] +[-5] +[0]><><><><{1..10.f} +[{1..10.f}]><><><><{1..ff} +[{1..ff}]><><><><{1..10..ff} +[{1..10..ff}]><><><><{1.20..2} +[{1.20..2}]><><><><{1..20..f2} +[{1..20..f2}]><><><><{1..20..2f} +[{1..20..2f}]><><><><{1..2f..2} +[{1..2f..2}]><><><><{1..ff..2} +[{1..ff..2}]><><><><{1..ff} +[{1..ff}]><><><><{1..f} +[{1..f}]><><><><{1..0f} +[{1..0f}]><><><><{1..10f} +[{1..10f}]><><><><{1..10.f} +[{1..10.f}]><><><><{1..10.f} +[{1..10.f}]><><><>< \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt new file mode 100644 index 0000000..e5161c3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/cases.txt @@ -0,0 +1,182 @@ +# skip quotes for now +# "{x,x}" +# {"x,x"} +# {x","x} +# '{a,b}{{a,b},a,b}' +A{b,{d,e},{f,g}}Z +PRE-{a,b}{{a,b},a,b}-POST +\\{a,b}{{a,b},a,b} +{{a,b} +{a,b}} +{,} +a{,} +{,}b +a{,}b +a{b}c +a{1..5}b +a{01..5}b +a{-01..5}b +a{-01..5..3}b +a{001..9}b +a{b,c{d,e},{f,g}h}x{y,z +a{b,c{d,e},{f,g}h}x{y,z\\} +a{b,c{d,e},{f,g}h}x{y,z} +a{b{c{d,e}f{x,y{{g}h +a{b{c{d,e}f{x,y{}g}h +a{b{c{d,e}f{x,y}}g}h +a{b{c{d,e}f}g}h +a{{x,y},z}b +f{x,y{g,z}}h +f{x,y{{g,z}}h +f{x,y{{g,z}}h} +f{x,y{{g}h +f{x,y{{g}}h +f{x,y{}g}h +z{a,b{,c}d +z{a,b},c}d +{-01..5} +{-05..100..5} +{-05..100} +{0..5..2} +{0001..05..2} +{0001..-5..2} +{0001..-5..-2} +{0001..5..-2} +{01..5} +{1..05} +{1..05..3} +{05..100} +{0a..0z} +{a,b\\}c,d} +{a,b{c,d} +{a,b}c,d} +{a..F} +{A..f} +{a..Z} +{A..z} +{z..A} +{Z..a} +{a..F..2} +{A..f..02} +{a..Z..5} +d{a..Z..5}b +{A..z..10} +{z..A..-2} +{Z..a..20} +{a{,b} +{a},b} +{x,y{,}g} +{x,y{}g} +{{a,b} +{{a,b},c} +{{a,b}c} +{{a,b},} +X{{a,b},}X +{{a,b},}c +{{a,b}.} +{{a,b}} +X{a..#}X +# this next one is an empty string + +{-10..00} +# Need to escape slashes in here for reasons i guess. +{a,\\\\{a,b}c} +{a,\\{a,b}c} +a,\\{b,c} +{-10.\\.00} +#### bash tests/braces.tests +# Note that some tests are edited out because some features of +# bash are intentionally not supported in this brace expander. +ff{c,b,a} +f{d,e,f}g +{l,n,m}xyz +{abc\\,def} +{abc} +{x\\,y,\\{abc\\},trie} +# not impementing back-ticks obviously +# XXXX\\{`echo a b c | tr ' ' ','`\\} +{} +# We only ever have to worry about parsing a single argument, +# not a command line, so spaces have a different meaning than bash. +# { } +} +{ +abcd{efgh +# spaces +# foo {1,2} bar +# not impementing back-ticks obviously +# `zecho foo {1,2} bar` +# $(zecho foo {1,2} bar) +# ${var} is not a variable here, like it is in bash. omit. +# foo{bar,${var}.} +# foo{bar,${var}} +# isaacs: skip quotes for now +# "${var}"{x,y} +# $var{x,y} +# ${var}{x,y} +# new sequence brace operators +{1..10} +# this doesn't work yet +{0..10,braces} +# but this does +{{0..10},braces} +x{{0..10},braces}y +{3..3} +x{3..3}y +{10..1} +{10..1}y +x{10..1}y +{a..f} +{f..a} +{a..A} +{A..a} +{f..f} +# mixes are incorrectly-formed brace expansions +{1..f} +{f..1} +# spaces +# 0{1..9} {10..20} +# do negative numbers work? +{-1..-10} +{-20..0} +# weirdly-formed brace expansions -- fixed in post-bash-3.1 +a-{b{d,e}}-c +a-{bdef-{g,i}-c +# isaacs: skip quotes for now +# {"klklkl"}{1,2,3} +# isaacs: this is a valid test, though +{klklkl}{1,2,3} +# {"x,x"} +{1..10..2} +{-1..-10..2} +{-1..-10..-2} +{10..1..-2} +{10..1..2} +{1..20..2} +{1..20..20} +{100..0..5} +{100..0..-5} +{a..z} +{a..z..2} +{z..a..-2} +# make sure brace expansion handles ints > 2**31 - 1 using intmax_t +{2147483645..2147483649} +# unwanted zero-padding -- fixed post-bash-4.0 +{10..0..2} +{10..0..-2} +{-50..-0..5} +# bad +{1..10.f} +{1..ff} +{1..10..ff} +{1.20..2} +{1..20..f2} +{1..20..2f} +{1..2f..2} +{1..ff..2} +{1..ff} +{1..f} +{1..0f} +{1..10f} +{1..10.f} +{1..10.f} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js new file mode 100644 index 0000000..3fcc185 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/dollar.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var expand = require('..'); + +test('ignores ${', function(t) { + t.deepEqual(expand('${1..3}'), ['${1..3}']); + t.deepEqual(expand('${a,b}${c,d}'), ['${a,b}${c,d}']); + t.deepEqual(expand('x${a,b}x${c,d}x'), ['x${a,b}x${c,d}x']); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js new file mode 100644 index 0000000..e429121 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/empty-option.js @@ -0,0 +1,10 @@ +var test = require('tape'); +var expand = require('..'); + +test('empty option', function(t) { + t.deepEqual(expand('-v{,,,,}'), [ + '-v', '-v', '-v', '-v', '-v' + ]); + t.end(); +}); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh new file mode 100644 index 0000000..e040e66 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/generate.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -e + +# Bash 4.3 because of arbitrary need to pick a single standard. + +if [ "${BASH_VERSINFO[0]}" != "4" ] || [ "${BASH_VERSINFO[1]}" != "3" ]; then + echo "this script requires bash 4.3" >&2 + exit 1 +fi + +CDPATH= cd "$(dirname "$0")" + +js='require("./")(process.argv[1]).join(" ")' + +cat cases.txt | \ + while read case; do + if [ "${case:0:1}" = "#" ]; then + continue; + fi; + b="$($BASH -c 'for c in '"$case"'; do echo ["$c"]; done')" + echo "$case" + echo -n "$b><><><><"; + done > bash-results.txt diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js new file mode 100644 index 0000000..8d434c2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/negative-increment.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var expand = require('..'); + +test('negative increment', function(t) { + t.deepEqual(expand('{3..1}'), ['3', '2', '1']); + t.deepEqual(expand('{10..8}'), ['10', '9', '8']); + t.deepEqual(expand('{10..08}'), ['10', '09', '08']); + t.deepEqual(expand('{c..a}'), ['c', 'b', 'a']); + + t.deepEqual(expand('{4..0..2}'), ['4', '2', '0']); + t.deepEqual(expand('{4..0..-2}'), ['4', '2', '0']); + t.deepEqual(expand('{e..a..2}'), ['e', 'c', 'a']); + + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/nested.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/nested.js new file mode 100644 index 0000000..0862dc5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/nested.js @@ -0,0 +1,16 @@ +var test = require('tape'); +var expand = require('..'); + +test('nested', function(t) { + t.deepEqual(expand('{a,b{1..3},c}'), [ + 'a', 'b1', 'b2', 'b3', 'c' + ]); + t.deepEqual(expand('{{A..Z},{a..z}}'), + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') + ); + t.deepEqual(expand('ppp{,config,oe{,conf}}'), [ + 'ppp', 'pppconfig', 'pppoe', 'pppoeconf' + ]); + t.end(); +}); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/order.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/order.js new file mode 100644 index 0000000..c00ad15 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/order.js @@ -0,0 +1,10 @@ +var test = require('tape'); +var expand = require('..'); + +test('order', function(t) { + t.deepEqual(expand('a{d,c,b}e'), [ + 'ade', 'ace', 'abe' + ]); + t.end(); +}); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/pad.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/pad.js new file mode 100644 index 0000000..e415877 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/pad.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var expand = require('..'); + +test('pad', function(t) { + t.deepEqual(expand('{9..11}'), [ + '9', '10', '11' + ]); + t.deepEqual(expand('{09..11}'), [ + '09', '10', '11' + ]); + t.end(); +}); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js new file mode 100644 index 0000000..3038fba --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/same-type.js @@ -0,0 +1,7 @@ +var test = require('tape'); +var expand = require('..'); + +test('x and y of same type', function(t) { + t.deepEqual(expand('{a..9}'), ['{a..9}']); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js new file mode 100644 index 0000000..f73a957 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion/test/sequence.js @@ -0,0 +1,50 @@ +var test = require('tape'); +var expand = require('..'); + +test('numeric sequences', function(t) { + t.deepEqual(expand('a{1..2}b{2..3}c'), [ + 'a1b2c', 'a1b3c', 'a2b2c', 'a2b3c' + ]); + t.deepEqual(expand('{1..2}{2..3}'), [ + '12', '13', '22', '23' + ]); + t.end(); +}); + +test('numeric sequences with step count', function(t) { + t.deepEqual(expand('{0..8..2}'), [ + '0', '2', '4', '6', '8' + ]); + t.deepEqual(expand('{1..8..2}'), [ + '1', '3', '5', '7' + ]); + t.end(); +}); + +test('numeric sequence with negative x / y', function(t) { + t.deepEqual(expand('{3..-2}'), [ + '3', '2', '1', '0', '-1', '-2' + ]); + t.end(); +}); + +test('alphabetic sequences', function(t) { + t.deepEqual(expand('1{a..b}2{b..c}3'), [ + '1a2b3', '1a2c3', '1b2b3', '1b2c3' + ]); + t.deepEqual(expand('{a..b}{b..c}'), [ + 'ab', 'ac', 'bb', 'bc' + ]); + t.end(); +}); + +test('alphabetic sequences with step count', function(t) { + t.deepEqual(expand('{a..k..2}'), [ + 'a', 'c', 'e', 'g', 'i', 'k' + ]); + t.deepEqual(expand('{b..k..2}'), [ + 'b', 'd', 'f', 'h', 'j' + ]); + t.end(); +}); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/package.json new file mode 100644 index 0000000..986de93 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/minimatch/package.json @@ -0,0 +1,63 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "2.0.8", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "pretest": "standard minimatch.js test/*.js", + "test": "tap test/*.js", + "prepublish": "browserify -o browser.js -e minimatch.js --bare" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "brace-expansion": "^1.0.0" + }, + "devDependencies": { + "browserify": "^9.0.3", + "standard": "^3.7.2", + "tap": "" + }, + "license": "ISC", + "files": [ + "minimatch.js", + "browser.js" + ], + "gitHead": "0bc7d9c4b2bc816502184862b45bd090de3406a3", + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "homepage": "https://github.com/isaacs/minimatch#readme", + "_id": "minimatch@2.0.8", + "_shasum": "0bc20f6bf3570a698ef0ddff902063c6cabda6bf", + "_from": "minimatch@>=2.0.1 <3.0.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "0bc20f6bf3570a698ef0ddff902063c6cabda6bf", + "tarball": "http://registry.npmjs.org/minimatch/-/minimatch-2.0.8.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-2.0.8.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/README.md new file mode 100644 index 0000000..a2981ea --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/README.md @@ -0,0 +1,51 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/package.json new file mode 100644 index 0000000..2b8e311 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/package.json @@ -0,0 +1,36 @@ +{ + "name": "wrappy", + "version": "1.0.1", + "description": "Callback wrapping utility", + "main": "wrappy.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "^0.4.12" + }, + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/npm/wrappy.git" + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "ISC", + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "homepage": "https://github.com/npm/wrappy", + "readme": "# wrappy\n\nCallback wrapping utility\n\n## USAGE\n\n```javascript\nvar wrappy = require(\"wrappy\")\n\n// var wrapper = wrappy(wrapperFunction)\n\n// make sure a cb is called only once\n// See also: http://npm.im/once for this specific use case\nvar once = wrappy(function (cb) {\n var called = false\n return function () {\n if (called) return\n called = true\n return cb.apply(this, arguments)\n }\n})\n\nfunction printBoo () {\n console.log('boo')\n}\n// has some rando property\nprintBoo.iAmBooPrinter = true\n\nvar onlyPrintOnce = once(printBoo)\n\nonlyPrintOnce() // prints 'boo'\nonlyPrintOnce() // does nothing\n\n// random property is retained!\nassert.equal(onlyPrintOnce.iAmBooPrinter, true)\n```\n", + "readmeFilename": "README.md", + "_id": "wrappy@1.0.1", + "_shasum": "1e65969965ccbc2db4548c6b84a6f2c5aedd4739", + "_resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.1.tgz", + "_from": "wrappy@>=1.0.0 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/test/basic.js new file mode 100644 index 0000000..5ed0fcd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/test/basic.js @@ -0,0 +1,51 @@ +var test = require('tap').test +var wrappy = require('../wrappy.js') + +test('basic', function (t) { + function onceifier (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } + } + onceifier.iAmOnce = {} + var once = wrappy(onceifier) + t.equal(once.iAmOnce, onceifier.iAmOnce) + + var called = 0 + function boo () { + t.equal(called, 0) + called++ + } + // has some rando property + boo.iAmBoo = true + + var onlyPrintOnce = once(boo) + + onlyPrintOnce() // prints 'boo' + onlyPrintOnce() // does nothing + t.equal(called, 1) + + // random property is retained! + t.equal(onlyPrintOnce.iAmBoo, true) + + var logs = [] + var logwrap = wrappy(function (msg, cb) { + logs.push(msg + ' wrapping cb') + return function () { + logs.push(msg + ' before cb') + var ret = cb.apply(this, arguments) + logs.push(msg + ' after cb') + } + }) + + var c = logwrap('foo', function () { + t.same(logs, [ 'foo wrapping cb', 'foo before cb' ]) + }) + c() + t.same(logs, [ 'foo wrapping cb', 'foo before cb', 'foo after cb' ]) + + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/wrappy.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/once.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/once.js new file mode 100644 index 0000000..2e1e721 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/once.js @@ -0,0 +1,21 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/package.json new file mode 100644 index 0000000..5b64a1b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/package.json @@ -0,0 +1,44 @@ +{ + "name": "once", + "version": "1.3.2", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "~0.3.0" + }, + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once.git" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "ISC", + "readme": "# once\n\nOnly call a function once.\n\n## usage\n\n```javascript\nvar once = require('once')\n\nfunction load (file, cb) {\n cb = once(cb)\n loader.load('file')\n loader.once('load', cb)\n loader.once('error', cb)\n}\n```\n\nOr add to the Function.prototype in a responsible way:\n\n```javascript\n// only has to be done once\nrequire('once').proto()\n\nfunction load (file, cb) {\n cb = cb.once()\n loader.load('file')\n loader.once('load', cb)\n loader.once('error', cb)\n}\n```\n\nIronically, the prototype feature makes this module twice as\ncomplicated as necessary.\n\nTo check whether you function has been called, use `fn.called`. Once the\nfunction is called for the first time the return value of the original\nfunction is saved in `fn.value` and subsequent calls will continue to\nreturn this value.\n\n```javascript\nvar once = require('once')\n\nfunction load (cb) {\n cb = once(cb)\n var stream = createStream()\n stream.once('data', cb)\n stream.once('end', function () {\n if (!cb.called) cb(new Error('not found'))\n })\n}\n```\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/once/issues" + }, + "homepage": "https://github.com/isaacs/once#readme", + "_id": "once@1.3.2", + "_shasum": "d8feeca93b039ec1dcdee7741c92bdac5e28081b", + "_resolved": "https://registry.npmjs.org/once/-/once-1.3.2.tgz", + "_from": "once@>=1.3.0 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/test/once.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/test/once.js new file mode 100644 index 0000000..c618360 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/node_modules/once/test/once.js @@ -0,0 +1,23 @@ +var test = require('tap').test +var once = require('../once.js') + +test('once', function (t) { + var f = 0 + function fn (g) { + t.equal(f, 0) + f ++ + return f + g + this + } + fn.ownProperty = {} + var foo = once(fn) + t.equal(fn.ownProperty, foo.ownProperty) + t.notOk(foo.called) + for (var i = 0; i < 1E3; i++) { + t.same(f, i === 0 ? 0 : 1) + var g = foo.call(1, 1) + t.ok(foo.called) + t.same(g, 3) + t.same(f, 1) + } + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/package.json new file mode 100644 index 0000000..acae7aa --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/package.json @@ -0,0 +1,55 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "glob", + "description": "a little globber", + "version": "4.5.3", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "main": "glob.js", + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "engines": { + "node": "*" + }, + "dependencies": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^2.0.1", + "once": "^1.3.0" + }, + "devDependencies": { + "mkdirp": "0", + "rimraf": "^2.2.8", + "tap": "^0.5.0", + "tick": "0.0.6" + }, + "scripts": { + "prepublish": "npm run benchclean", + "profclean": "rm -f v8.log profile.txt", + "test": "npm run profclean && tap test/*.js", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", + "bench": "bash benchmark.sh", + "prof": "bash prof.sh && cat profile.txt", + "benchclean": "bash benchclean.sh" + }, + "license": "ISC", + "readme": "[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Dependency Status](https://david-dm.org/isaacs/node-glob.svg)](https://david-dm.org/isaacs/node-glob) [![devDependency Status](https://david-dm.org/isaacs/node-glob/dev-status.svg)](https://david-dm.org/isaacs/node-glob#info=devDependencies) [![optionalDependency Status](https://david-dm.org/isaacs/node-glob/optional-status.svg)](https://david-dm.org/isaacs/node-glob#info=optionalDependencies)\n\n# Glob\n\nMatch files using the patterns the shell uses, like stars and stuff.\n\nThis is a glob implementation in JavaScript. It uses the `minimatch`\nlibrary to do its matching.\n\n![](oh-my-glob.gif)\n\n## Usage\n\n```javascript\nvar glob = require(\"glob\")\n\n// options is optional\nglob(\"**/*.js\", options, function (er, files) {\n // files is an array of filenames.\n // If the `nonull` option is set, and nothing\n // was found, then files is [\"**/*.js\"]\n // er is an error object or null.\n})\n```\n\n## Glob Primer\n\n\"Globs\" are the patterns you type when you do stuff like `ls *.js` on\nthe command line, or put `build/*` in a `.gitignore` file.\n\nBefore parsing the path part patterns, braced sections are expanded\ninto a set. Braced sections start with `{` and end with `}`, with any\nnumber of comma-delimited sections within. Braced sections may contain\nslash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.\n\nThe following characters have special magic meaning when used in a\npath portion:\n\n* `*` Matches 0 or more characters in a single path portion\n* `?` Matches 1 character\n* `[...]` Matches a range of characters, similar to a RegExp range.\n If the first character of the range is `!` or `^` then it matches\n any character not in the range.\n* `!(pattern|pattern|pattern)` Matches anything that does not match\n any of the patterns provided.\n* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the\n patterns provided.\n* `+(pattern|pattern|pattern)` Matches one or more occurrences of the\n patterns provided.\n* `*(a|b|c)` Matches zero or more occurrences of the patterns provided\n* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns\n provided\n* `**` If a \"globstar\" is alone in a path portion, then it matches\n zero or more directories and subdirectories searching for matches.\n It does not crawl symlinked directories.\n\n### Dots\n\nIf a file or directory path portion has a `.` as the first character,\nthen it will not match any glob pattern unless that pattern's\ncorresponding path part also has a `.` as its first character.\n\nFor example, the pattern `a/.*/c` would match the file at `a/.b/c`.\nHowever the pattern `a/*/c` would not, because `*` does not start with\na dot character.\n\nYou can make glob treat dots as normal characters by setting\n`dot:true` in the options.\n\n### Basename Matching\n\nIf you set `matchBase:true` in the options, and the pattern has no\nslashes in it, then it will seek for any file anywhere in the tree\nwith a matching basename. For example, `*.js` would match\n`test/simple/basic.js`.\n\n### Negation\n\nThe intent for negation would be for a pattern starting with `!` to\nmatch everything that *doesn't* match the supplied pattern. However,\nthe implementation is weird, and for the time being, this should be\navoided. The behavior will change or be deprecated in version 5.\n\n### Empty Sets\n\nIf no matching files are found, then an empty array is returned. This\ndiffers from the shell, where the pattern itself is returned. For\nexample:\n\n $ echo a*s*d*f\n a*s*d*f\n\nTo get the bash-style behavior, set the `nonull:true` in the options.\n\n### See Also:\n\n* `man sh`\n* `man bash` (Search for \"Pattern Matching\")\n* `man 3 fnmatch`\n* `man 5 gitignore`\n* [minimatch documentation](https://github.com/isaacs/minimatch)\n\n## glob.hasMagic(pattern, [options])\n\nReturns `true` if there are any special characters in the pattern, and\n`false` otherwise.\n\nNote that the options affect the results. If `noext:true` is set in\nthe options object, then `+(a|b)` will not be considered a magic\npattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`\nthen that is considered magical, unless `nobrace:true` is set in the\noptions.\n\n## glob(pattern, [options], cb)\n\n* `pattern` {String} Pattern to be matched\n* `options` {Object}\n* `cb` {Function}\n * `err` {Error | null}\n * `matches` {Array} filenames found matching the pattern\n\nPerform an asynchronous glob search.\n\n## glob.sync(pattern, [options])\n\n* `pattern` {String} Pattern to be matched\n* `options` {Object}\n* return: {Array} filenames found matching the pattern\n\nPerform a synchronous glob search.\n\n## Class: glob.Glob\n\nCreate a Glob object by instantiating the `glob.Glob` class.\n\n```javascript\nvar Glob = require(\"glob\").Glob\nvar mg = new Glob(pattern, options, cb)\n```\n\nIt's an EventEmitter, and starts walking the filesystem to find matches\nimmediately.\n\n### new glob.Glob(pattern, [options], [cb])\n\n* `pattern` {String} pattern to search for\n* `options` {Object}\n* `cb` {Function} Called when an error occurs, or matches are found\n * `err` {Error | null}\n * `matches` {Array} filenames found matching the pattern\n\nNote that if the `sync` flag is set in the options, then matches will\nbe immediately available on the `g.found` member.\n\n### Properties\n\n* `minimatch` The minimatch object that the glob uses.\n* `options` The options object passed in.\n* `aborted` Boolean which is set to true when calling `abort()`. There\n is no way at this time to continue a glob search after aborting, but\n you can re-use the statCache to avoid having to duplicate syscalls.\n* `statCache` Collection of all the stat results the glob search\n performed.\n* `cache` Convenience object. Each field has the following possible\n values:\n * `false` - Path does not exist\n * `true` - Path exists\n * `'DIR'` - Path exists, and is not a directory\n * `'FILE'` - Path exists, and is a directory\n * `[file, entries, ...]` - Path exists, is a directory, and the\n array value is the results of `fs.readdir`\n* `statCache` Cache of `fs.stat` results, to prevent statting the same\n path multiple times.\n* `symlinks` A record of which paths are symbolic links, which is\n relevant in resolving `**` patterns.\n* `realpathCache` An optional object which is passed to `fs.realpath`\n to minimize unnecessary syscalls. It is stored on the instantiated\n Glob object, and may be re-used.\n\n### Events\n\n* `end` When the matching is finished, this is emitted with all the\n matches found. If the `nonull` option is set, and no match was found,\n then the `matches` list contains the original pattern. The matches\n are sorted, unless the `nosort` flag is set.\n* `match` Every time a match is found, this is emitted with the matched.\n* `error` Emitted when an unexpected error is encountered, or whenever\n any fs error occurs if `options.strict` is set.\n* `abort` When `abort()` is called, this event is raised.\n\n### Methods\n\n* `pause` Temporarily stop the search\n* `resume` Resume the search\n* `abort` Stop the search forever\n\n### Options\n\nAll the options that can be passed to Minimatch can also be passed to\nGlob to change pattern matching behavior. Also, some have been added,\nor have glob-specific ramifications.\n\nAll options are false by default, unless otherwise noted.\n\nAll options are added to the Glob object, as well.\n\nIf you are running many `glob` operations, you can pass a Glob object\nas the `options` argument to a subsequent operation to shortcut some\n`stat` and `readdir` calls. At the very least, you may pass in shared\n`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that\nparallel glob operations will be sped up by sharing information about\nthe filesystem.\n\n* `cwd` The current working directory in which to search. Defaults\n to `process.cwd()`.\n* `root` The place where patterns starting with `/` will be mounted\n onto. Defaults to `path.resolve(options.cwd, \"/\")` (`/` on Unix\n systems, and `C:\\` or some such on Windows.)\n* `dot` Include `.dot` files in normal matches and `globstar` matches.\n Note that an explicit dot in a portion of the pattern will always\n match dot files.\n* `nomount` By default, a pattern starting with a forward-slash will be\n \"mounted\" onto the root setting, so that a valid filesystem path is\n returned. Set this flag to disable that behavior.\n* `mark` Add a `/` character to directory matches. Note that this\n requires additional stat calls.\n* `nosort` Don't sort the results.\n* `stat` Set to true to stat *all* results. This reduces performance\n somewhat, and is completely unnecessary, unless `readdir` is presumed\n to be an untrustworthy indicator of file existence.\n* `silent` When an unusual error is encountered when attempting to\n read a directory, a warning will be printed to stderr. Set the\n `silent` option to true to suppress these warnings.\n* `strict` When an unusual error is encountered when attempting to\n read a directory, the process will just continue on in search of\n other matches. Set the `strict` option to raise an error in these\n cases.\n* `cache` See `cache` property above. Pass in a previously generated\n cache object to save some fs calls.\n* `statCache` A cache of results of filesystem information, to prevent\n unnecessary stat calls. While it should not normally be necessary\n to set this, you may pass the statCache from one glob() call to the\n options object of another, if you know that the filesystem will not\n change between calls. (See \"Race Conditions\" below.)\n* `symlinks` A cache of known symbolic links. You may pass in a\n previously generated `symlinks` object to save `lstat` calls when\n resolving `**` matches.\n* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.\n* `nounique` In some cases, brace-expanded patterns can result in the\n same file showing up multiple times in the result set. By default,\n this implementation prevents duplicates in the result set. Set this\n flag to disable that behavior.\n* `nonull` Set to never return an empty set, instead returning a set\n containing the pattern itself. This is the default in glob(3).\n* `debug` Set to enable debug logging in minimatch and glob.\n* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.\n* `noglobstar` Do not match `**` against multiple filenames. (Ie,\n treat it as a normal `*` instead.)\n* `noext` Do not match `+(a|b)` \"extglob\" patterns.\n* `nocase` Perform a case-insensitive match. Note: on\n case-insensitive filesystems, non-magic patterns will match by\n default, since `stat` and `readdir` will not raise errors.\n* `matchBase` Perform a basename-only match if the pattern does not\n contain any slash characters. That is, `*.js` would be treated as\n equivalent to `**/*.js`, matching all js files in all directories.\n* `nonegate` Suppress `negate` behavior. (See below.)\n* `nocomment` Suppress `comment` behavior. (See below.)\n* `nonull` Return the pattern when no matches are found.\n* `nodir` Do not match directories, only files. (Note: to match\n *only* directories, simply put a `/` at the end of the pattern.)\n* `ignore` Add a pattern or an array of patterns to exclude matches.\n* `follow` Follow symlinked directories when expanding `**` patterns.\n Note that this can result in a lot of duplicate references in the\n presence of cyclic links.\n* `realpath` Set to true to call `fs.realpath` on all of the results.\n In the case of a symlink that cannot be resolved, the full absolute\n path to the matched entry is returned (though it will usually be a\n broken symlink)\n\n## Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between node-glob and other\nimplementations, and are intentional.\n\nIf the pattern starts with a `!` character, then it is negated. Set the\n`nonegate` flag to suppress this behavior, and treat leading `!`\ncharacters normally. This is perhaps relevant if you wish to start the\npattern with a negative extglob pattern like `!(a|B)`. Multiple `!`\ncharacters at the start of a pattern will negate the pattern multiple\ntimes.\n\nIf a pattern starts with `#`, then it is treated as a comment, and\nwill not match anything. Use `\\#` to match a literal `#` at the\nstart of a line, or set the `nocomment` flag to suppress this behavior.\n\nThe double-star character `**` is supported by default, unless the\n`noglobstar` flag is set. This is supported in the manner of bsdglob\nand bash 4.3, where `**` only has special significance if it is the only\nthing in a path part. That is, `a/**/b` will match `a/x/y/b`, but\n`a/**b` will not.\n\nNote that symlinked directories are not crawled as part of a `**`,\nthough their contents may match against subsequent portions of the\npattern. This prevents infinite loops and duplicates and the like.\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen glob returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`glob.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`. This is akin to setting the `nullglob` option in bash, except\nthat it does not resolve escaped pattern characters.\n\nIf brace expansion is not disabled, then it is performed before any\nother interpretation of the glob pattern. Thus, a pattern like\n`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded\n**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are\nchecked for validity. Since those two are valid, matching proceeds.\n\n## Windows\n\n**Please only use forward-slashes in glob expressions.**\n\nThough windows uses either `/` or `\\` as its path separator, only `/`\ncharacters are used by this glob implementation. You must use\nforward-slashes **only** in glob expressions. Back-slashes will always\nbe interpreted as escape characters, not path separators.\n\nResults from absolute patterns such as `/foo/*` are mounted onto the\nroot setting using `path.join`. On windows, this will by default result\nin `/foo/*` matching `C:\\foo\\bar.txt`.\n\n## Race Conditions\n\nGlob searching, by its very nature, is susceptible to race conditions,\nsince it relies on directory walking and such.\n\nAs a result, it is possible that a file that exists when glob looks for\nit may have been deleted or modified by the time it returns the result.\n\nAs part of its internal implementation, this program caches all stat\nand readdir calls that it makes, in order to cut down on system\noverhead. However, this also makes it even more susceptible to races,\nespecially if the cache or statCache objects are reused between glob\ncalls.\n\nUsers are thus advised not to use a glob result as a guarantee of\nfilesystem state in the face of rapid changes. For the vast majority\nof operations, this is never a problem.\n\n## Contributing\n\nAny change to behavior (including bugfixes) must come with a test.\n\nPatches that fail tests or reduce performance will be rejected.\n\n```\n# to run tests\nnpm test\n\n# to re-generate test fixtures\nnpm run test-regen\n\n# to benchmark against bash/zsh\nnpm run bench\n\n# to profile javascript\nnpm run prof\n```\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/node-glob/issues" + }, + "homepage": "https://github.com/isaacs/node-glob#readme", + "_id": "glob@4.5.3", + "_shasum": "c6cb73d3226c1efef04de3c56d012f03377ee15f", + "_resolved": "https://registry.npmjs.org/glob/-/glob-4.5.3.tgz", + "_from": "glob@>=4.4.2 <5.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/sync.js new file mode 100644 index 0000000..f4f5e36 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/node_modules/glob/sync.js @@ -0,0 +1,457 @@ +module.exports = globSync +globSync.GlobSync = GlobSync + +var fs = require('fs') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var isAbsolute = common.isAbsolute +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = fs.realpathSync(p, this.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this.matches[index][e] = true + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + var abs = this._makeAbs(e) + if (this.mark) + e = this._mark(e) + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[this._makeAbs(e)] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + // lstat failed, doesn't exist + return null + } + + var isSym = lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTDIR': // totally normal. means it *does* exist. + this.cache[this._makeAbs(f)] = 'FILE' + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) throw er + if (!this.silent) console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this.matches[index][prefix] = true +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + return false + } + + if (lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c !== 'DIR') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/package.json new file mode 100644 index 0000000..842d063 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/package.json @@ -0,0 +1,58 @@ +{ + "name": "rimraf", + "version": "2.3.4", + "main": "rimraf.js", + "description": "A deep deletion module for node (like `rm -rf`)", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/rimraf.git" + }, + "scripts": { + "test": "cd test && bash run.sh" + }, + "bin": { + "rimraf": "./bin.js" + }, + "dependencies": { + "glob": "^4.4.2" + }, + "files": [ + "bin.js", + "rimraf.js", + "LICENSE", + "README.md" + ], + "gitHead": "2a6cc45bbbdd8da5fd703d8af62843565f7dea57", + "bugs": { + "url": "https://github.com/isaacs/rimraf/issues" + }, + "homepage": "https://github.com/isaacs/rimraf#readme", + "_id": "rimraf@2.3.4", + "_shasum": "82d9bc1b2fcf31e205ac7b28138a025d08e9159a", + "_from": "rimraf@>=2.3.2 <2.4.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "82d9bc1b2fcf31e205ac7b28138a025d08e9159a", + "tarball": "http://registry.npmjs.org/rimraf/-/rimraf-2.3.4.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.3.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/rimraf.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/rimraf.js new file mode 100644 index 0000000..7f684e4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/rimraf/rimraf.js @@ -0,0 +1,332 @@ +module.exports = rimraf +rimraf.sync = rimrafSync + +var assert = require("assert") +var path = require("path") +var fs = require("fs") +var glob = require("glob") + +var globOpts = { + nosort: true, + nocomment: true, + nonegate: true, + silent: true +} + +// for EMFILE handling +var timeout = 0 + +var isWindows = (process.platform === "win32") + +function defaults (options) { + var methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(function(m) { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 +} + +function rimraf (p, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + + defaults(options) + + var busyTries = 0 + var errState = null + var n = 0 + + if (!glob.hasMagic(p)) + return afterGlob(null, [p]) + + fs.lstat(p, function (er, stat) { + if (!er) + return afterGlob(null, [p]) + + glob(p, globOpts, afterGlob) + }) + + function next (er) { + errState = errState || er + if (--n === 0) + cb(errState) + } + + function afterGlob (er, results) { + if (er) + return cb(er) + + n = results.length + if (n === 0) + return cb() + + results.forEach(function (p) { + rimraf_(p, options, function CB (er) { + if (er) { + if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") && + busyTries < options.maxBusyTries) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, options, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(function () { + rimraf_(p, options, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + next(er) + }) + }) + } +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, function (er, st) { + if (er && er.code === "ENOENT") + return cb(null) + + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) + + options.unlink(p, function (er) { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) + + options.chmod(p, 666, function (er2) { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, function(er3, stats) { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} + +function fixWinEPERMSync (p, options, er) { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) + + try { + options.chmodSync(p, 666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } + + try { + var stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } + + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} + +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} + +function rmkids(p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return options.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), options, function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + var results + + if (!glob.hasMagic(p)) { + results = [p] + } else { + try { + fs.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, globOpts) + } + } + + if (!results.length) + return + + for (var i = 0; i < results.length; i++) { + var p = results[i] + + try { + var st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er + rmdirSync(p, options, er) + } + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f), options) + }) + options.rmdirSync(p, options) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.npmignore new file mode 100644 index 0000000..534108e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.npmignore @@ -0,0 +1,4 @@ +node_modules/ +coverage/ +.nyc_output/ +nyc_output/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.travis.yml new file mode 100644 index 0000000..991d04b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - 'iojs' diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/Makefile b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/Makefile new file mode 100644 index 0000000..71af0e9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/Makefile @@ -0,0 +1,24 @@ +files = semver.browser.js \ + semver.min.js \ + semver.browser.js.gz \ + semver.min.js.gz + +all: $(files) + +clean: + rm -f $(files) + +semver.browser.js: head.js.txt semver.js foot.js.txt + ( cat head.js.txt; \ + cat semver.js | \ + egrep -v '^ *\/\* nomin \*\/' | \ + perl -pi -e 's/debug\([^\)]+\)//g'; \ + cat foot.js.txt ) > semver.browser.js + +semver.min.js: semver.browser.js + uglifyjs -m semver.min.js + +%.gz: % + gzip --stdout -9 <$< >$@ + +.PHONY: all clean diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/README.md new file mode 100644 index 0000000..b5e35ff --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/README.md @@ -0,0 +1,303 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Usage + + $ npm install semver + + semver.valid('1.2.3') // '1.2.3' + semver.valid('a.b.c') // null + semver.clean(' =v1.2.3 ') // '1.2.3' + semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true + semver.gt('1.2.3', '9.8.7') // false + semver.lt('1.2.3', '9.8.7') // true + +As a command-line utility: + + $ semver -h + + Usage: semver [ [...]] [-r | -i | --preid | -l | -rv] + Test if version(s) satisfy the supplied range(s), and sort them. + + Multiple versions or ranges may be supplied, unless increment + option is specified. In that case, only a single version may + be used, and it is incremented by the specified level + + Program exits successfully if any valid version satisfies + all supplied ranges, and prints all satisfying versions. + + If no versions are valid, or ranges are not satisfied, + then exits failure. + + Versions are printed in ascending order, so supplying + multiple versions to the utility will just sort them. + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +> semver.inc('1.2.3', 'pre', 'beta') +'1.2.4-beta.0' +``` + +command-line example: + +```shell +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```shell +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +## Functions + +All methods and classes take a final `loose` boolean argument that, if +true, will be more forgiving about not-quite-valid semver strings. +The resulting output will always be 100% strict, of course. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/bin/semver b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/bin/semver new file mode 100755 index 0000000..c5f2e85 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/bin/semver @@ -0,0 +1,133 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + , versions = [] + , range = [] + , gt = [] + , lt = [] + , eq = [] + , inc = null + , version = require("../package.json").version + , loose = false + , identifier = undefined + , semver = require("../semver") + , reverse = false + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var i = a.indexOf('=') + if (i !== -1) { + a = a.slice(0, i) + argv.unshift(a.slice(i + 1)) + } + switch (a) { + case "-rv": case "-rev": case "--rev": case "--reverse": + reverse = true + break + case "-l": case "--loose": + loose = true + break + case "-v": case "--version": + versions.push(argv.shift()) + break + case "-i": case "--inc": case "--increment": + switch (argv[0]) { + case "major": case "minor": case "patch": case "prerelease": + case "premajor": case "preminor": case "prepatch": + inc = argv.shift() + break + default: + inc = "patch" + break + } + break + case "--preid": + identifier = argv.shift() + break + case "-r": case "--range": + range.push(argv.shift()) + break + case "-h": case "--help": case "-?": + return help() + default: + versions.push(a) + break + } + } + + versions = versions.filter(function (v) { + return semver.valid(v, loose) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) + return failInc() + + for (var i = 0, l = range.length; i < l ; i ++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], loose) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error("--inc can only be used on a single version with no range") + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? "rcompare" : "compare" + versions.sort(function (a, b) { + return semver[compare](a, b, loose) + }).map(function (v) { + return semver.clean(v, loose) + }).map(function (v) { + return inc ? semver.inc(v, inc, loose, identifier) : v + }).forEach(function (v,i,_) { console.log(v) }) +} + +function help () { + console.log(["SemVer " + version + ,"" + ,"A JavaScript implementation of the http://semver.org/ specification" + ,"Copyright Isaac Z. Schlueter" + ,"" + ,"Usage: semver [options] [ [...]]" + ,"Prints valid versions sorted by SemVer precedence" + ,"" + ,"Options:" + ,"-r --range " + ," Print versions that match the specified range." + ,"" + ,"-i --increment []" + ," Increment a version by the specified level. Level can" + ," be one of: major, minor, patch, premajor, preminor," + ," prepatch, or prerelease. Default level is 'patch'." + ," Only one version may be specified." + ,"" + ,"--preid " + ," Identifier to be used to prefix premajor, preminor," + ," prepatch or prerelease version increments." + ,"" + ,"-l --loose" + ," Interpret versions and ranges loosely" + ,"" + ,"Program exits successfully if any valid version satisfies" + ,"all supplied ranges, and prints all satisfying versions." + ,"" + ,"If no satisfying versions are found, then exits failure." + ,"" + ,"Versions are printed in ascending order, so supplying" + ,"multiple versions to the utility will just sort them." + ].join("\n")) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/foot.js.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/foot.js.txt new file mode 100644 index 0000000..8f83c20 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/foot.js.txt @@ -0,0 +1,6 @@ + +})( + typeof exports === 'object' ? exports : + typeof define === 'function' && define.amd ? {} : + semver = {} +); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/head.js.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/head.js.txt new file mode 100644 index 0000000..6536865 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/head.js.txt @@ -0,0 +1,2 @@ +;(function(exports) { + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/package.json new file mode 100644 index 0000000..936b4c3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/package.json @@ -0,0 +1,54 @@ +{ + "name": "semver", + "version": "4.3.6", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "browser": "semver.browser.js", + "min": "semver.min.js", + "scripts": { + "test": "tap test/*.js", + "prepublish": "make" + }, + "devDependencies": { + "tap": "^1.2.0", + "uglify-js": "~2.3.6" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver" + }, + "gitHead": "63c48296ca5da3ba6a88c743bb8c92effc789811", + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "homepage": "https://github.com/npm/node-semver#readme", + "_id": "semver@4.3.6", + "_shasum": "300bc6e0e86374f7ba61068b5b1ecd57fc6532da", + "_from": "semver@>=4.3.3 <4.4.0", + "_npmVersion": "2.10.1", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "300bc6e0e86374f7ba61068b5b1ecd57fc6532da", + "tarball": "http://registry.npmjs.org/semver/-/semver-4.3.6.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/semver/-/semver-4.3.6.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js new file mode 100644 index 0000000..4b0cfec --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js @@ -0,0 +1,1201 @@ +;(function(exports) { + +// export the class if we are in a Node-like system. +if (typeof module === 'object' && module.exports === exports) + exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + ; + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + ; + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.inspect = function() { + return ''; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + ; + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + ; + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(b); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + ; + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + ; +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.inspect = function() { + return ''; +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + ; + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + + +exports.Range = Range; +function Range(range, loose) { + if ((range instanceof Range) && range.loose === loose) + return range; + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.inspect = function() { + return ''; +}; + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + ; + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + ; + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + ; + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + ; + comp = replaceCarets(comp, loose); + ; + comp = replaceTildes(comp, loose); + ; + comp = replaceXRanges(comp, loose); + ; + comp = replaceStars(comp, loose); + ; + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + ; + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0- <1.3.0- + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + ; + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + ; + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + ; + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + ; + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + ; + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + ; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + ; + return ret; + }); +} + +function replaceXRanges(comp, loose) { + ; + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + ; + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) + M = +M + 1 + else + m = +m + 1 + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + ; + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + ; + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + ; + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return rcompare(a, b, loose); + })[0] || null; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +// Use the define() function if we're in AMD land +if (typeof define === 'function' && define.amd) + define(exports); + +})( + typeof exports === 'object' ? exports : + typeof define === 'function' && define.amd ? {} : + semver = {} +); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js.gz b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.browser.js.gz new file mode 100644 index 0000000000000000000000000000000000000000..d67009d8ad2cd540874578704d097e4ffefd47d7 GIT binary patch literal 7992 zcmV-8AIIPyiwFQ;=V(;|1KmAqR~tvN-}x17)+dsTBnuqh-53OiBqZ@Y2KxZn<6Rr# zku->jM>ERIh(`kc?YAENo`;0v?4EP)-B_p})z$Ut>gwv&cKc$HjEg8u+TqPS&5FDu z{#aXk`c&{&QCx;%90z$Wq6={yiXaO`l!!narIWB1M;}9x-{wU)>#sqBc5yoo(+e?6 zCyO`~!{Jc0($TNsxM+#5zLLd#ITBT?QP+gf#ie%QB%J*-%(e-!Q^05vjuum)P!~}S zoyYNF5>7;z6j2t&x8fp8XN3MNN}`Jhs;D8 z9Q^X~==9*ngJY;WTFgd(d#UE`PJA;M{C)GAZ?>L){r9g2-+Z%as2GfkMG%WDoB~d{ zn5F`dRp@0QjRou;T4nI%-5Fz%XJf01zo|MzXW%u+Flrodjt6;K)73Mz(1vlM1d z)d(Lac=Yq(!ST!QUVeXYbo%m#m&AkPjg9R!pu@XT?%MFa#y z0JteYP>^&dO`O+9&Gf0Lr#T^Q-UYqi_j~{Doyk97n!U3p);tdbus{D~uCst;AxtYR zdU*)45fm^dMTbb!LE(0||MJLan?}hhCQRBbu_0=BxglDe_wW1A0*qGa|NhFZ#w=)T zOCsafEt!sN(~Q_M?7lRR*0y5yn=I^sH4lS4R6H+fbeY+fW|u3aAiOy~I6ioFuzzw; zEu>ZTOv}9&O>C;2I!*shcdgU`o5@uOl(=2nXep|S+>Q7?2icSa@~ZS21|}X1 zeUF#2D!j1pO}xlq<(@Xk&m7b|ome6?A}BKpN?CdcsS=ioGwA^F%j2mpe?&aTTvTY_;gFBbG|nx%_*-WTNfxrm^noq)eg z%ml;< zYESXTS?kMs<=YS7++M4uofH>p0-VJn9Fzp;9LF;#K%2)>#A(-b0qloKFMu4#;9Oj7 z_P6@ai2g(Rvn#GIqwyt3b_zQVFpwfoft1lK1n~thL7b;uv5EVIAf8_ao1zVjQ+&IQ z3ZNo$o0YU9;Q<$*T~XXhBF=CJl~BWEKEv%m1f0F?6Aj6BXd=G58oqy@gF99xWxbuM zw0(6{ts<+&!`4(|Ly6E9o{G}g?Z?wsr*<#=&gu>Nx^uVN*&FUDi+F<6y+ny52CZ-P zpRA*KSx0W%toL0lTEBrZq-DT66mfGLB(Uj|Mh2abSr{Y;Zan~7Dg}2Pp}bDyPVpkj za@F1 z3(YC4zM;s_F7c9aC@m5goAnHq3GgRIU~j;jft{N|2?hbcyn&fwqkD943bgVJuPjt< z(x=@$?fz25>G8`$yN5319*BNN;cr3XnV}z;g>IiDyvE4U!Ogtw!t09GwAEp97C70{ zESepM^Een|sH*jN^OJ*F2`iVv4l+%wqedmpnbOt4mYMb)_)|q4(|}XBycgsqjDqpU z>mZxt>l&%i8%smV+Vt`moi>Gn%H2h7FOF?_3Ul+i*^>tCC;BQT$ zF=(6T8xVG{58vz`@1MRdFZ5njgL!C|eWK3eyK_we4X7IYGRTfws{r%-DS|9xyEs#H zYUToG3EpQB=5u83C@ikSkbTZ+5f>`j$i$+(T7jnkxLJdJW}dRo^MW+n&ue3&t_(S2IaRcXfq0F z|8NA!Xpfa3B>- zLG1~WF`l0C$(9rU$YGY*p}kYv|7Uaam! z2Y@gm*55rOgcP0^_&0?*48i(f-3v8Hry63B-O|iW4bYV5>r)5;--BOJj4wqS$l>)P zh|t330B^*Hydk$ZK;J7lfHS;OJgdS$(H~}i)mP+xA%};d_1I(Z%MyS@pVrv)y>{%} zAG;4soV7dsj17AG>G`|i)!D{VF#WAg1!6fMmRBLBkD2+H)H*}gs8!Q_1<91GaAb-^ z1W)uCiZm;}_+nWY=b@}tLk#uVyw&oaS}qlLiA-^sff+(^I)%muS(aw)*2{!NLWWsi z2sDRELRoxP)s0H{nnXEF8;m1wo@f;7=pHOBtdp?xjWKKv3aV75&FKdv`gT^;5NWUw zjN$;-ZAq?-TZ~7u&Sw)>;gto~1_>(WFmlexBy8znF-a(eAy?ff zI1L>)X74u7^du=(&81tWltR~B`s~cuNCRe9RAok34R*v}g_&|&ITgc43$vzysKJT@ zQQPW)c(M%xaf8(c;VJ?kau67sey2C)0opiEPXFGz|Q@A z9!EvH)o-C}&P_s6G*P_;Y2BM@zibhV> z0w_%eo+EWN=F$>fur74$WC@v5L@eHRBuKMBnmdbsYKRT6uss9A^!PQ65}K8@2-!Vh zTH6)#0wXsEAFezx38J+l7piqND9&Piw^akLNcqUD7T^jv@rER{L8Q2Q@jO8;tToeI zJGAXI6?HAM%%WmrCdbBP7B#5SUs?4g3uR3+`jih-J%zsneL1W-EzT`V+hutC1*c>b ztF|8>KgxdiWwn0typsFTmnDRHQ_JcvODEh@zdnU+{}t_rZ2JjPy{jtHBy3blv{sMg z?5Y)3GNiYutSnEY9^5L>RtB~bZUeoK;QbbSnWWNaV`-plnE?a)s%>3Af_i@(-C$dL zp#gcGi)0dBL!7i9ue$k2H5;cO$jKrsdBgPz7IdLI z`^49mxJ7PnY(!GrLEL~gZ1}Gu49qNMbLX6XF~==6o$rP>g>)_?G5Nqhn$5yV1bgO~ z4uvP_HO20%Jb*q8LJN+}5MbBgI?XxHCNjbsiLZ$018EmeM`SBe8*u)-<>gvMiOyAq zq1uF0>v6@ds8U&7(@{x!duLcfdb`Oo(qmhP^jkjZw_MV1^*8O>XJyj=2{KohyFW+J zCeuf$XjN%+#{L;X@x2bMzzSAW7}jVf&o-VOZ=C&h1>LDWtfTzEuiyMUvq4aNIxnRt z<=Rv7SURG#0Z!9PT7^!~n=eLjG>&ikYqlzjbpXB&t^y|YjY9BmLaE~elahucy3SH? zj3-gXIftID{9GgH&TOEkM*f)_KZwfisD!+&+ertk*NZ5qV22=_*nHWo<@-<^Txq%e zL`8GMAPF0g>uuR(_iN?95QB(D>TPytg^q|tMwHc2&06i?{rMulY!CDrac>dcciKD= z9)(5VS_oab)valMk*1^gcRVOGg_RHn&MbY34Vb{y2ukGhqu{92ar3OxY2pQnjeWVm zh>!|WuYE?}`-%k^HWa}kE{yM}LU%H37s;@l#msEFz&|+psyt^7ZI=R0P6&c`59*kJ zeRTNOI=Vo|L7PPF8`4gLa5-i-c#w|`~yym$kVCXUAU(T z4?0qsL>Cu;7k*fj!LMrc&91WNTZR(hZ&lTG1KOsDPNX*dW1-EC*%M!F`L$aevlYJD ztT2nP3}08&(5iKH_rcOv(`0G6Wxc*s~Plz9j$ zKtB{FT5cak)`S-Hd1Sy5bP0yz>_JDJCXFg;N9MGMI%DVsKGnQ2z_StXY%!R#G18hX ziJ`ka;(mLuaETX&Xzh`z4`jVl9f%zO>~{*pE|ofk1Lt5gtE6mJMOsb2tdW5A@taXs z1a7i`I^LpBYXtg^Fs;Mbvf9+8S`*(>oWvPIablq*Y^DkP|OIvR5j8FSEU z!O!tp{!rkD1sA`zV~VkqVPZM;Gly$tTDp}-BnLxMT5p~bk<7y+`+}%sE8;RmM5ZZPuwjst3gt+5D41dGx^1oRS!AW=!MB3aqFcSirI8c*^f_+p1J1s(@ zXXp?#d>}=KC6ZElf&(>vDAXMv>KHcJpvkkjt-!N6_DbhIWPZ`0*tUYr>D-Mo1Cia0 zChz6~=P`>8t!qKw$!l@ikG%G{_Kp1ZnCLx}phvYaj7R?kj2<;&)Ow+aW&XlHxwj{O z+f_5tjg#fAcXeY=sjJ!!t;XT9);qd!ycF`z&}!TOS#9B(^DfePNSUy_Z37upJ2ol% zB&3#V|aYGxCU{r*Tw39p-<5fKWa$=sSjjS}lHl#7!^m zo3x`XJMBpE7fD}cq^`AmMFilT-D5nYl3^<+uUKkYoySrMe#KlCR;zj_up6@>s7ySW z%(6@y)KD1?Qk`WyEM*y+grusdOkDyAtj=y5B_CazT@}pH=8&)24h4N$Mv%U@DNns* z0J+#ULe#p0TT7~{wtLDT^GLM@jbW8+Sp`Byn>-uFYViYJ3GNEY9>Y|7y!oGqQJPYI zF$fmr##ot^5;HC8g({O7XiqW6{to^>fAZAJu*;YLj_YmgsD-=C9pzPu8Pn-sM6eKM z2HIFbqWn%YGI;+S&xYwdSf2NqV_po&Ttf|A@#ou!HX>sy@_uibF*QvuhSg}+q%ZU#m+VYKIq1rzf6j{p0>k5w9mQ6K`N7ZdZN{lykj!T z;=4Pi+-AKLrz$*Gvr`QKj95AOAVvyt1yfpKRD@8Jy=-yZmJR{Pn|H5C(Dg8WMgg`A z^0E`dzw~Z2l&|N!@QTmM2&nY@OE6RXx`MocsH_S zk|W9?Kj|BCFw`e`L9Ss8`!212gI1@reK@zFo-c=L-|_Tsc50{zihUgYj_>P1d0qmj z?bpWBj*(~8ec#R!>C*Y3wD5c%HV!eJNua3A@Gej?S(9ldn2%DVcxcI17W$_aZSip! z78NWz4qb6s*%K>UV$#Nv`g+<+I#TNbTRM!uYzjHfn6>t?vz5p>%+g8NZ8FckAIKRj zJQ*}UC97{uK~Lh*Bg+S6Dt1iPH1Bi_$YmsH+!W}=L0yQUofGH99j1AquBp+>g5V-i zPG&L@aX1aew_^XzOS$&s+Pf%HGaAN(o$r>n;gnZ+9nF3~f0e0AGR`YjS!HFrGL2#f2H+Kb>S?Q9nKq)UGSx&PjXc>t)BU<2CCJd3YG~! z*K*pAExPIX@hUH%`VGpyE(glYnid%l6avD&OEs?Yi`&0Q@?b@VOPw$0tT7u z=#Du*rr6S&Nr`ydKJ0Xy_+P8#WiVr-ncrx4NcY_6wh0LWer<1H!DdI5RzaF;NRqc8 z*ovP$$KkF?j0^G3UK4vK$HR^YtJ#+;K@ zpI6uv(}ax3d4&zxvYYs(!>t@t_4IYKViEb07K6Y)++viw={2yzYS?d>ywC;zZ>)xs zv2n=D;lNVWFJLT$o6ofh#2V!9{}RLF&fLpCnUzWMxu&YpP|Pga&1udijm1lY`+}p^ z@ag^moN5@bwF(ofnD^zm@E>Quf0FhOBm2@N$hVVK4!gFLw(a{I+s(iqZoDh{5q$f! z%!INk?D^YLSn916ky>KWp}tF7wRjeuIYYHPNfNzKHG& zEGa9gw-4kZ%|_8=5+**FCoMON*Ru75o|>kHOmQcEqUkL^NMm1{xS1JKF|+SFQ03fO z66EhHR8z;J#_lGD>!eHNR-ntx4$-r675bW3$+1*jt9S)kzU|n%o0*&Bh~mU*ZD(#e z^RnjRCQ_>zI{@iU|I7#I_g^c)u_R^a6K7{Q=>HvDO1`qiFHnGR`~w|QzNChcF>b^6 z9PHlnAjc<;Poh~A2U!dr@XoLV?H@?@t_X{9zeL2HmQTV;0@fLKLlG^8j+aHl)R^Lu zcVhGJGn}*<#(e=_Os@isJCSeYyJSz0`uj)U_reKl7@jN1N2wS?es9i1o#^L9Fuv7l z(ObQ_`x;-D1BY2S!&juR>yupnyiC7j?8|{5z5c*3luVf5GgWwQI8D+F(7X(@5X1;0 zZEUlygIoB>5#^@dXai6VLiz_n#|cLc6OW70DKKCIbadi)a1k@PQA^W78YHEj39U zpydvR;Ld?d`|+S#_l6n%1Q0BUFqaGboa2AELXK*C6lqr!(7u57#T@^`b7)FWTr)eL z3$^v3-x#u!M@*BM*Mt?};?U6^x68b#3;j8>^h28juQ`0%wvjCqvcULCREwF@K|54QH3 zViM+yDXa?ES%#*#V#oMoWT^xFn+Kfk^g*}X`almcpueG-{{;9@ehjtxx<`-y_rYzY zvzQMG623t)()f2(Z|I8aV7i!If|R#%S}Wz!$mgd>iqWmNR?6WYz&LleEIC+}dE~x{ zQP-#9R@1I~`;s;wl3R4JXga$Nt8Aq1U<}O@XRQqB< zP((RCxQo9I#TyjKY}=8OLnW?h<` zVID}{vCM0F(xN;!uq`NO;3})vm_dNha-dI(ufP}sMV==)b)08FnVv07m*eCDaI(SC zT_IIYCO^SU<&JyB%bS41_aSf!^ppGz`<6 zb9*6c(glfHx+wB!5|&zm%j8_}X~5ckntw&a`_^rajJAZCbDQH&VZPg{yqYB237f&Ge*Kk#4Pq=hPzU0nr1RNTuTyZYhT7fE+vo9xq#kR#iV!IAnuud6KeeRD7Yoeb+x8eu5la8bLT>U~R%w#>r z&Pu%db#AxJ|FT>pe7VcI>pgZ-jdXK*NqJVSff|ML6S*{5ylk~Lu*#4%(8eQ1DsKq-mh-3V$5^rm%jS8M0 z={?Q|QB=#BS!&hP+K-S2dIXq~^IgrgV|(6Y80}?3F|pG)Z%Z8fA=qes^%WV|heLLK zSM6*AX?~VJuD~x{v^!Ri&N5E>hu@1BlUA+x0QcbVfa*kNDqPVIX7m=J1gw5q8$|NH u(?<7>q1Zpat$&?+PZz&1Ems&1I{tA_ee@-pKknCH%>M%jFB%A1d;kFdn5hB) literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.js new file mode 100644 index 0000000..cafcc00 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.js @@ -0,0 +1,1205 @@ +// export the class if we are in a Node-like system. +if (typeof module === 'object' && module.exports === exports) + exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.inspect = function() { + return ''; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(b); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.inspect = function() { + return ''; +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + + +exports.Range = Range; +function Range(range, loose) { + if ((range instanceof Range) && range.loose === loose) + return range; + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.inspect = function() { + return ''; +}; + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0- <1.3.0- + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) + M = +M + 1 + else + m = +m + 1 + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return rcompare(a, b, loose); + })[0] || null; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +// Use the define() function if we're in AMD land +if (typeof define === 'function' && define.amd) + define(exports); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js new file mode 100644 index 0000000..dea027b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js @@ -0,0 +1 @@ +(function(e){if(typeof module==="object"&&module.exports===e)e=module.exports=K;e.SEMVER_SPEC_VERSION="2.0.0";var r=256;var t=Number.MAX_SAFE_INTEGER||9007199254740991;var n=e.re=[];var i=e.src=[];var s=0;var o=s++;i[o]="0|[1-9]\\d*";var a=s++;i[a]="[0-9]+";var f=s++;i[f]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var u=s++;i[u]="("+i[o]+")\\."+"("+i[o]+")\\."+"("+i[o]+")";var l=s++;i[l]="("+i[a]+")\\."+"("+i[a]+")\\."+"("+i[a]+")";var p=s++;i[p]="(?:"+i[o]+"|"+i[f]+")";var c=s++;i[c]="(?:"+i[a]+"|"+i[f]+")";var h=s++;i[h]="(?:-("+i[p]+"(?:\\."+i[p]+")*))";var v=s++;i[v]="(?:-?("+i[c]+"(?:\\."+i[c]+")*))";var m=s++;i[m]="[0-9A-Za-z-]+";var g=s++;i[g]="(?:\\+("+i[m]+"(?:\\."+i[m]+")*))";var w=s++;var y="v?"+i[u]+i[h]+"?"+i[g]+"?";i[w]="^"+y+"$";var d="[v=\\s]*"+i[l]+i[v]+"?"+i[g]+"?";var j=s++;i[j]="^"+d+"$";var b=s++;i[b]="((?:<|>)?=?)";var E=s++;i[E]=i[a]+"|x|X|\\*";var $=s++;i[$]=i[o]+"|x|X|\\*";var k=s++;i[k]="[v=\\s]*("+i[$]+")"+"(?:\\.("+i[$]+")"+"(?:\\.("+i[$]+")"+"(?:"+i[h]+")?"+i[g]+"?"+")?)?";var R=s++;i[R]="[v=\\s]*("+i[E]+")"+"(?:\\.("+i[E]+")"+"(?:\\.("+i[E]+")"+"(?:"+i[v]+")?"+i[g]+"?"+")?)?";var S=s++;i[S]="^"+i[b]+"\\s*"+i[k]+"$";var x=s++;i[x]="^"+i[b]+"\\s*"+i[R]+"$";var I=s++;i[I]="(?:~>?)";var T=s++;i[T]="(\\s*)"+i[I]+"\\s+";n[T]=new RegExp(i[T],"g");var V="$1~";var A=s++;i[A]="^"+i[I]+i[k]+"$";var C=s++;i[C]="^"+i[I]+i[R]+"$";var M=s++;i[M]="(?:\\^)";var N=s++;i[N]="(\\s*)"+i[M]+"\\s+";n[N]=new RegExp(i[N],"g");var _="$1^";var z=s++;i[z]="^"+i[M]+i[k]+"$";var P=s++;i[P]="^"+i[M]+i[R]+"$";var X=s++;i[X]="^"+i[b]+"\\s*("+d+")$|^$";var Z=s++;i[Z]="^"+i[b]+"\\s*("+y+")$|^$";var q=s++;i[q]="(\\s*)"+i[b]+"\\s*("+d+"|"+i[k]+")";n[q]=new RegExp(i[q],"g");var L="$1$2$3";var F=s++;i[F]="^\\s*("+i[k]+")"+"\\s+-\\s+"+"("+i[k]+")"+"\\s*$";var G=s++;i[G]="^\\s*("+i[R]+")"+"\\s+-\\s+"+"("+i[R]+")"+"\\s*$";var O=s++;i[O]="(<|>)?=?\\s*\\*";for(var B=0;Br)return null;var i=t?n[j]:n[w];if(!i.test(e))return null;try{return new K(e,t)}catch(s){return null}}e.valid=H;function H(e,r){var t=D(e,r);return t?t.version:null}e.clean=J;function J(e,r){var t=D(e.trim().replace(/^[=v]+/,""),r);return t?t.version:null}e.SemVer=K;function K(e,i){if(e instanceof K){if(e.loose===i)return e;else e=e.version}else if(typeof e!=="string"){throw new TypeError("Invalid Version: "+e)}if(e.length>r)throw new TypeError("version is longer than "+r+" characters");if(!(this instanceof K))return new K(e,i);this.loose=i;var s=e.trim().match(i?n[j]:n[w]);if(!s)throw new TypeError("Invalid Version: "+e);this.raw=e;this.major=+s[1];this.minor=+s[2];this.patch=+s[3];if(this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");if(!s[4])this.prerelease=[];else this.prerelease=s[4].split(".").map(function(e){if(/^[0-9]+$/.test(e)){var r=+e;if(r>=0&&r'};K.prototype.toString=function(){return this.version};K.prototype.compare=function(e){if(!(e instanceof K))e=new K(e,this.loose);return this.compareMain(e)||this.comparePre(e)};K.prototype.compareMain=function(e){if(!(e instanceof K))e=new K(e,this.loose);return Y(this.major,e.major)||Y(this.minor,e.minor)||Y(this.patch,e.patch)};K.prototype.comparePre=function(e){if(!(e instanceof K))e=new K(e,this.loose);if(this.prerelease.length&&!e.prerelease.length)return-1;else if(!this.prerelease.length&&e.prerelease.length)return 1;else if(!this.prerelease.length&&!e.prerelease.length)return 0;var r=0;do{var t=this.prerelease[r];var n=e.prerelease[r];if(t===undefined&&n===undefined)return 0;else if(n===undefined)return 1;else if(t===undefined)return-1;else if(t===n)continue;else return Y(t,n)}while(++r)};K.prototype.inc=function(e,r){switch(e){case"premajor":this.prerelease.length=0;this.patch=0;this.minor=0;this.major++;this.inc("pre",r);break;case"preminor":this.prerelease.length=0;this.patch=0;this.minor++;this.inc("pre",r);break;case"prepatch":this.prerelease.length=0;this.inc("patch",r);this.inc("pre",r);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",r);this.inc("pre",r);break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0;this.patch=0;this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0;this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":if(this.prerelease.length===0)this.prerelease=[0];else{var t=this.prerelease.length;while(--t>=0){if(typeof this.prerelease[t]==="number"){this.prerelease[t]++;t=-2}}if(t===-1)this.prerelease.push(0)}if(r){if(this.prerelease[0]===r){if(isNaN(this.prerelease[1]))this.prerelease=[r,0]}else this.prerelease=[r,0]}break;default:throw new Error("invalid increment argument: "+e)}this.format();return this};e.inc=Q;function Q(e,r,t,n){if(typeof t==="string"){n=t;t=undefined}try{return new K(e,t).inc(r,n).version}catch(i){return null}}e.diff=U;function U(e,r){if(pr(e,r)){return null}else{var t=D(e);var n=D(r);if(t.prerelease.length||n.prerelease.length){for(var i in t){if(i==="major"||i==="minor"||i==="patch"){if(t[i]!==n[i]){return"pre"+i}}}return"prerelease"}for(var i in t){if(i==="major"||i==="minor"||i==="patch"){if(t[i]!==n[i]){return i}}}}}e.compareIdentifiers=Y;var W=/^[0-9]+$/;function Y(e,r){var t=W.test(e);var n=W.test(r);if(t&&n){e=+e;r=+r}return t&&!n?-1:n&&!t?1:er?1:0}e.rcompareIdentifiers=er;function er(e,r){return Y(r,e)}e.major=rr;function rr(e,r){return new K(e,r).major}e.minor=tr;function tr(e,r){return new K(e,r).minor}e.patch=nr;function nr(e,r){return new K(e,r).patch}e.compare=ir;function ir(e,r,t){return new K(e,t).compare(r)}e.compareLoose=sr;function sr(e,r){return ir(e,r,true)}e.rcompare=or;function or(e,r,t){return ir(r,e,t)}e.sort=ar;function ar(r,t){return r.sort(function(r,n){return e.compare(r,n,t)})}e.rsort=fr;function fr(r,t){return r.sort(function(r,n){return e.rcompare(r,n,t)})}e.gt=ur;function ur(e,r,t){return ir(e,r,t)>0}e.lt=lr;function lr(e,r,t){return ir(e,r,t)<0}e.eq=pr;function pr(e,r,t){return ir(e,r,t)===0}e.neq=cr;function cr(e,r,t){return ir(e,r,t)!==0}e.gte=hr;function hr(e,r,t){return ir(e,r,t)>=0}e.lte=vr;function vr(e,r,t){return ir(e,r,t)<=0}e.cmp=mr;function mr(e,r,t,n){var i;switch(r){case"===":if(typeof e==="object")e=e.version;if(typeof t==="object")t=t.version;i=e===t;break;case"!==":if(typeof e==="object")e=e.version;if(typeof t==="object")t=t.version;i=e!==t;break;case"":case"=":case"==":i=pr(e,t,n);break;case"!=":i=cr(e,t,n);break;case">":i=ur(e,t,n);break;case">=":i=hr(e,t,n);break;case"<":i=lr(e,t,n);break;case"<=":i=vr(e,t,n);break;default:throw new TypeError("Invalid operator: "+r)}return i}e.Comparator=gr;function gr(e,r){if(e instanceof gr){if(e.loose===r)return e;else e=e.value}if(!(this instanceof gr))return new gr(e,r);this.loose=r;this.parse(e);if(this.semver===wr)this.value="";else this.value=this.operator+this.semver.version}var wr={};gr.prototype.parse=function(e){var r=this.loose?n[X]:n[Z];var t=e.match(r);if(!t)throw new TypeError("Invalid comparator: "+e);this.operator=t[1];if(this.operator==="=")this.operator="";if(!t[2])this.semver=wr;else this.semver=new K(t[2],this.loose)};gr.prototype.inspect=function(){return''};gr.prototype.toString=function(){return this.value};gr.prototype.test=function(e){if(this.semver===wr)return true;if(typeof e==="string")e=new K(e,this.loose);return mr(e,this.operator,this.semver,this.loose)};e.Range=yr;function yr(e,r){if(e instanceof yr&&e.loose===r)return e;if(!(this instanceof yr))return new yr(e,r);this.loose=r;this.raw=e;this.set=e.split(/\s*\|\|\s*/).map(function(e){return this.parseRange(e.trim())},this).filter(function(e){return e.length});if(!this.set.length){throw new TypeError("Invalid SemVer Range: "+e)}this.format()}yr.prototype.inspect=function(){return''};yr.prototype.format=function(){this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim();return this.range};yr.prototype.toString=function(){return this.range};yr.prototype.parseRange=function(e){var r=this.loose;e=e.trim();var t=r?n[G]:n[F];e=e.replace(t,Tr);e=e.replace(n[q],L);e=e.replace(n[T],V);e=e.replace(n[N],_);e=e.split(/\s+/).join(" ");var i=r?n[X]:n[Z];var s=e.split(" ").map(function(e){return jr(e,r)}).join(" ").split(/\s+/);if(this.loose){s=s.filter(function(e){return!!e.match(i)})}s=s.map(function(e){return new gr(e,r)});return s};e.toComparators=dr;function dr(e,r){return new yr(e,r).set.map(function(e){return e.map(function(e){return e.value}).join(" ").trim().split(" ")})}function jr(e,r){e=kr(e,r);e=Er(e,r);e=Sr(e,r);e=Ir(e,r);return e}function br(e){return!e||e.toLowerCase()==="x"||e==="*"}function Er(e,r){return e.trim().split(/\s+/).map(function(e){return $r(e,r)}).join(" ")}function $r(e,r){var t=r?n[C]:n[A];return e.replace(t,function(e,r,t,n,i){var s;if(br(r))s="";else if(br(t))s=">="+r+".0.0 <"+(+r+1)+".0.0";else if(br(n))s=">="+r+"."+t+".0 <"+r+"."+(+t+1)+".0";else if(i){if(i.charAt(0)!=="-")i="-"+i;s=">="+r+"."+t+"."+n+i+" <"+r+"."+(+t+1)+".0"}else s=">="+r+"."+t+"."+n+" <"+r+"."+(+t+1)+".0";return s})}function kr(e,r){return e.trim().split(/\s+/).map(function(e){return Rr(e,r)}).join(" ")}function Rr(e,r){var t=r?n[P]:n[z];return e.replace(t,function(e,r,t,n,i){var s;if(br(r))s="";else if(br(t))s=">="+r+".0.0 <"+(+r+1)+".0.0";else if(br(n)){if(r==="0")s=">="+r+"."+t+".0 <"+r+"."+(+t+1)+".0";else s=">="+r+"."+t+".0 <"+(+r+1)+".0.0"}else if(i){if(i.charAt(0)!=="-")i="-"+i;if(r==="0"){if(t==="0")s=">="+r+"."+t+"."+n+i+" <"+r+"."+t+"."+(+n+1);else s=">="+r+"."+t+"."+n+i+" <"+r+"."+(+t+1)+".0"}else s=">="+r+"."+t+"."+n+i+" <"+(+r+1)+".0.0"}else{if(r==="0"){if(t==="0")s=">="+r+"."+t+"."+n+" <"+r+"."+t+"."+(+n+1);else s=">="+r+"."+t+"."+n+" <"+r+"."+(+t+1)+".0"}else s=">="+r+"."+t+"."+n+" <"+(+r+1)+".0.0"}return s})}function Sr(e,r){return e.split(/\s+/).map(function(e){return xr(e,r)}).join(" ")}function xr(e,r){e=e.trim();var t=r?n[x]:n[S];return e.replace(t,function(e,r,t,n,i,s){var o=br(t);var a=o||br(n);var f=a||br(i);var u=f;if(r==="="&&u)r="";if(o){if(r===">"||r==="<"){e="<0.0.0"}else{e="*"}}else if(r&&u){if(a)n=0;if(f)i=0;if(r===">"){r=">=";if(a){t=+t+1;n=0;i=0}else if(f){n=+n+1;i=0}}else if(r==="<="){r="<";if(a)t=+t+1;else n=+n+1}e=r+t+"."+n+"."+i}else if(a){e=">="+t+".0.0 <"+(+t+1)+".0.0"}else if(f){e=">="+t+"."+n+".0 <"+t+"."+(+n+1)+".0"}return e})}function Ir(e,r){return e.trim().replace(n[O],"")}function Tr(e,r,t,n,i,s,o,a,f,u,l,p,c){if(br(t))r="";else if(br(n))r=">="+t+".0.0";else if(br(i))r=">="+t+"."+n+".0";else r=">="+r;if(br(f))a="";else if(br(u))a="<"+(+f+1)+".0.0";else if(br(l))a="<"+f+"."+(+u+1)+".0";else if(p)a="<="+f+"."+u+"."+l+"-"+p;else a="<="+a;return(r+" "+a).trim()}yr.prototype.test=function(e){if(!e)return false;if(typeof e==="string")e=new K(e,this.loose);for(var r=0;r0){var n=e[t].semver;if(n.major===r.major&&n.minor===r.minor&&n.patch===r.patch)return true}}return false}return true}e.satisfies=Ar;function Ar(e,r,t){try{r=new yr(r,t)}catch(n){return false}return r.test(e)}e.maxSatisfying=Cr;function Cr(e,r,t){return e.filter(function(e){return Ar(e,r,t)}).sort(function(e,r){return or(e,r,t)})[0]||null}e.validRange=Mr;function Mr(e,r){try{return new yr(e,r).range||"*"}catch(t){return null}}e.ltr=Nr;function Nr(e,r,t){return zr(e,r,"<",t)}e.gtr=_r;function _r(e,r,t){return zr(e,r,">",t)}e.outside=zr;function zr(e,r,t,n){e=new K(e,n);r=new yr(r,n);var i,s,o,a,f;switch(t){case">":i=ur;s=vr;o=lr;a=">";f=">=";break;case"<":i=lr;s=hr;o=ur;a="<";f="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ar(e,r,n)){return false}for(var u=0;u=0.0.0")}p=p||e;c=c||e;if(i(e.semver,p.semver,n)){p=e}else if(o(e.semver,c.semver,n)){c=e}});if(p.operator===a||p.operator===f){return false}if((!c.operator||c.operator===a)&&s(e,c.semver)){return false}else if(c.operator===f&&o(e,c.semver)){return false}}return true}if(typeof define==="function"&&define.amd)define(e)})(typeof exports==="object"?exports:typeof define==="function"&&define.amd?{}:semver={}); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js.gz b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/semver.min.js.gz new file mode 100644 index 0000000000000000000000000000000000000000..cbbc16188002f2ca4bd733d2b9cdc3c4c79a0f7e GIT binary patch literal 3790 zcmV;<4l(f`iwFQ<=V(;|1H~H+bJMu;uOyyMh;b6q-rc*QiP|Zpa6M?@T8;zK&@ri! z8WKCmPCrO|zy0k>YfEyRw7q*XZ+Fh+peK-pTNf3o~?#_c@J-MCoXjqv< z7qc;Ej5*PluY8a=wVIl0@tbKRk{Fh_%UNOaRfo4u502g+oSdJ&J=i~ohttD1$IRJk zwOehcbLESQU|YZZM?NL&csBXMMeAtq!};mni-YsS<97!y4^9?~r|tHyn@^u^{qpm# zKewMg-IVYl<1N8iuP;XdjAAj!hB0f)--yMY*9m%2pE>PCZ?pNde|C29Snci8q7RF` zHY|B+en|5}m`CWI-~6%H{M78z1AsRBL}NyqvdaX&81YvhBR2Fkb6uyqz%`Q3r8-AcS1Xz z6n8pUCcA#hAqB45>6CUlRf{|c^ zlSc$_l=<{$V)B?4jx8pS3?`2YOdcCdo+Fc=6{R0U=|{%HQGv;~1n|}ZFqr&603V7P zuS@)JRRDuKMUAiopjcS}B-@FKIki}HRi$ot)p_chA9v9In1q(#T$$KuKF3D-5C_$N$=Sp)?6l2{J zXr=RU%qtwK4WgaOi4~@pCzm3+mP&gE%LhV$Z#ajcR8i$UaaVCX?xwb>N)c(xN)T7Z zQ8?nDkV`)Vbm2Lb!KE+!K>{FfZqSzX1tVCpFeivRLR*x4oVX2~;7KDV6B` zG$|b2NeY2VNJ&m}QgU<`DG6kgs>Z#a`>rA(xZvRbv8-#QXBFoWxD`*wK~i^G4%%p1 zFI4StAY?VW@gzUZb5(15GH8e$)~?k=H_6;Vq?voCWUw!@V0;04{nFpXKgNdJJu(x7 zIq;9Vo4x|}q9j89r%9GGgeL%CNnWO{=K(EGTR;z`g0zNn!RctYCOwZi%?wQgevN`q zvYJN%110U4?84!g!hOc%SK&PBs#sBR9!dJ%BWLH4jhjTL@{}(lui0=AO(4*7RK7RJXq+#c#$P=x?b_h# zx16=N|6DOE{iRl`@)9pnk~B9vS@f>1LSKztxd--|%`0uX0Jl3A5oNamnV#t9S6zD+ z<%PU73orOE2>C^=7Mer7MaE(2vKAmIS#H|Pp*x7eBnW4e1GO_WLN~p>492|fdBQE8 zuz_Jy%;WKOfLR6XI{;xEkV`s{vt6!3P>+!n+GfsZ8yN-4F*$(!>PXYUO5ls&{s@>52Q9#w5^IDZTux6J|#pq-HaLByINKilHIt zV?QpGEi;GGthJ0Hu;x~p()n#}7CCB7XYpmdElW?K_9{?m<0fh;h>!i_C4kMoyDX<@ zwEJmk@uHTL8X?&DvvIPm%Oxt60xFfjgW=HfFsb-rG{Xm~l&$i^%!z471)M*0f&T{v zod$*|QP36%qExql?^CW;wp4Zj&Cs?}vTm-`*`%`o9rwV(p`&7tB8^iDj zxZAiC@1KJ~WRPF>ki{Y_$tm;f))|1_D(c=CpqT2sFBWPbj~orukx+W+1${VrA^c?A zNe}meG)?t5i%IGKdb0}dgUX{y;P3*h9Sj3dHTx)4@)y%pt=8>F^J@54R_&4wX-tZQ z4C&4}R=`jO=LIiJSHs=r=5`1V$?oPh?+P699RY(ja3o4t;zF~)l~Lz;I)vH>@AK-O zBMeAkLuS4uTm_p_$;1)^Cs~byuqoA3EHrS!l{gYsYncTGRv^?#aZ7xk;6ard`L(<< z#s-Dh-ZvvCW>O!S9$93dM8!=33G|2E1>TAykucwY_Hj|e3JIYvKX^K`HLiJXgh)=Z zASn(Fio=Ic6eT1_5I78avl4mK#18t>IALQ0db|?4i_rW#n;Ov5mC%@N06qkSfq^hs ziBMGtqlB|d1L1Nt_e` zxH2wXkw{mCrRBt1(x-@~T=+>OFy+Fr&%-ot?aNbuYiwi~cO>#WXIkdWxX_i zJmYC;(+cp-t`%)#wyi`~2Z|VPz4=`*<`b|N?07AxYk<2j$1xf!YDzw45_<-6p6uoO zCc)-uXC#c9@AaA)}S0#D=kltr^}r@xu{kx5k0EU2!081vV8*PD82t-`ehf zyVCuQ7HiDW%~Z?o3BHwBz`ywMljUZisc7lTQjEOC?xs>qw>1nP_KPyqtN=~PooWBP zEM4o};zbZFR4SLo#dCXG>a2~UGwU1V-SM+=J z)!2d#EojF}5C$>SunrRnPh+V!ia`rs$?YZeHWu7Y({Tg&z5>eLB0a|oy})xysj5y& zDM~qlc3eZJ-~NTMPSzRgWXV`>(O5tJZ^lB^%NnTdJj`(Az}8mjeJyP8FsJ@oDL+ew zPl&e=Htnpo{6BCOLRpq){t#v#&gwt&YMae6k3KDW^nG0UW}PeF-5!`x|@Q>)F~tY(k2NAExwmJeMAxpca1!-`x+ z=iEaD(m+h#4Otrr4Z%Cx9Zd_ABGuoKK=Xv5bvhClukS=>hz(M-v7FW9B^yi;=@Jbh zAz>6!3iYWrEPlk7Q}Cq-X#T`J*h$H08(N@>lms_jP`Q@|NS`DmKl7b*;K~NkVx~^ZKJ(E*XMZ@yg zH_jl2q?OrHVwy?_mVwOV-?4`=YpQ@~-6ub<?19Fb&@rX zElK2Cl69T;6%-{w^J1F6Mzt50N$<2(6bYFDhFBqWm*M)To@%v_n#XbqpKwa`hH*;0 zbvM;y>&aY!Na`m+JPdfu_KZq*FK_qBHzbToU7^1P)7?^ws>mAivMqjdDyiS%5+!&wfl<&eFi2kpXwfUWH4|<9#VM!lU4KbMg~_r2(n7r zWa-t4%ztL#kTbBS1Je5YAU2><~gUOXA>yvmXZ152LNBj}@dD!$g#H z@?e&AUK8rPQsWUS(<{-5uuJV@is%eghFI=40^}t^&Lm`4LUwb=buGq6N3%GoKoGeC zK`MUbG8jh{Fi8bM1Q4oVyJ*LGB;QJsnM1eWSlN-A!I7JFg&8C~Z>CPon92FxtWO`z z=bt?e)Z-W%0S7*4p%B8jbzDiOa4!T^sD$gLQ#OSgQD?vg_=BZjj@6iE56JeE@jQ)1 z8fIX^3;;&;Po`!Q59$MJJS->y;Oo^v4zXAaENr({i$QzYPDK@FOj$_7S}j_GV}%JF z*wu?ujP98tp@317Eq`+1sz*HkZk`MB|2LBL*LP`Z`+h`s=jk?CX%4#kFU4gR3b`@> E01snB{Qv*} literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/amd.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/amd.js new file mode 100644 index 0000000..a604134 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/amd.js @@ -0,0 +1,15 @@ +var tap = require('tap'); +var test = tap.test; + +test('amd', function(t) { + global.define = define; + define.amd = true; + var defined = null; + function define(stuff) { + defined = stuff; + } + var fromRequire = require('../'); + t.ok(defined, 'amd function called'); + t.equal(fromRequire, defined, 'amd stuff same as require stuff'); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/big-numbers.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/big-numbers.js new file mode 100644 index 0000000..c051864 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/big-numbers.js @@ -0,0 +1,31 @@ +var test = require('tap').test +var semver = require('../') + +test('long version is too long', function (t) { + var v = '1.2.' + new Array(256).join('1') + t.throws(function () { + new semver.SemVer(v) + }) + t.equal(semver.valid(v, false), null) + t.equal(semver.valid(v, true), null) + t.equal(semver.inc(v, 'patch'), null) + t.end() +}) + +test('big number is like too long version', function (t) { + var v = '1.2.' + new Array(100).join('1') + t.throws(function () { + new semver.SemVer(v) + }) + t.equal(semver.valid(v, false), null) + t.equal(semver.valid(v, true), null) + t.equal(semver.inc(v, 'patch'), null) + t.end() +}) + +test('parsing null does not throw', function (t) { + t.equal(semver.parse(null), null) + t.equal(semver.parse({}), null) + t.equal(semver.parse(new semver.SemVer('1.2.3')).version, '1.2.3') + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/clean.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/clean.js new file mode 100644 index 0000000..9e268de --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/clean.js @@ -0,0 +1,29 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var clean = semver.clean; + +test('\nclean tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.3', '1.2.3'], + [' 1.2.3 ', '1.2.3'], + [' 1.2.3-4 ', '1.2.3-4'], + [' 1.2.3-pre ', '1.2.3-pre'], + [' =v1.2.3 ', '1.2.3'], + ['v1.2.3', '1.2.3'], + [' v1.2.3 ', '1.2.3'], + ['\t1.2.3', '1.2.3'], + ['>1.2.3', null], + ['~1.2.3', null], + ['<=1.2.3', null], + ['1.2.x', null] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var msg = 'clean(' + range + ') = ' + version; + t.equal(clean(range), version, msg); + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/gtr.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/gtr.js new file mode 100644 index 0000000..bbb8789 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/gtr.js @@ -0,0 +1,173 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var gtr = semver.gtr; + +test('\ngtr tests', function(t) { + // [range, version, loose] + // Version should be greater than range + [ + ['~1.2.2', '1.3.0'], + ['~0.6.1-1', '0.7.1-1'], + ['1.0.0 - 2.0.0', '2.0.1'], + ['1.0.0', '1.0.1-beta1'], + ['1.0.0', '2.0.0'], + ['<=2.0.0', '2.1.1'], + ['<=2.0.0', '3.2.9'], + ['<2.0.0', '2.0.0'], + ['0.1.20 || 1.2.4', '1.2.5'], + ['2.x.x', '3.0.0'], + ['1.2.x', '1.3.0'], + ['1.2.x || 2.x', '3.0.0'], + ['2.*.*', '5.0.1'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '4.0.0'], + ['2', '3.0.0'], + ['2.3', '2.4.2'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.5.5'], + ['~>3.2.1', '3.3.0'], // >=3.2.1 <3.3.0 + ['~1', '2.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.4'], + ['~> 1', '3.2.3'], + ['~1.0', '1.1.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.1.0'], + ['<1.2', '1.2.0'], + ['< 1.2', '1.2.1'], + ['1', '2.0.0beta', true], + ['~v0.5.4-pre', '0.6.0'], + ['~v0.5.4-pre', '0.6.1-pre'], + ['=0.7.x', '0.8.0'], + ['=0.7.x', '0.8.0-asdf'], + ['<0.7.x', '0.7.0'], + ['~1.2.2', '1.3.0'], + ['1.0.0 - 2.0.0', '2.2.3'], + ['1.0.0', '1.0.1'], + ['<=2.0.0', '3.0.0'], + ['<=2.0.0', '2.9999.9999'], + ['<=2.0.0', '2.2.9'], + ['<2.0.0', '2.9999.9999'], + ['<2.0.0', '2.2.9'], + ['2.x.x', '3.1.3'], + ['1.2.x', '1.3.3'], + ['1.2.x || 2.x', '3.1.3'], + ['2.*.*', '3.1.3'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '3.1.3'], + ['2', '3.1.2'], + ['2.3', '2.4.1'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 + ['~1', '2.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.3'], + ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 + ['<1', '1.0.0'], + ['1', '2.0.0beta', true], + ['<1', '1.0.0beta', true], + ['< 1', '1.0.0beta', true], + ['=0.7.x', '0.8.2'], + ['<0.7.x', '0.7.2'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'gtr(' + version + ', ' + range + ', ' + loose + ')'; + t.ok(gtr(version, range, loose), msg); + }); + t.end(); +}); + +test('\nnegative gtr tests', function(t) { + // [range, version, loose] + // Version should NOT be greater than range + [ + ['~0.6.1-1', '0.6.1-1'], + ['1.0.0 - 2.0.0', '1.2.3'], + ['1.0.0 - 2.0.0', '0.9.9'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0', true], + ['*', '1.2.3'], + ['*', 'v1.2.3-foo'], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97'], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['0.1.20 || >1.2.4', '1.2.4'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['0.1.20 || 1.2.4', '0.1.20'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.0.2'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['1', '1.0.0beta', true], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['=0.7.x', '0.7.0-asdf'], + ['>=0.7.x', '0.7.0-asdf'], + ['<=0.7.x', '0.6.2'], + ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], + ['>=0.2.3 <=0.2.4', '0.2.4'], + ['1.0.0 - 2.0.0', '2.0.0'], + ['^1', '0.0.0-0'], + ['^3.0.0', '2.0.0'], + ['^1.0.0 || ~2.0.1', '2.0.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], + ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], + ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = '!gtr(' + version + ', ' + range + ', ' + loose + ')'; + t.notOk(gtr(version, range, loose), msg); + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/index.js new file mode 100644 index 0000000..c256c79 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/index.js @@ -0,0 +1,685 @@ +'use strict'; + +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var eq = semver.eq; +var gt = semver.gt; +var lt = semver.lt; +var neq = semver.neq; +var cmp = semver.cmp; +var gte = semver.gte; +var lte = semver.lte; +var satisfies = semver.satisfies; +var validRange = semver.validRange; +var inc = semver.inc; +var diff = semver.diff; +var replaceStars = semver.replaceStars; +var toComparators = semver.toComparators; +var SemVer = semver.SemVer; +var Range = semver.Range; + +test('\ncomparison tests', function(t) { + // [version1, version2] + // version1 should be greater than version2 + [['0.0.0', '0.0.0-foo'], + ['0.0.1', '0.0.0'], + ['1.0.0', '0.9.9'], + ['0.10.0', '0.9.0'], + ['0.99.0', '0.10.0'], + ['2.0.0', '1.2.3'], + ['v0.0.0', '0.0.0-foo', true], + ['v0.0.1', '0.0.0', true], + ['v1.0.0', '0.9.9', true], + ['v0.10.0', '0.9.0', true], + ['v0.99.0', '0.10.0', true], + ['v2.0.0', '1.2.3', true], + ['0.0.0', 'v0.0.0-foo', true], + ['0.0.1', 'v0.0.0', true], + ['1.0.0', 'v0.9.9', true], + ['0.10.0', 'v0.9.0', true], + ['0.99.0', 'v0.10.0', true], + ['2.0.0', 'v1.2.3', true], + ['1.2.3', '1.2.3-asdf'], + ['1.2.3', '1.2.3-4'], + ['1.2.3', '1.2.3-4-foo'], + ['1.2.3-5-foo', '1.2.3-5'], + ['1.2.3-5', '1.2.3-4'], + ['1.2.3-5-foo', '1.2.3-5-Foo'], + ['3.0.0', '2.7.2+asdf'], + ['1.2.3-a.10', '1.2.3-a.5'], + ['1.2.3-a.b', '1.2.3-a.5'], + ['1.2.3-a.b', '1.2.3-a'], + ['1.2.3-a.b.c.10.d.5', '1.2.3-a.b.c.5.d.100'], + ['1.2.3-r2', '1.2.3-r100'], + ['1.2.3-r100', '1.2.3-R2'] + ].forEach(function(v) { + var v0 = v[0]; + var v1 = v[1]; + var loose = v[2]; + t.ok(gt(v0, v1, loose), "gt('" + v0 + "', '" + v1 + "')"); + t.ok(lt(v1, v0, loose), "lt('" + v1 + "', '" + v0 + "')"); + t.ok(!gt(v1, v0, loose), "!gt('" + v1 + "', '" + v0 + "')"); + t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); + t.ok(eq(v0, v0, loose), "eq('" + v0 + "', '" + v0 + "')"); + t.ok(eq(v1, v1, loose), "eq('" + v1 + "', '" + v1 + "')"); + t.ok(neq(v0, v1, loose), "neq('" + v0 + "', '" + v1 + "')"); + t.ok(cmp(v1, '==', v1, loose), "cmp('" + v1 + "' == '" + v1 + "')"); + t.ok(cmp(v0, '>=', v1, loose), "cmp('" + v0 + "' >= '" + v1 + "')"); + t.ok(cmp(v1, '<=', v0, loose), "cmp('" + v1 + "' <= '" + v0 + "')"); + t.ok(cmp(v0, '!=', v1, loose), "cmp('" + v0 + "' != '" + v1 + "')"); + }); + t.end(); +}); + +test('\nequality tests', function(t) { + // [version1, version2] + // version1 should be equivalent to version2 + [['1.2.3', 'v1.2.3', true], + ['1.2.3', '=1.2.3', true], + ['1.2.3', 'v 1.2.3', true], + ['1.2.3', '= 1.2.3', true], + ['1.2.3', ' v1.2.3', true], + ['1.2.3', ' =1.2.3', true], + ['1.2.3', ' v 1.2.3', true], + ['1.2.3', ' = 1.2.3', true], + ['1.2.3-0', 'v1.2.3-0', true], + ['1.2.3-0', '=1.2.3-0', true], + ['1.2.3-0', 'v 1.2.3-0', true], + ['1.2.3-0', '= 1.2.3-0', true], + ['1.2.3-0', ' v1.2.3-0', true], + ['1.2.3-0', ' =1.2.3-0', true], + ['1.2.3-0', ' v 1.2.3-0', true], + ['1.2.3-0', ' = 1.2.3-0', true], + ['1.2.3-1', 'v1.2.3-1', true], + ['1.2.3-1', '=1.2.3-1', true], + ['1.2.3-1', 'v 1.2.3-1', true], + ['1.2.3-1', '= 1.2.3-1', true], + ['1.2.3-1', ' v1.2.3-1', true], + ['1.2.3-1', ' =1.2.3-1', true], + ['1.2.3-1', ' v 1.2.3-1', true], + ['1.2.3-1', ' = 1.2.3-1', true], + ['1.2.3-beta', 'v1.2.3-beta', true], + ['1.2.3-beta', '=1.2.3-beta', true], + ['1.2.3-beta', 'v 1.2.3-beta', true], + ['1.2.3-beta', '= 1.2.3-beta', true], + ['1.2.3-beta', ' v1.2.3-beta', true], + ['1.2.3-beta', ' =1.2.3-beta', true], + ['1.2.3-beta', ' v 1.2.3-beta', true], + ['1.2.3-beta', ' = 1.2.3-beta', true], + ['1.2.3-beta+build', ' = 1.2.3-beta+otherbuild', true], + ['1.2.3+build', ' = 1.2.3+otherbuild', true], + ['1.2.3-beta+build', '1.2.3-beta+otherbuild'], + ['1.2.3+build', '1.2.3+otherbuild'], + [' v1.2.3+build', '1.2.3+otherbuild'] + ].forEach(function(v) { + var v0 = v[0]; + var v1 = v[1]; + var loose = v[2]; + t.ok(eq(v0, v1, loose), "eq('" + v0 + "', '" + v1 + "')"); + t.ok(!neq(v0, v1, loose), "!neq('" + v0 + "', '" + v1 + "')"); + t.ok(cmp(v0, '==', v1, loose), 'cmp(' + v0 + '==' + v1 + ')'); + t.ok(!cmp(v0, '!=', v1, loose), '!cmp(' + v0 + '!=' + v1 + ')'); + t.ok(!cmp(v0, '===', v1, loose), '!cmp(' + v0 + '===' + v1 + ')'); + t.ok(cmp(v0, '!==', v1, loose), 'cmp(' + v0 + '!==' + v1 + ')'); + t.ok(!gt(v0, v1, loose), "!gt('" + v0 + "', '" + v1 + "')"); + t.ok(gte(v0, v1, loose), "gte('" + v0 + "', '" + v1 + "')"); + t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); + t.ok(lte(v0, v1, loose), "lte('" + v0 + "', '" + v1 + "')"); + }); + t.end(); +}); + + +test('\nrange tests', function(t) { + // [range, version] + // version should be included by range + [['1.0.0 - 2.0.0', '1.2.3'], + ['^1.2.3+build', '1.2.3'], + ['^1.2.3+build', '1.3.0'], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '1.2.3'], + ['1.2.3pre+asdf - 2.4.3-pre+asdf', '1.2.3', true], + ['1.2.3-pre+asdf - 2.4.3pre+asdf', '1.2.3', true], + ['1.2.3pre+asdf - 2.4.3pre+asdf', '1.2.3', true], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '1.2.3-pre.2'], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '2.4.3-alpha'], + ['1.2.3+asdf - 2.4.3+asdf', '1.2.3'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0'], + ['*', '1.2.3'], + ['*', 'v1.2.3', true], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97', true], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0, + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0, + ['~ 1.0', '1.0.2'], + ['~ 1.0.3', '1.0.12'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['<=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['<=0.7.x', '0.6.2'], + ['~1.2.1 >=1.2.3', '1.2.3'], + ['~1.2.1 =1.2.3', '1.2.3'], + ['~1.2.1 1.2.3', '1.2.3'], + ['~1.2.1 >=1.2.3 1.2.3', '1.2.3'], + ['~1.2.1 1.2.3 >=1.2.3', '1.2.3'], + ['~1.2.1 1.2.3', '1.2.3'], + ['>=1.2.1 1.2.3', '1.2.3'], + ['1.2.3 >=1.2.1', '1.2.3'], + ['>=1.2.3 >=1.2.1', '1.2.3'], + ['>=1.2.1 >=1.2.3', '1.2.3'], + ['>=1.2', '1.2.8'], + ['^1.2.3', '1.8.1'], + ['^0.1.2', '0.1.2'], + ['^0.1', '0.1.2'], + ['^1.2', '1.4.2'], + ['^1.2 ^1', '1.4.2'], + ['^1.2.3-alpha', '1.2.3-pre'], + ['^1.2.0-alpha', '1.2.0-pre'], + ['^0.0.1-alpha', '0.0.1-beta'] + ].forEach(function(v) { + var range = v[0]; + var ver = v[1]; + var loose = v[2]; + t.ok(satisfies(ver, range, loose), range + ' satisfied by ' + ver); + }); + t.end(); +}); + +test('\nnegative range tests', function(t) { + // [range, version] + // version should not be included by range + [['1.0.0 - 2.0.0', '2.2.3'], + ['1.2.3+asdf - 2.4.3+asdf', '1.2.3-pre.2'], + ['1.2.3+asdf - 2.4.3+asdf', '2.4.3-alpha'], + ['^1.2.3+build', '2.0.0'], + ['^1.2.3+build', '1.2.0'], + ['^1.2.3', '1.2.3-pre'], + ['^1.2', '1.2.0-pre'], + ['>1.2', '1.3.0-beta'], + ['<=1.2.3', '1.2.3-beta'], + ['^1.2.3', '1.2.3-beta'], + ['=0.7.x', '0.7.0-asdf'], + ['>=0.7.x', '0.7.0-asdf'], + ['1', '1.0.0beta', true], + ['<1', '1.0.0beta', true], + ['< 1', '1.0.0beta', true], + ['1.0.0', '1.0.1'], + ['>=1.0.0', '0.0.0'], + ['>=1.0.0', '0.0.1'], + ['>=1.0.0', '0.1.0'], + ['>1.0.0', '0.0.1'], + ['>1.0.0', '0.1.0'], + ['<=2.0.0', '3.0.0'], + ['<=2.0.0', '2.9999.9999'], + ['<=2.0.0', '2.2.9'], + ['<2.0.0', '2.9999.9999'], + ['<2.0.0', '2.2.9'], + ['>=0.1.97', 'v0.1.93', true], + ['>=0.1.97', '0.1.93'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['>=0.2.3 || <0.0.1', '0.0.3'], + ['>=0.2.3 || <0.0.1', '0.2.2'], + ['2.x.x', '1.1.3'], + ['2.x.x', '3.1.3'], + ['1.2.x', '1.3.3'], + ['1.2.x || 2.x', '3.1.3'], + ['1.2.x || 2.x', '1.1.3'], + ['2.*.*', '1.1.3'], + ['2.*.*', '3.1.3'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '3.1.3'], + ['1.2.* || 2.*', '1.1.3'], + ['2', '1.1.2'], + ['2.3', '2.4.1'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.3.9'], + ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 + ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.3'], + ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 + ['<1', '1.0.0'], + ['>=1.2', '1.1.1'], + ['1', '2.0.0beta', true], + ['~v0.5.4-beta', '0.5.4-alpha'], + ['=0.7.x', '0.8.2'], + ['>=0.7.x', '0.6.2'], + ['<0.7.x', '0.7.2'], + ['<1.2.3', '1.2.3-beta'], + ['=1.2.3', '1.2.3-beta'], + ['>1.2', '1.2.8'], + ['^1.2.3', '2.0.0-alpha'], + ['^1.2.3', '1.2.2'], + ['^1.2', '1.1.9'], + ['*', 'v1.2.3-foo', true], + // invalid ranges never satisfied! + ['blerg', '1.2.3'], + ['git+https://user:password0123@github.com/foo', '123.0.0', true], + ['^1.2.3', '2.0.0-pre'] + ].forEach(function(v) { + var range = v[0]; + var ver = v[1]; + var loose = v[2]; + var found = satisfies(ver, range, loose); + t.ok(!found, ver + ' not satisfied by ' + range); + }); + t.end(); +}); + +test('\nincrement versions test', function(t) { +// [version, inc, result, identifier] +// inc(version, inc) -> result + [['1.2.3', 'major', '2.0.0'], + ['1.2.3', 'minor', '1.3.0'], + ['1.2.3', 'patch', '1.2.4'], + ['1.2.3tag', 'major', '2.0.0', true], + ['1.2.3-tag', 'major', '2.0.0'], + ['1.2.3', 'fake', null], + ['1.2.0-0', 'patch', '1.2.0'], + ['fake', 'major', null], + ['1.2.3-4', 'major', '2.0.0'], + ['1.2.3-4', 'minor', '1.3.0'], + ['1.2.3-4', 'patch', '1.2.3'], + ['1.2.3-alpha.0.beta', 'major', '2.0.0'], + ['1.2.3-alpha.0.beta', 'minor', '1.3.0'], + ['1.2.3-alpha.0.beta', 'patch', '1.2.3'], + ['1.2.4', 'prerelease', '1.2.5-0'], + ['1.2.3-0', 'prerelease', '1.2.3-1'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1'], + ['1.2.3-alpha.1', 'prerelease', '1.2.3-alpha.2'], + ['1.2.3-alpha.2', 'prerelease', '1.2.3-alpha.3'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta'], + ['1.2.3-alpha.1.beta', 'prerelease', '1.2.3-alpha.2.beta'], + ['1.2.3-alpha.2.beta', 'prerelease', '1.2.3-alpha.3.beta'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta'], + ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta'], + ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1'], + ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2'], + ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta'], + ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta'], + ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta'], + ['1.2.0', 'prepatch', '1.2.1-0'], + ['1.2.0-1', 'prepatch', '1.2.1-0'], + ['1.2.0', 'preminor', '1.3.0-0'], + ['1.2.3-1', 'preminor', '1.3.0-0'], + ['1.2.0', 'premajor', '2.0.0-0'], + ['1.2.3-1', 'premajor', '2.0.0-0'], + ['1.2.0-1', 'minor', '1.2.0'], + ['1.0.0-1', 'major', '1.0.0'], + + ['1.2.3', 'major', '2.0.0', false, 'dev'], + ['1.2.3', 'minor', '1.3.0', false, 'dev'], + ['1.2.3', 'patch', '1.2.4', false, 'dev'], + ['1.2.3tag', 'major', '2.0.0', true, 'dev'], + ['1.2.3-tag', 'major', '2.0.0', false, 'dev'], + ['1.2.3', 'fake', null, false, 'dev'], + ['1.2.0-0', 'patch', '1.2.0', false, 'dev'], + ['fake', 'major', null, false, 'dev'], + ['1.2.3-4', 'major', '2.0.0', false, 'dev'], + ['1.2.3-4', 'minor', '1.3.0', false, 'dev'], + ['1.2.3-4', 'patch', '1.2.3', false, 'dev'], + ['1.2.3-alpha.0.beta', 'major', '2.0.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'minor', '1.3.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'patch', '1.2.3', false, 'dev'], + ['1.2.4', 'prerelease', '1.2.5-dev.0', false, 'dev'], + ['1.2.3-0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1', false, 'alpha'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta', false, 'alpha'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta', false, 'alpha'], + ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta', false, 'alpha'], + ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta', false, 'alpha'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1', false, 'alpha'], + ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2', false, 'alpha'], + ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3', false, 'alpha'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta', false, 'alpha'], + ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta', false, 'alpha'], + ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta', false, 'alpha'], + ['1.2.0', 'prepatch', '1.2.1-dev.0', 'dev'], + ['1.2.0-1', 'prepatch', '1.2.1-dev.0', 'dev'], + ['1.2.0', 'preminor', '1.3.0-dev.0', 'dev'], + ['1.2.3-1', 'preminor', '1.3.0-dev.0', 'dev'], + ['1.2.0', 'premajor', '2.0.0-dev.0', 'dev'], + ['1.2.3-1', 'premajor', '2.0.0-dev.0', 'dev'], + ['1.2.0-1', 'minor', '1.2.0', 'dev'], + ['1.0.0-1', 'major', '1.0.0', 'dev'], + ['1.2.3-dev.bar', 'prerelease', '1.2.3-dev.0', false, 'dev'] + + ].forEach(function(v) { + var pre = v[0]; + var what = v[1]; + var wanted = v[2]; + var loose = v[3]; + var id = v[4]; + var found = inc(pre, what, loose, id); + var cmd = 'inc(' + pre + ', ' + what + ', ' + id + ')'; + t.equal(found, wanted, cmd + ' === ' + wanted); + }); + + t.end(); +}); + +test('\ndiff versions test', function(t) { +// [version1, version2, result] +// diff(version1, version2) -> result + [['1.2.3', '0.2.3', 'major'], + ['1.4.5', '0.2.3', 'major'], + ['1.2.3', '2.0.0-pre', 'premajor'], + ['1.2.3', '1.3.3', 'minor'], + ['1.0.1', '1.1.0-pre', 'preminor'], + ['1.2.3', '1.2.4', 'patch'], + ['1.2.3', '1.2.4-pre', 'prepatch'], + ['0.0.1', '0.0.1-pre', 'prerelease'], + ['0.0.1', '0.0.1-pre-2', 'prerelease'], + ['1.1.0', '1.1.0-pre', 'prerelease'], + ['1.1.0-pre-1', '1.1.0-pre-2', 'prerelease'], + ['1.0.0', '1.0.0', null] + + ].forEach(function(v) { + var version1 = v[0]; + var version2 = v[1]; + var wanted = v[2]; + var found = diff(version1, version2); + var cmd = 'diff(' + version1 + ', ' + version2 + ')'; + t.equal(found, wanted, cmd + ' === ' + wanted); + }); + + t.end(); +}); + +test('\nvalid range test', function(t) { + // [range, result] + // validRange(range) -> result + // translate ranges into their canonical form + [['1.0.0 - 2.0.0', '>=1.0.0 <=2.0.0'], + ['1.0.0', '1.0.0'], + ['>=*', '*'], + ['', '*'], + ['*', '*'], + ['*', '*'], + ['>=1.0.0', '>=1.0.0'], + ['>1.0.0', '>1.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['1', '>=1.0.0 <2.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['<2.0.0', '<2.0.0'], + ['<2.0.0', '<2.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['> 1.0.0', '>1.0.0'], + ['> 1.0.0', '>1.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['< 2.0.0', '<2.0.0'], + ['< 2.0.0', '<2.0.0'], + ['>=0.1.97', '>=0.1.97'], + ['>=0.1.97', '>=0.1.97'], + ['0.1.20 || 1.2.4', '0.1.20||1.2.4'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['||', '||'], + ['2.x.x', '>=2.0.0 <3.0.0'], + ['1.2.x', '>=1.2.0 <1.3.0'], + ['1.2.x || 2.x', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['1.2.x || 2.x', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['x', '*'], + ['2.*.*', '>=2.0.0 <3.0.0'], + ['1.2.*', '>=1.2.0 <1.3.0'], + ['1.2.* || 2.*', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['*', '*'], + ['2', '>=2.0.0 <3.0.0'], + ['2.3', '>=2.3.0 <2.4.0'], + ['~2.4', '>=2.4.0 <2.5.0'], + ['~2.4', '>=2.4.0 <2.5.0'], + ['~>3.2.1', '>=3.2.1 <3.3.0'], + ['~1', '>=1.0.0 <2.0.0'], + ['~>1', '>=1.0.0 <2.0.0'], + ['~> 1', '>=1.0.0 <2.0.0'], + ['~1.0', '>=1.0.0 <1.1.0'], + ['~ 1.0', '>=1.0.0 <1.1.0'], + ['^0', '>=0.0.0 <1.0.0'], + ['^ 1', '>=1.0.0 <2.0.0'], + ['^0.1', '>=0.1.0 <0.2.0'], + ['^1.0', '>=1.0.0 <2.0.0'], + ['^1.2', '>=1.2.0 <2.0.0'], + ['^0.0.1', '>=0.0.1 <0.0.2'], + ['^0.0.1-beta', '>=0.0.1-beta <0.0.2'], + ['^0.1.2', '>=0.1.2 <0.2.0'], + ['^1.2.3', '>=1.2.3 <2.0.0'], + ['^1.2.3-beta.4', '>=1.2.3-beta.4 <2.0.0'], + ['<1', '<1.0.0'], + ['< 1', '<1.0.0'], + ['>=1', '>=1.0.0'], + ['>= 1', '>=1.0.0'], + ['<1.2', '<1.2.0'], + ['< 1.2', '<1.2.0'], + ['1', '>=1.0.0 <2.0.0'], + ['>01.02.03', '>1.2.3', true], + ['>01.02.03', null], + ['~1.2.3beta', '>=1.2.3-beta <1.3.0', true], + ['~1.2.3beta', null], + ['^ 1.2 ^ 1', '>=1.2.0 <2.0.0 >=1.0.0 <2.0.0'] + ].forEach(function(v) { + var pre = v[0]; + var wanted = v[1]; + var loose = v[2]; + var found = validRange(pre, loose); + + t.equal(found, wanted, 'validRange(' + pre + ') === ' + wanted); + }); + + t.end(); +}); + +test('\ncomparators test', function(t) { + // [range, comparators] + // turn range into a set of individual comparators + [['1.0.0 - 2.0.0', [['>=1.0.0', '<=2.0.0']]], + ['1.0.0', [['1.0.0']]], + ['>=*', [['']]], + ['', [['']]], + ['*', [['']]], + ['*', [['']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>1.0.0', [['>1.0.0']]], + ['>1.0.0', [['>1.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['1', [['>=1.0.0', '<2.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['<2.0.0', [['<2.0.0']]], + ['<2.0.0', [['<2.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['> 1.0.0', [['>1.0.0']]], + ['> 1.0.0', [['>1.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['< 2.0.0', [['<2.0.0']]], + ['<\t2.0.0', [['<2.0.0']]], + ['>=0.1.97', [['>=0.1.97']]], + ['>=0.1.97', [['>=0.1.97']]], + ['0.1.20 || 1.2.4', [['0.1.20'], ['1.2.4']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['||', [[''], ['']]], + ['2.x.x', [['>=2.0.0', '<3.0.0']]], + ['1.2.x', [['>=1.2.0', '<1.3.0']]], + ['1.2.x || 2.x', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['1.2.x || 2.x', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['x', [['']]], + ['2.*.*', [['>=2.0.0', '<3.0.0']]], + ['1.2.*', [['>=1.2.0', '<1.3.0']]], + ['1.2.* || 2.*', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['1.2.* || 2.*', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['*', [['']]], + ['2', [['>=2.0.0', '<3.0.0']]], + ['2.3', [['>=2.3.0', '<2.4.0']]], + ['~2.4', [['>=2.4.0', '<2.5.0']]], + ['~2.4', [['>=2.4.0', '<2.5.0']]], + ['~>3.2.1', [['>=3.2.1', '<3.3.0']]], + ['~1', [['>=1.0.0', '<2.0.0']]], + ['~>1', [['>=1.0.0', '<2.0.0']]], + ['~> 1', [['>=1.0.0', '<2.0.0']]], + ['~1.0', [['>=1.0.0', '<1.1.0']]], + ['~ 1.0', [['>=1.0.0', '<1.1.0']]], + ['~ 1.0.3', [['>=1.0.3', '<1.1.0']]], + ['~> 1.0.3', [['>=1.0.3', '<1.1.0']]], + ['<1', [['<1.0.0']]], + ['< 1', [['<1.0.0']]], + ['>=1', [['>=1.0.0']]], + ['>= 1', [['>=1.0.0']]], + ['<1.2', [['<1.2.0']]], + ['< 1.2', [['<1.2.0']]], + ['1', [['>=1.0.0', '<2.0.0']]], + ['1 2', [['>=1.0.0', '<2.0.0', '>=2.0.0', '<3.0.0']]], + ['1.2 - 3.4.5', [['>=1.2.0', '<=3.4.5']]], + ['1.2.3 - 3.4', [['>=1.2.3', '<3.5.0']]], + ['1.2.3 - 3', [['>=1.2.3', '<4.0.0']]], + ['>*', [['<0.0.0']]], + ['<*', [['<0.0.0']]] + ].forEach(function(v) { + var pre = v[0]; + var wanted = v[1]; + var found = toComparators(v[0]); + var jw = JSON.stringify(wanted); + t.equivalent(found, wanted, 'toComparators(' + pre + ') === ' + jw); + }); + + t.end(); +}); + +test('\ninvalid version numbers', function(t) { + ['1.2.3.4', + 'NOT VALID', + 1.2, + null, + 'Infinity.NaN.Infinity' + ].forEach(function(v) { + t.throws(function() { + new SemVer(v); + }, {name:'TypeError', message:'Invalid Version: ' + v}); + }); + + t.end(); +}); + +test('\nstrict vs loose version numbers', function(t) { + [['=1.2.3', '1.2.3'], + ['01.02.03', '1.2.3'], + ['1.2.3-beta.01', '1.2.3-beta.1'], + [' =1.2.3', '1.2.3'], + ['1.2.3foo', '1.2.3-foo'] + ].forEach(function(v) { + var loose = v[0]; + var strict = v[1]; + t.throws(function() { + new SemVer(loose); + }); + var lv = new SemVer(loose, true); + t.equal(lv.version, strict); + t.ok(eq(loose, strict, true)); + t.throws(function() { + eq(loose, strict); + }); + t.throws(function() { + new SemVer(strict).compare(loose); + }); + }); + t.end(); +}); + +test('\nstrict vs loose ranges', function(t) { + [['>=01.02.03', '>=1.2.3'], + ['~1.02.03beta', '>=1.2.3-beta <1.3.0'] + ].forEach(function(v) { + var loose = v[0]; + var comps = v[1]; + t.throws(function() { + new Range(loose); + }); + t.equal(new Range(loose, true).range, comps); + }); + t.end(); +}); + +test('\nmax satisfying', function(t) { + [[['1.2.3', '1.2.4'], '1.2', '1.2.4'], + [['1.2.4', '1.2.3'], '1.2', '1.2.4'], + [['1.2.3', '1.2.4', '1.2.5', '1.2.6'], '~1.2.3', '1.2.6'], + [['1.1.0', '1.2.0', '1.2.1', '1.3.0', '2.0.0b1', '2.0.0b2', '2.0.0b3', '2.0.0', '2.1.0'], '~2.0.0', '2.0.0', true] + ].forEach(function(v) { + var versions = v[0]; + var range = v[1]; + var expect = v[2]; + var loose = v[3]; + var actual = semver.maxSatisfying(versions, range, loose); + t.equal(actual, expect); + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/ltr.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/ltr.js new file mode 100644 index 0000000..0f7167d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/ltr.js @@ -0,0 +1,181 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var ltr = semver.ltr; + +test('\nltr tests', function(t) { + // [range, version, loose] + // Version should be less than range + [ + ['~1.2.2', '1.2.1'], + ['~0.6.1-1', '0.6.1-0'], + ['1.0.0 - 2.0.0', '0.0.1'], + ['1.0.0-beta.2', '1.0.0-beta.1'], + ['1.0.0', '0.0.0'], + ['>=2.0.0', '1.1.1'], + ['>=2.0.0', '1.2.9'], + ['>2.0.0', '2.0.0'], + ['0.1.20 || 1.2.4', '0.1.5'], + ['2.x.x', '1.0.0'], + ['1.2.x', '1.1.0'], + ['1.2.x || 2.x', '1.0.0'], + ['2.*.*', '1.0.1'], + ['1.2.*', '1.1.3'], + ['1.2.* || 2.*', '1.1.9999'], + ['2', '1.0.0'], + ['2.3', '2.2.2'], + ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.3.5'], + ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '0.2.4'], + ['~> 1', '0.2.3'], + ['~1.0', '0.1.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '0.1.0'], + ['>1.2', '1.2.0'], + ['> 1.2', '1.2.1'], + ['1', '0.0.0beta', true], + ['~v0.5.4-pre', '0.5.4-alpha'], + ['~v0.5.4-pre', '0.5.4-alpha'], + ['=0.7.x', '0.6.0'], + ['=0.7.x', '0.6.0-asdf'], + ['>=0.7.x', '0.6.0'], + ['~1.2.2', '1.2.1'], + ['1.0.0 - 2.0.0', '0.2.3'], + ['1.0.0', '0.0.1'], + ['>=2.0.0', '1.0.0'], + ['>=2.0.0', '1.9999.9999'], + ['>=2.0.0', '1.2.9'], + ['>2.0.0', '2.0.0'], + ['>2.0.0', '1.2.9'], + ['2.x.x', '1.1.3'], + ['1.2.x', '1.1.3'], + ['1.2.x || 2.x', '1.1.3'], + ['2.*.*', '1.1.3'], + ['1.2.*', '1.1.3'], + ['1.2.* || 2.*', '1.1.3'], + ['2', '1.9999.9999'], + ['2.3', '2.2.1'], + ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 + ['~>3.2.1', '2.3.2'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '0.2.3'], + ['~1.0', '0.0.0'], // >=1.0.0 <1.1.0 + ['>1', '1.0.0'], + ['2', '1.0.0beta', true], + ['>1', '1.0.0beta', true], + ['> 1', '1.0.0beta', true], + ['=0.7.x', '0.6.2'], + ['=0.7.x', '0.7.0-asdf'], + ['^1', '1.0.0-0'], + ['>=0.7.x', '0.7.0-asdf'], + ['1', '1.0.0beta', true], + ['>=0.7.x', '0.6.2'], + ['>1.2.3', '1.3.0-alpha'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'ltr(' + version + ', ' + range + ', ' + loose + ')'; + t.ok(ltr(version, range, loose), msg); + }); + t.end(); +}); + +test('\nnegative ltr tests', function(t) { + // [range, version, loose] + // Version should NOT be less than range + [ + ['~ 1.0', '1.1.0'], + ['~0.6.1-1', '0.6.1-1'], + ['1.0.0 - 2.0.0', '1.2.3'], + ['1.0.0 - 2.0.0', '2.9.9'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0', true], + ['*', '1.2.3'], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97'], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['0.1.20 || >1.2.4', '1.2.4'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['0.1.20 || 1.2.4', '0.1.20'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.0.2'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['<=0.7.x', '0.6.2'], + ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], + ['>=0.2.3 <=0.2.4', '0.2.4'], + ['1.0.0 - 2.0.0', '2.0.0'], + ['^3.0.0', '4.0.0'], + ['^1.0.0 || ~2.0.1', '2.0.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], + ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], + ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'], + ['^1.0.0alpha', '1.0.0beta', true], + ['~1.0.0alpha', '1.0.0beta', true], + ['^1.0.0-alpha', '1.0.0beta', true], + ['~1.0.0-alpha', '1.0.0beta', true], + ['^1.0.0-alpha', '1.0.0-beta'], + ['~1.0.0-alpha', '1.0.0-beta'], + ['=0.1.0', '1.0.0'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = '!ltr(' + version + ', ' + range + ', ' + loose + ')'; + t.notOk(ltr(version, range, loose), msg); + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/major-minor-patch.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/major-minor-patch.js new file mode 100644 index 0000000..e9d4039 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/major-minor-patch.js @@ -0,0 +1,72 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); + +test('\nmajor tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.3', 1], + [' 1.2.3 ', 1], + [' 2.2.3-4 ', 2], + [' 3.2.3-pre ', 3], + ['v5.2.3', 5], + [' v8.2.3 ', 8], + ['\t13.2.3', 13], + ['=21.2.3', 21, true], + ['v=34.2.3', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'major(' + range + ') = ' + version; + t.equal(semver.major(range, loose), version, msg); + }); + t.end(); +}); + +test('\nminor tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.1.3', 1], + [' 1.1.3 ', 1], + [' 1.2.3-4 ', 2], + [' 1.3.3-pre ', 3], + ['v1.5.3', 5], + [' v1.8.3 ', 8], + ['\t1.13.3', 13], + ['=1.21.3', 21, true], + ['v=1.34.3', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'minor(' + range + ') = ' + version; + t.equal(semver.minor(range, loose), version, msg); + }); + t.end(); +}); + +test('\npatch tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.1', 1], + [' 1.2.1 ', 1], + [' 1.2.2-4 ', 2], + [' 1.2.3-pre ', 3], + ['v1.2.5', 5], + [' v1.2.8 ', 8], + ['\t1.2.13', 13], + ['=1.2.21', 21, true], + ['v=1.2.34', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'patch(' + range + ') = ' + version; + t.equal(semver.patch(range, loose), version, msg); + }); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/no-module.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/no-module.js new file mode 100644 index 0000000..8b50873 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/semver/test/no-module.js @@ -0,0 +1,19 @@ +var tap = require('tap'); +var test = tap.test; + +test('no module system', function(t) { + var fs = require('fs'); + var vm = require('vm'); + var head = fs.readFileSync(require.resolve('../head.js.txt'), 'utf8'); + var src = fs.readFileSync(require.resolve('../'), 'utf8'); + var foot = fs.readFileSync(require.resolve('../foot.js.txt'), 'utf8'); + vm.runInThisContext(head + src + foot, 'semver.js'); + + // just some basic poking to see if it did some stuff + t.type(global.semver, 'object'); + t.type(global.semver.SemVer, 'function'); + t.type(global.semver.Range, 'function'); + t.ok(global.semver.satisfies('1.2.3', '1.2')); + t.end(); +}); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.npmignore new file mode 100644 index 0000000..080b47e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.npmignore @@ -0,0 +1,14 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid + +pids +logs +results + +npm-debug.log +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.travis.yml new file mode 100644 index 0000000..1d8a1a6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/README.md new file mode 100644 index 0000000..135424b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/README.md @@ -0,0 +1,81 @@ +# Tar Pack + +Package and un-package modules of some sort (in tar/gz bundles). This is mostly useful for package managers. Note that it doesn't check for or touch `package.json` so it can be used even if that's not the way you store your package info. + +[![Build Status](https://travis-ci.org/ForbesLindesay/tar-pack.png?branch=master)](https://travis-ci.org/ForbesLindesay/tar-pack) +[![Dependency Status](https://gemnasium.com/ForbesLindesay/tar-pack.png)](https://gemnasium.com/ForbesLindesay/tar-pack) +[![NPM version](https://badge.fury.io/js/tar-pack.png)](http://badge.fury.io/js/tar-pack) + +## Installation + + $ npm install tar-pack + +## API + +### pack(folder|packer, [options]) + +Pack the folder at `folder` into a gzipped tarball and return the tgz as a stream. Files ignored by `.gitignore` will not be in the package. + +You can optionally pass a `fstream.DirReader` directly, instead of folder. For example, to create an npm package, do: + +```js +pack(require("fstream-npm")(folder), [options]) +``` + +Options: + + - `noProprietary` (defaults to `false`) Set this to `true` to prevent any proprietary attributes being added to the tarball. These attributes are allowed by the spec, but may trip up some poorly written tarball parsers. + - `ignoreFiles` (defaults to `['.gitignore']`) These files can specify files to be excluded from the package using the syntax of `.gitignore`. This option is ignored if you parse a `fstream.DirReader` instead of a string for folder. + - `filter` (defaults to `entry => true`) A function that takes an entry and returns `true` if it should be included in the package and `false` if it should not. Entryies are of the form `{path, basename, dirname, type}` where (type is "Directory" or "File"). This function is ignored if you parse a `fstream.DirReader` instead of a string for folder. + +Example: + +```js +var write = require('fs').createWriteStream +var pack = require('tar-pack').pack +pack(process.cwd()) + .pipe(write(__dirname + '/package.tar.gz')) + .on('error', function (err) { + console.error(err.stack) + }) + .on('close', function () { + console.log('done') + }) +``` + +### unpack(folder, [options,] cb) + +Return a stream that unpacks a tarball into a folder at `folder`. N.B. the output folder will be removed first if it already exists. + +The callback is called with an optional error and, as its second argument, a string which is one of: + + - `'directory'`, indicating that the extracted package was a directory (either `.tar.gz` or `.tar`) + - `'file'`, incating that the extracted package was just a single file (extracted to `defaultName`, see options) + +Basic Options: + + - `defaultName` (defaults to `index.js`) If the package is a single file, rather than a tarball, it will be "extracted" to this file name, set to `false` to disable. + +Advanced Options (you probably don't need any of these): + + - `gid` - (defaults to `null`) the `gid` to use when writing files + - `uid` - (defaults to `null`) the `uid` to use when writing files + - `dmode` - (defaults to `0777`) The mode to use when creating directories + - `fmode` - (defaults to `0666`) The mode to use when creating files + - `unsafe` - (defaults to `false`) (on non win32 OSes it overrides `gid` and `uid` with the current processes IDs) + +Example: + +```js +var read = require('fs').createReadStream +var unpack = require('tar-pack').unpack +read(process.cwd() + '/package.tar.gz') + .pipe(unpack(__dirname + '/package/', function (err) { + if (err) console.error(err.stack) + else console.log('done') + })) +``` + +## License + + BSD \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/index.js new file mode 100644 index 0000000..23b95a9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/index.js @@ -0,0 +1,246 @@ +"use strict" + +var debug = require('debug')('tar-pack') +var uidNumber = require('uid-number') +var rm = require('rimraf') +var tar = require('tar') +var once = require('once') +var fstream = require('fstream') +var packer = require('fstream-ignore') + +var PassThrough = require('stream').PassThrough || require('readable-stream').PassThrough +var zlib = require('zlib') +var path = require('path') +var fs +try { + fs = require('graceful-fs') +} catch (ex) { + fs = require('fs') +} + +var win32 = process.platform === 'win32' +var myUid = process.getuid && process.getuid() +var myGid = process.getgid && process.getgid() + +if (process.env.SUDO_UID && myUid === 0) { + if (!isNaN(process.env.SUDO_UID)) myUid = +process.env.SUDO_UID + if (!isNaN(process.env.SUDO_GID)) myGid = +process.env.SUDO_GID +} + +exports.pack = pack +exports.unpack = unpack + +function pack(folder, options) { + options = options || {} + if (typeof folder === 'string') { + + var filter = options.filter || function (entry) { return true; } + + folder = packer({ + path: folder, + type: 'Directory', + isDirectory: true, + ignoreFiles: options.ignoreFiles || ['.gitignore'], + filter: function (entry) { // {path, basename, dirname, type} (type is "Directory" or "File") + var basename = entry.basename + // some files are *never* allowed under any circumstances + // these files should always be either temporary files or + // version control related files + if (basename === '.git' || basename === '.lock-wscript' || basename.match(/^\.wafpickle-[0-9]+$/) || + basename === 'CVS' || basename === '.svn' || basename === '.hg' || basename.match(/^\..*\.swp$/) || + basename === '.DS_Store' || basename.match(/^\._/)) { + return false + } + //custom excludes + return filter(entry) + } + }) + } + // By default, npm includes some proprietary attributes in the + // package tarball. This is sane, and allowed by the spec. + // However, npm *itself* excludes these from its own package, + // so that it can be more easily bootstrapped using old and + // non-compliant tar implementations. + var tarPack = tar.Pack({ noProprietary: options.noProprietary || false }) + var gzip = zlib.Gzip() + + folder + .on('error', function (er) { + if (er) debug('Error reading folder') + return gzip.emit('error', er) + }) + tarPack + .on('error', function (er) { + if (er) debug('tar creation error') + gzip.emit('error', er) + }) + return folder.pipe(tarPack).pipe(gzip) +} + +function unpack(unpackTarget, options, cb) { + if (typeof options === 'function' && cb === undefined) cb = options, options = undefined + + var tarball = new PassThrough() + if (typeof cb === 'function') { + cb = once(cb) + tarball.on('error', cb) + tarball.on('close', function () { + cb() + }) + } + + var parent = path.dirname(unpackTarget) + var base = path.basename(unpackTarget) + + options = options || {} + var gid = options.gid || null + var uid = options.uid || null + var dMode = options.dmode || 0x0777 //npm.modes.exec + var fMode = options.fmode || 0x0666 //npm.modes.file + var defaultName = options.defaultName || (options.defaultName === false ? false : 'index.js') + + // figure out who we're supposed to be, if we're not pretending + // to be a specific user. + if (options.unsafe && !win32) { + uid = myUid + gid = myGid + } + + var pending = 2 + uidNumber(uid, gid, function (er, uid, gid) { + if (er) { + tarball.emit('error', er) + return tarball.end() + } + if (0 === --pending) next() + }) + rm(unpackTarget, function (er) { + if (er) { + tarball.emit('error', er) + return tarball.end() + } + if (0 === --pending) next() + }) + function next() { + // gzip {tarball} --decompress --stdout \ + // | tar -mvxpf - --strip-components=1 -C {unpackTarget} + gunzTarPerm(tarball, unpackTarget, dMode, fMode, uid, gid, defaultName) + } + return tarball +} + + +function gunzTarPerm(tarball, target, dMode, fMode, uid, gid, defaultName) { + debug('modes %j', [dMode.toString(8), fMode.toString(8)]) + + function fixEntry(entry) { + debug('fixEntry %j', entry.path) + // never create things that are user-unreadable, + // or dirs that are user-un-listable. Only leads to headaches. + var originalMode = entry.mode = entry.mode || entry.props.mode + entry.mode = entry.mode | (entry.type === 'Directory' ? dMode : fMode) + entry.props.mode = entry.mode + if (originalMode !== entry.mode) { + debug('modified mode %j', [entry.path, originalMode, entry.mode]) + } + + // if there's a specific owner uid/gid that we want, then set that + if (!win32 && typeof uid === 'number' && typeof gid === 'number') { + entry.props.uid = entry.uid = uid + entry.props.gid = entry.gid = gid + } + } + + var extractOpts = { type: 'Directory', path: target, strip: 1 } + + if (!win32 && typeof uid === 'number' && typeof gid === 'number') { + extractOpts.uid = uid + extractOpts.gid = gid + } + + extractOpts.filter = function () { + // symbolic links are not allowed in packages. + if (this.type.match(/^.*Link$/)) { + debug('excluding symbolic link: ' + this.path.substr(target.length + 1) + ' -> ' + this.linkpath) + return false + } + return true + } + + + type(tarball, function (err, type) { + if (err) return tarball.emit('error', err) + var strm = tarball + if (type === 'gzip') { + strm = strm.pipe(zlib.Unzip()) + strm.on('error', function (er) { + if (er) debug('unzip error') + tarball.emit('error', er) + }) + type = 'tar' + } + if (type === 'tar') { + strm + .pipe(tar.Extract(extractOpts)) + .on('entry', fixEntry) + .on('error', function (er) { + if (er) debug('untar error') + tarball.emit('error', er) + }) + .on('close', function () { + tarball.emit('close') + }) + return + } + if (type === 'naked-file' && defaultName) { + var jsOpts = { path: path.resolve(target, defaultName) } + + if (!win32 && typeof uid === 'number' && typeof gid === 'number') { + jsOpts.uid = uid + jsOpts.gid = gid + } + + strm + .pipe(fstream.Writer(jsOpts)) + .on('error', function (er) { + if (er) debug('copy error') + tarball.emit('error', er) + }) + .on('close', function () { + tarball.emit('close') + }) + return + } + + return cb(new Error('Unrecognised package type')); + }) +} + +function type(stream, callback) { + stream.on('error', handle) + stream.on('data', parse) + function handle(err) { + stream.removeListener('data', parse) + stream.removeListener('error', handle) + } + function parse(chunk) { + // detect what it is. + // Then, depending on that, we'll figure out whether it's + // a single-file module, gzipped tarball, or naked tarball. + + // gzipped files all start with 1f8b08 + if (chunk[0] === 0x1F && chunk[1] === 0x8B && chunk[2] === 0x08) { + callback(null, 'gzip') + } else if (chunk.toString().match(/^package\/\u0000/)) { + // note, this will only pick up on tarballs with a root directory called package + callback(null, 'tar') + } else { + callback(null, 'naked-file') + } + + // now un-hook, and re-emit the chunk + stream.removeListener('data', parse) + stream.removeListener('error', handle) + stream.unshift(chunk) + } +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/.bin/rimraf b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/.bin/rimraf new file mode 120000 index 0000000..4cd49a4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/.bin/rimraf @@ -0,0 +1 @@ +../rimraf/bin.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/Readme.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/Readme.md new file mode 100644 index 0000000..c5a34e8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/Readme.md @@ -0,0 +1,115 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +``` +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_ + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + a('doing some work'); +}, 1200); +``` + +## License + +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/debug.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/debug.js new file mode 100644 index 0000000..509dc0d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/debug.js @@ -0,0 +1,137 @@ + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + if (!debug.enabled(name)) return function(){}; + + return function(fmt){ + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (debug[name] || curr); + debug[name] = curr; + + fmt = name + + ' ' + + fmt + + ' +' + debug.humanize(ms); + + // This hackery is required for IE8 + // where `console.log` doesn't have 'apply' + window.console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); + } +} + +/** + * The currently active debug mode names. + */ + +debug.names = []; +debug.skips = []; + +/** + * Enables a debug mode by name. This can include modes + * separated by a colon and wildcards. + * + * @param {String} name + * @api public + */ + +debug.enable = function(name) { + try { + localStorage.debug = name; + } catch(e){} + + var split = (name || '').split(/[\s,]+/) + , len = split.length; + + for (var i = 0; i < len; i++) { + name = split[i].replace('*', '.*?'); + if (name[0] === '-') { + debug.skips.push(new RegExp('^' + name.substr(1) + '$')); + } + else { + debug.names.push(new RegExp('^' + name + '$')); + } + } +}; + +/** + * Disable debug output. + * + * @api public + */ + +debug.disable = function(){ + debug.enable(''); +}; + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +debug.humanize = function(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +}; + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +debug.enabled = function(name) { + for (var i = 0, len = debug.skips.length; i < len; i++) { + if (debug.skips[i].test(name)) { + return false; + } + } + for (var i = 0, len = debug.names.length; i < len; i++) { + if (debug.names[i].test(name)) { + return true; + } + } + return false; +}; + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +// persist + +try { + if (window.localStorage) debug.enable(localStorage.debug); +} catch(e){} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/index.js new file mode 100644 index 0000000..e02c13b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/index.js @@ -0,0 +1,5 @@ +if ('undefined' == typeof window) { + module.exports = require('./lib/debug'); +} else { + module.exports = require('./debug'); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/lib/debug.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/lib/debug.js new file mode 100644 index 0000000..3b0a918 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/lib/debug.js @@ -0,0 +1,147 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Enabled debuggers. + */ + +var names = [] + , skips = []; + +(process.env.DEBUG || '') + .split(/[\s,]+/) + .forEach(function(name){ + name = name.replace('*', '.*?'); + if (name[0] === '-') { + skips.push(new RegExp('^' + name.substr(1) + '$')); + } else { + names.push(new RegExp('^' + name + '$')); + } + }); + +/** + * Colors. + */ + +var colors = [6, 2, 3, 4, 5, 1]; + +/** + * Previous debug() call. + */ + +var prev = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Is stdout a TTY? Colored output is disabled when `true`. + */ + +var isatty = tty.isatty(2); + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function color() { + return colors[prevColor++ % colors.length]; +} + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +function humanize(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +} + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + function disabled(){} + disabled.enabled = false; + + var match = skips.some(function(re){ + return re.test(name); + }); + + if (match) return disabled; + + match = names.some(function(re){ + return re.test(name); + }); + + if (!match) return disabled; + var c = color(); + + function colored(fmt) { + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (prev[name] || curr); + prev[name] = curr; + + fmt = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[3' + c + 'm\u001b[90m' + + fmt + '\u001b[3' + c + 'm' + + ' +' + humanize(ms) + '\u001b[0m'; + + console.error.apply(this, arguments); + } + + function plain(fmt) { + fmt = coerce(fmt); + + fmt = new Date().toUTCString() + + ' ' + name + ' ' + fmt; + console.error.apply(this, arguments); + } + + colored.enabled = plain.enabled = true; + + return isatty || process.env.DEBUG_COLORS + ? colored + : plain; +} + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/package.json new file mode 100644 index 0000000..c6910f2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/debug/package.json @@ -0,0 +1,63 @@ +{ + "name": "debug", + "version": "0.7.4", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*" + }, + "main": "lib/debug.js", + "browser": "./debug.js", + "engines": { + "node": "*" + }, + "files": [ + "lib/debug.js", + "debug.js", + "index.js" + ], + "component": { + "scripts": { + "debug/index.js": "index.js", + "debug/debug.js": "debug.js" + } + }, + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@0.7.4", + "dist": { + "shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", + "tarball": "http://registry.npmjs.org/debug/-/debug-0.7.4.tgz" + }, + "_from": "debug@>=0.7.2 <0.8.0", + "_npmVersion": "1.3.13", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", + "_resolved": "https://registry.npmjs.org/debug/-/debug-0.7.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/.npmignore new file mode 100644 index 0000000..a843dc4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/.npmignore @@ -0,0 +1 @@ +test/fixtures diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/README.md new file mode 100644 index 0000000..31170fe --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/README.md @@ -0,0 +1,22 @@ +# fstream-ignore + +A fstream DirReader that filters out files that match globs in `.ignore` +files throughout the tree, like how git ignores files based on a +`.gitignore` file. + +Here's an example: + +```javascript +var Ignore = require("fstream-ignore") +Ignore({ path: __dirname + , ignoreFiles: [".ignore", ".gitignore"] + }) + .on("child", function (c) { + console.error(c.path.substr(c.root.path.length + 1)) + }) + .pipe(tar.Pack()) + .pipe(fs.createWriteStream("foo.tar")) +``` + +This will tar up the files in __dirname into `foo.tar`, ignoring +anything matched by the globs in any .iginore or .gitignore file. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/example/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/example/basic.js new file mode 100644 index 0000000..ff45342 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/example/basic.js @@ -0,0 +1,13 @@ +var Ignore = require("../") +Ignore({ path: __dirname + , ignoreFiles: [".ignore", ".gitignore"] + }) + .on("child", function (c) { + console.error(c.path.substr(c.root.path.length + 1)) + c.on("ignoreFile", onIgnoreFile) + }) + .on("ignoreFile", onIgnoreFile) + +function onIgnoreFile (e) { + console.error("adding ignore file", e.path) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/ignore.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/ignore.js new file mode 100644 index 0000000..0728f7c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/ignore.js @@ -0,0 +1,275 @@ +// Essentially, this is a fstream.DirReader class, but with a +// bit of special logic to read the specified sort of ignore files, +// and a filter that prevents it from picking up anything excluded +// by those files. + +var Minimatch = require("minimatch").Minimatch +, fstream = require("fstream") +, DirReader = fstream.DirReader +, inherits = require("inherits") +, path = require("path") +, fs = require("fs") + +module.exports = IgnoreReader + +inherits(IgnoreReader, DirReader) + +function IgnoreReader (props) { + if (!(this instanceof IgnoreReader)) { + return new IgnoreReader(props) + } + + // must be a Directory type + if (typeof props === "string") { + props = { path: path.resolve(props) } + } + + props.type = "Directory" + props.Directory = true + + if (!props.ignoreFiles) props.ignoreFiles = [".ignore"] + this.ignoreFiles = props.ignoreFiles + + this.ignoreRules = null + + // ensure that .ignore files always show up at the top of the list + // that way, they can be read before proceeding to handle other + // entries in that same folder + if (props.sort) { + this._sort = props.sort === "alpha" ? alphasort : props.sort + props.sort = null + } + + this.on("entries", function () { + // if there are any ignore files in the list, then + // pause and add them. + // then, filter the list based on our ignoreRules + + var hasIg = this.entries.some(this.isIgnoreFile, this) + + if (!hasIg) return this.filterEntries() + + this.addIgnoreFiles() + }) + + // we filter entries before we know what they are. + // however, directories have to be re-tested against + // rules with a "/" appended, because "a/b/" will only + // match if "a/b" is a dir, and not otherwise. + this.on("_entryStat", function (entry, props) { + var t = entry.basename + if (!this.applyIgnores(entry.basename, + entry.type === "Directory", + entry)) { + entry.abort() + } + }.bind(this)) + + DirReader.call(this, props) +} + + +IgnoreReader.prototype.addIgnoreFiles = function () { + if (this._paused) { + this.once("resume", this.addIgnoreFiles) + return + } + if (this._ignoreFilesAdded) return + this._ignoreFilesAdded = true + + var newIg = this.entries.filter(this.isIgnoreFile, this) + , count = newIg.length + , errState = null + + if (!count) return + + this.pause() + + var then = function then (er) { + if (errState) return + if (er) return this.emit("error", errState = er) + if (-- count === 0) { + this.filterEntries() + this.resume() + } + }.bind(this) + + newIg.forEach(function (ig) { + this.addIgnoreFile(ig, then) + }, this) +} + + +IgnoreReader.prototype.isIgnoreFile = function (e) { + return e !== "." && + e !== ".." && + -1 !== this.ignoreFiles.indexOf(e) +} + + +IgnoreReader.prototype.getChildProps = function (stat) { + var props = DirReader.prototype.getChildProps.call(this, stat) + props.ignoreFiles = this.ignoreFiles + + // Directories have to be read as IgnoreReaders + // otherwise fstream.Reader will create a DirReader instead. + if (stat.isDirectory()) { + props.type = this.constructor + } + return props +} + + +IgnoreReader.prototype.addIgnoreFile = function (e, cb) { + // read the file, and then call addIgnoreRules + // if there's an error, then tell the cb about it. + + var ig = path.resolve(this.path, e) + fs.readFile(ig, function (er, data) { + if (er) return cb(er) + + this.emit("ignoreFile", e, data) + var rules = this.readRules(data, e) + this.addIgnoreRules(rules, e) + cb() + }.bind(this)) +} + + +IgnoreReader.prototype.readRules = function (buf, e) { + return buf.toString().split(/\r?\n/) +} + + +// Override this to do fancier things, like read the +// "files" array from a package.json file or something. +IgnoreReader.prototype.addIgnoreRules = function (set, e) { + // filter out anything obvious + set = set.filter(function (s) { + s = s.trim() + return s && !s.match(/^#/) + }) + + // no rules to add! + if (!set.length) return + + // now get a minimatch object for each one of these. + // Note that we need to allow dot files by default, and + // not switch the meaning of their exclusion + var mmopt = { matchBase: true, dot: true, flipNegate: true } + , mm = set.map(function (s) { + var m = new Minimatch(s, mmopt) + m.ignoreFile = e + return m + }) + + if (!this.ignoreRules) this.ignoreRules = [] + this.ignoreRules.push.apply(this.ignoreRules, mm) +} + + +IgnoreReader.prototype.filterEntries = function () { + // this exclusion is at the point where we know the list of + // entries in the dir, but don't know what they are. since + // some of them *might* be directories, we have to run the + // match in dir-mode as well, so that we'll pick up partials + // of files that will be included later. Anything included + // at this point will be checked again later once we know + // what it is. + this.entries = this.entries.filter(function (entry) { + // at this point, we don't know if it's a dir or not. + return this.applyIgnores(entry) || this.applyIgnores(entry, true) + }, this) +} + + +IgnoreReader.prototype.applyIgnores = function (entry, partial, obj) { + var included = true + + // this = /a/b/c + // entry = d + // parent /a/b sees c/d + if (this.parent && this.parent.applyIgnores) { + var pt = this.basename + "/" + entry + included = this.parent.applyIgnores(pt, partial) + } + + // Negated Rules + // Since we're *ignoring* things here, negating means that a file + // is re-included, if it would have been excluded by a previous + // rule. So, negated rules are only relevant if the file + // has been excluded. + // + // Similarly, if a file has been excluded, then there's no point + // trying it against rules that have already been applied + // + // We're using the "flipnegate" flag here, which tells minimatch + // to set the "negate" for our information, but still report + // whether the core pattern was a hit or a miss. + + if (!this.ignoreRules) { + return included + } + + this.ignoreRules.forEach(function (rule) { + // negation means inclusion + if (rule.negate && included || + !rule.negate && !included) { + // unnecessary + return + } + + // first, match against /foo/bar + var match = rule.match("/" + entry) + + if (!match) { + // try with the leading / trimmed off the test + // eg: foo/bar instead of /foo/bar + match = rule.match(entry) + } + + // if the entry is a directory, then it will match + // with a trailing slash. eg: /foo/bar/ or foo/bar/ + if (!match && partial) { + match = rule.match("/" + entry + "/") || + rule.match(entry + "/") + } + + // When including a file with a negated rule, it's + // relevant if a directory partially matches, since + // it may then match a file within it. + // Eg, if you ignore /a, but !/a/b/c + if (!match && rule.negate && partial) { + match = rule.match("/" + entry, true) || + rule.match(entry, true) + } + + if (match) { + included = rule.negate + } + }, this) + + return included +} + + +IgnoreReader.prototype.sort = function (a, b) { + var aig = this.ignoreFiles.indexOf(a) !== -1 + , big = this.ignoreFiles.indexOf(b) !== -1 + + if (aig && !big) return -1 + if (big && !aig) return 1 + return this._sort(a, b) +} + +IgnoreReader.prototype._sort = function (a, b) { + return 0 +} + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/package.json new file mode 100644 index 0000000..8c08a43 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.0 <3.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..05a4010 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/README.md new file mode 100644 index 0000000..978268e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/README.md @@ -0,0 +1,218 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +Eventually, it will replace the C binding in node-glob. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instanting the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +## Functions + +The top-level exported function has a `cache` property, which is an LRU +cache set to store 100 items. So, calling these methods repeatedly +with the same pattern and options will use the same Minimatch object, +saving the cost of parsing it multiple times. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself. When set, an empty list is returned if there are +no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/minimatch.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..c633f89 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/minimatch.js @@ -0,0 +1,1055 @@ +;(function (require, exports, module, platform) { + +if (module) module.exports = minimatch +else exports.minimatch = minimatch + +if (!require) { + require = function (id) { + switch (id) { + case "sigmund": return function sigmund (obj) { + return JSON.stringify(obj) + } + case "path": return { basename: function (f) { + f = f.split(/[\/\\]/) + var e = f.pop() + if (!e) e = f.pop() + return e + }} + case "lru-cache": return function LRUCache () { + // not quite an LRU, but still space-limited. + var cache = {} + var cnt = 0 + this.set = function (k, v) { + cnt ++ + if (cnt >= 100) cache = {} + cache[k] = v + } + this.get = function (k) { return cache[k] } + } + } + } +} + +minimatch.Minimatch = Minimatch + +var LRU = require("lru-cache") + , cache = minimatch.cache = new LRU({max: 100}) + , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} + , sigmund = require("sigmund") + +var path = require("path") + // any single thing other than / + // don't need to escape / when using new RegExp() + , qmark = "[^/]" + + // * => any number of characters + , star = qmark + "*?" + + // ** when dots are allowed. Anything goes, except .. and . + // not (^ or / followed by one or two dots followed by $ or /), + // followed by anything, any number of times. + , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" + + // not a ^ or / followed by a dot, + // followed by anything, any number of times. + , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" + + // characters that need to be escaped in RegExp. + , reSpecials = charSet("().*{}+?[]^$\\!") + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split("").reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + + +function minimatch (p, pattern, options) { + if (typeof pattern !== "string") { + throw new TypeError("glob pattern string required") + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === "#") { + return false + } + + // "" only matches "" + if (pattern.trim() === "") return p === "" + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options, cache) + } + + if (typeof pattern !== "string") { + throw new TypeError("glob pattern string required") + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows: need to use /, not \ + // On other platforms, \ is a valid (albeit bad) filename char. + if (platform === "win32") { + pattern = pattern.split("\\").join("/") + } + + // lru storage. + // these things aren't particularly big, but walking down the string + // and turning it into a regexp can get pretty costly. + var cacheKey = pattern + "\n" + sigmund(options) + var cached = minimatch.cache.get(cacheKey) + if (cached) return cached + minimatch.cache.set(cacheKey, this) + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function() {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return -1 === s.indexOf(false) + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + , negate = false + , options = this.options + , negateOffset = 0 + + if (options.nonegate) return + + for ( var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === "!" + ; i ++) { + negate = !negate + negateOffset ++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return new Minimatch(pattern, options).braceExpand() +} + +Minimatch.prototype.braceExpand = braceExpand +function braceExpand (pattern, options) { + options = options || this.options + pattern = typeof pattern === "undefined" + ? this.pattern : pattern + + if (typeof pattern === "undefined") { + throw new Error("undefined pattern") + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + var escaping = false + + // examples and comments refer to this crazy pattern: + // a{b,c{d,e},{f,g}h}x{y,z} + // expected: + // abxy + // abxz + // acdxy + // acdxz + // acexy + // acexz + // afhxy + // afhxz + // aghxy + // aghxz + + // everything before the first \{ is just a prefix. + // So, we pluck that off, and work with the rest, + // and then prepend it to everything we find. + if (pattern.charAt(0) !== "{") { + this.debug(pattern) + var prefix = null + for (var i = 0, l = pattern.length; i < l; i ++) { + var c = pattern.charAt(i) + this.debug(i, c) + if (c === "\\") { + escaping = !escaping + } else if (c === "{" && !escaping) { + prefix = pattern.substr(0, i) + break + } + } + + // actually no sets, all { were escaped. + if (prefix === null) { + this.debug("no sets") + return [pattern] + } + + var tail = braceExpand.call(this, pattern.substr(i), options) + return tail.map(function (t) { + return prefix + t + }) + } + + // now we have something like: + // {b,c{d,e},{f,g}h}x{y,z} + // walk through the set, expanding each part, until + // the set ends. then, we'll expand the suffix. + // If the set only has a single member, then'll put the {} back + + // first, handle numeric sets, since they're easier + var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/) + if (numset) { + this.debug("numset", numset[1], numset[2]) + var suf = braceExpand.call(this, pattern.substr(numset[0].length), options) + , start = +numset[1] + , end = +numset[2] + , inc = start > end ? -1 : 1 + , set = [] + for (var i = start; i != (end + inc); i += inc) { + // append all the suffixes + for (var ii = 0, ll = suf.length; ii < ll; ii ++) { + set.push(i + suf[ii]) + } + } + return set + } + + // ok, walk through the set + // We hope, somewhat optimistically, that there + // will be a } at the end. + // If the closing brace isn't found, then the pattern is + // interpreted as braceExpand("\\" + pattern) so that + // the leading \{ will be interpreted literally. + var i = 1 // skip the \{ + , depth = 1 + , set = [] + , member = "" + , sawEnd = false + , escaping = false + + function addMember () { + set.push(member) + member = "" + } + + this.debug("Entering for") + FOR: for (i = 1, l = pattern.length; i < l; i ++) { + var c = pattern.charAt(i) + this.debug("", i, c) + + if (escaping) { + escaping = false + member += "\\" + c + } else { + switch (c) { + case "\\": + escaping = true + continue + + case "{": + depth ++ + member += "{" + continue + + case "}": + depth -- + // if this closes the actual set, then we're done + if (depth === 0) { + addMember() + // pluck off the close-brace + i ++ + break FOR + } else { + member += c + continue + } + + case ",": + if (depth === 1) { + addMember() + } else { + member += c + } + continue + + default: + member += c + continue + } // switch + } // else + } // for + + // now we've either finished the set, and the suffix is + // pattern.substr(i), or we have *not* closed the set, + // and need to escape the leading brace + if (depth !== 0) { + this.debug("didn't close", pattern) + return braceExpand.call(this, "\\" + pattern, options) + } + + // x{y,z} -> ["xy", "xz"] + this.debug("set", set) + this.debug("suffix", pattern.substr(i)) + var suf = braceExpand.call(this, pattern.substr(i), options) + // ["b", "c{d,e}","{f,g}h"] -> + // [["b"], ["cd", "ce"], ["fh", "gh"]] + var addBraces = set.length === 1 + this.debug("set pre-expanded", set) + set = set.map(function (p) { + return braceExpand.call(this, p, options) + }, this) + this.debug("set expanded", set) + + + // [["b"], ["cd", "ce"], ["fh", "gh"]] -> + // ["b", "cd", "ce", "fh", "gh"] + set = set.reduce(function (l, r) { + return l.concat(r) + }) + + if (addBraces) { + set = set.map(function (s) { + return "{" + s + "}" + }) + } + + // now attach the suffixes. + var ret = [] + for (var i = 0, l = set.length; i < l; i ++) { + for (var ii = 0, ll = suf.length; ii < ll; ii ++) { + ret.push(set[i] + suf[ii]) + } + } + return ret +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === "**") return GLOBSTAR + if (pattern === "") return "" + + var re = "" + , hasMagic = !!options.nocase + , escaping = false + // ? => one single character + , patternListStack = [] + , plType + , stateChar + , inClass = false + , reClassStart = -1 + , classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + , patternStart = pattern.charAt(0) === "." ? "" // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" + : "(?!\\.)" + , self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case "*": + re += star + hasMagic = true + break + case "?": + re += qmark + hasMagic = true + break + default: + re += "\\"+stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for ( var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i ++ ) { + + this.debug("%s\t%s %s %j", pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += "\\" + c + escaping = false + continue + } + + SWITCH: switch (c) { + case "/": + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case "\\": + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case "?": + case "*": + case "+": + case "@": + case "!": + this.debug("%s\t%s %s %j <-- stateChar", pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === "!" && i === classStart + 1) c = "^" + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case "(": + if (inClass) { + re += "(" + continue + } + + if (!stateChar) { + re += "\\(" + continue + } + + plType = stateChar + patternListStack.push({ type: plType + , start: i - 1 + , reStart: re.length }) + // negation is (?:(?!js)[^/]*) + re += stateChar === "!" ? "(?:(?!" : "(?:" + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ")": + if (inClass || !patternListStack.length) { + re += "\\)" + continue + } + + clearStateChar() + hasMagic = true + re += ")" + plType = patternListStack.pop().type + // negation is (?:(?!js)[^/]*) + // The others are (?:) + switch (plType) { + case "!": + re += "[^/]*?)" + break + case "?": + case "+": + case "*": re += plType + case "@": break // the default anyway + } + continue + + case "|": + if (inClass || !patternListStack.length || escaping) { + re += "\\|" + escaping = false + continue + } + + clearStateChar() + re += "|" + continue + + // these are mostly the same in regexp and glob + case "[": + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += "\\" + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case "]": + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += "\\" + c + escaping = false + continue + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === "^" && inClass)) { + re += "\\" + } + + re += c + + } // switch + } // for + + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + var cs = pattern.substr(classStart + 1) + , sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + "\\[" + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + var pl + while (pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = "\\" + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + "|" + }) + + this.debug("tail=%j\n %s", tail, tail) + var t = pl.type === "*" ? star + : pl.type === "?" ? qmark + : "\\" + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + + t + "\\(" + + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += "\\\\" + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case ".": + case "[": + case "(": addPatternStart = true + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== "" && hasMagic) re = "(?=.)" + re + + if (addPatternStart) re = patternStart + re + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [ re, hasMagic ] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? "i" : "" + , regExp = new RegExp("^" + re + "$", flags) + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) return this.regexp = false + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + , flags = options.nocase ? "i" : "" + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === "string") ? regExpEscape(p) + : p._src + }).join("\\\/") + }).join("|") + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = "^(?:" + re + ")$" + + // can match anything, as long as it's not this. + if (this.negate) re = "^(?!" + re + ").*$" + + try { + return this.regexp = new RegExp(re, flags) + } catch (ex) { + return this.regexp = false + } +} + +minimatch.match = function (list, pattern, options) { + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug("match", f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === "" + + if (f === "/" && partial) return true + + var options = this.options + + // windows: need to use /, not \ + // On other platforms, \ is a valid (albeit bad) filename char. + if (platform === "win32") { + f = f.split("\\").join("/") + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, "split", f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, "set", set) + + var splitFile = path.basename(f.join("/")).split("/") + + for (var i = 0, l = set.length; i < l; i ++) { + var pattern = set[i], file = f + if (options.matchBase && pattern.length === 1) { + file = splitFile + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug("matchOne", + { "this": this + , file: file + , pattern: pattern }) + + this.debug("matchOne", file.length, pattern.length) + + for ( var fi = 0 + , pi = 0 + , fl = file.length + , pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi ++, pi ++ ) { + + this.debug("matchOne loop") + var p = pattern[pi] + , f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + , pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for ( ; fi < fl; fi ++) { + if (file[fi] === "." || file[fi] === ".." || + (!options.dot && file[fi].charAt(0) === ".")) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + WHILE: while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', + file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === "." || swallowee === ".." || + (!options.dot && swallowee.charAt(0) === ".")) { + this.debug("dot detected!", file, fr, pattern, pr) + break WHILE + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr ++ + } + } + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug("\n>>> no match, partial?", file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === "string") { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug("string match", p, f, hit) + } else { + hit = f.match(p) + this.debug("pattern match", p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === "") + return emptyFileEnd + } + + // should be unreachable. + throw new Error("wtf?") +} + + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, "$1") +} + + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") +} + +})( typeof require === "function" ? require : null, + this, + typeof module === "object" ? module : null, + typeof process === "object" ? process.platform : "win32" + ) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/.npmignore new file mode 100644 index 0000000..07e6e47 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/.npmignore @@ -0,0 +1 @@ +/node_modules diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS new file mode 100644 index 0000000..4a0bc50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS @@ -0,0 +1,14 @@ +# Authors, sorted by whether or not they are me +Isaac Z. Schlueter +Brian Cottingham +Carlos Brito Lage +Jesse Dailey +Kevin O'Hara +Marco Rogers +Mark Cavage +Marko Mikulicic +Nathan Rajlich +Satheesh Natesan +Trent Mick +ashleybrener +n4kz diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/README.md new file mode 100644 index 0000000..82a6dab --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/README.md @@ -0,0 +1,109 @@ +# lru cache + +A cache object that deletes the least-recently-used items. + +## Usage: + +```javascript +var LRU = require("lru-cache") + , options = { max: 500 + , length: function (n) { return n * 2 } + , dispose: function (key, n) { n.close() } + , maxAge: 1000 * 60 * 60 } + , cache = LRU(options) + , otherCache = LRU(50) // sets just the max size + +cache.set("key", "value") +cache.get("key") // "value" + +cache.reset() // empty the cache +``` + +If you put more stuff in it, then items will fall out. + +If you try to put an oversized thing in it, then it'll fall out right +away. + +## Options + +* `max` The maximum size of the cache, checked by applying the length + function to all values in the cache. Not setting this is kind of + silly, since that's the whole purpose of this lib, but it defaults + to `Infinity`. +* `maxAge` Maximum age in ms. Items are not pro-actively pruned out + as they age, but if you try to get an item that is too old, it'll + drop it and return undefined instead of giving it to you. +* `length` Function that is used to calculate the length of stored + items. If you're storing strings or buffers, then you probably want + to do something like `function(n){return n.length}`. The default is + `function(n){return 1}`, which is fine if you want to store `n` + like-sized things. +* `dispose` Function that is called on items when they are dropped + from the cache. This can be handy if you want to close file + descriptors or do other cleanup tasks when items are no longer + accessible. Called with `key, value`. It's called *before* + actually removing the item from the internal cache, so if you want + to immediately put it back in, you'll have to do that in a + `nextTick` or `setTimeout` callback or it won't do anything. +* `stale` By default, if you set a `maxAge`, it'll only actually pull + stale items out of the cache when you `get(key)`. (That is, it's + not pre-emptively doing a `setTimeout` or anything.) If you set + `stale:true`, it'll return the stale value before deleting it. If + you don't set this, then it'll return `undefined` when you try to + get a stale entry, as if it had already been deleted. + +## API + +* `set(key, value, max)` +* `get(key) => value` + + Both of these will update the "recently used"-ness of the key. + They do what you think. `max` is optional and overrides the + cache `max` option if provided. + +* `peek(key)` + + Returns the key value (or `undefined` if not found) without + updating the "recently used"-ness of the key. + + (If you find yourself using this a lot, you *might* be using the + wrong sort of data structure, but there are some use cases where + it's handy.) + +* `del(key)` + + Deletes a key out of the cache. + +* `reset()` + + Clear the cache entirely, throwing away all values. + +* `has(key)` + + Check if a key is in the cache, without updating the recent-ness + or deleting it for being stale. + +* `forEach(function(value,key,cache), [thisp])` + + Just like `Array.prototype.forEach`. Iterates over all the keys + in the cache, in order of recent-ness. (Ie, more recently used + items are iterated over first.) + +* `keys()` + + Return an array of the keys in the cache. + +* `values()` + + Return an array of the values in the cache. + +* `length()` + + Return total length of objects in cache taking into account + `length` options function. + +* `itemCount()` + + Return total quantity of objects currently in cache. Note, that + `stale` (see options) items are returned as part of this item + count. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js new file mode 100644 index 0000000..d66e7a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js @@ -0,0 +1,274 @@ +;(function () { // closure for web browsers + +if (typeof module === 'object' && module.exports) { + module.exports = LRUCache +} else { + // just set the global for non-node platforms. + this.LRUCache = LRUCache +} + +function hOP (obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key) +} + +function naiveLength () { return 1 } + +function LRUCache (options) { + if (!(this instanceof LRUCache)) + return new LRUCache(options) + + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + this._max = options.max + // Kind of weird to have a default max of Infinity, but oh well. + if (!this._max || !(typeof this._max === "number") || this._max <= 0 ) + this._max = Infinity + + this._lengthCalculator = options.length || naiveLength + if (typeof this._lengthCalculator !== "function") + this._lengthCalculator = naiveLength + + this._allowStale = options.stale || false + this._maxAge = options.maxAge || null + this._dispose = options.dispose + this.reset() +} + +// resize the cache when the max changes. +Object.defineProperty(LRUCache.prototype, "max", + { set : function (mL) { + if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity + this._max = mL + if (this._length > this._max) trim(this) + } + , get : function () { return this._max } + , enumerable : true + }) + +// resize the cache when the lengthCalculator changes. +Object.defineProperty(LRUCache.prototype, "lengthCalculator", + { set : function (lC) { + if (typeof lC !== "function") { + this._lengthCalculator = naiveLength + this._length = this._itemCount + for (var key in this._cache) { + this._cache[key].length = 1 + } + } else { + this._lengthCalculator = lC + this._length = 0 + for (var key in this._cache) { + this._cache[key].length = this._lengthCalculator(this._cache[key].value) + this._length += this._cache[key].length + } + } + + if (this._length > this._max) trim(this) + } + , get : function () { return this._lengthCalculator } + , enumerable : true + }) + +Object.defineProperty(LRUCache.prototype, "length", + { get : function () { return this._length } + , enumerable : true + }) + + +Object.defineProperty(LRUCache.prototype, "itemCount", + { get : function () { return this._itemCount } + , enumerable : true + }) + +LRUCache.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + var i = 0 + var itemCount = this._itemCount + + for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) { + i++ + var hit = this._lruList[k] + if (isStale(this, hit)) { + del(this, hit) + if (!this._allowStale) hit = undefined + } + if (hit) { + fn.call(thisp, hit.value, hit.key, this) + } + } +} + +LRUCache.prototype.keys = function () { + var keys = new Array(this._itemCount) + var i = 0 + for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { + var hit = this._lruList[k] + keys[i++] = hit.key + } + return keys +} + +LRUCache.prototype.values = function () { + var values = new Array(this._itemCount) + var i = 0 + for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { + var hit = this._lruList[k] + values[i++] = hit.value + } + return values +} + +LRUCache.prototype.reset = function () { + if (this._dispose && this._cache) { + for (var k in this._cache) { + this._dispose(k, this._cache[k].value) + } + } + + this._cache = Object.create(null) // hash of items by key + this._lruList = Object.create(null) // list of items in order of use recency + this._mru = 0 // most recently used + this._lru = 0 // least recently used + this._length = 0 // number of items in the list + this._itemCount = 0 +} + +// Provided for debugging/dev purposes only. No promises whatsoever that +// this API stays stable. +LRUCache.prototype.dump = function () { + return this._cache +} + +LRUCache.prototype.dumpLru = function () { + return this._lruList +} + +LRUCache.prototype.set = function (key, value, maxAge) { + maxAge = maxAge || this._maxAge + var now = maxAge ? Date.now() : 0 + + if (hOP(this._cache, key)) { + // dispose of the old one before overwriting + if (this._dispose) + this._dispose(key, this._cache[key].value) + + this._cache[key].now = now + this._cache[key].maxAge = maxAge + this._cache[key].value = value + this.get(key) + return true + } + + var len = this._lengthCalculator(value) + var hit = new Entry(key, value, this._mru++, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this._max) { + if (this._dispose) this._dispose(key, value) + return false + } + + this._length += hit.length + this._lruList[hit.lu] = this._cache[key] = hit + this._itemCount ++ + + if (this._length > this._max) + trim(this) + + return true +} + +LRUCache.prototype.has = function (key) { + if (!hOP(this._cache, key)) return false + var hit = this._cache[key] + if (isStale(this, hit)) { + return false + } + return true +} + +LRUCache.prototype.get = function (key) { + return get(this, key, true) +} + +LRUCache.prototype.peek = function (key) { + return get(this, key, false) +} + +LRUCache.prototype.pop = function () { + var hit = this._lruList[this._lru] + del(this, hit) + return hit || null +} + +LRUCache.prototype.del = function (key) { + del(this, this._cache[key]) +} + +function get (self, key, doUse) { + var hit = self._cache[key] + if (hit) { + if (isStale(self, hit)) { + del(self, hit) + if (!self._allowStale) hit = undefined + } else { + if (doUse) use(self, hit) + } + if (hit) hit = hit.value + } + return hit +} + +function isStale(self, hit) { + if (!hit || (!hit.maxAge && !self._maxAge)) return false + var stale = false; + var diff = Date.now() - hit.now + if (hit.maxAge) { + stale = diff > hit.maxAge + } else { + stale = self._maxAge && (diff > self._maxAge) + } + return stale; +} + +function use (self, hit) { + shiftLU(self, hit) + hit.lu = self._mru ++ + self._lruList[hit.lu] = hit +} + +function trim (self) { + while (self._lru < self._mru && self._length > self._max) + del(self, self._lruList[self._lru]) +} + +function shiftLU (self, hit) { + delete self._lruList[ hit.lu ] + while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++ +} + +function del (self, hit) { + if (hit) { + if (self._dispose) self._dispose(hit.key, hit.value) + self._length -= hit.length + self._itemCount -- + delete self._cache[ hit.key ] + shiftLU(self, hit) + } +} + +// classy, since V8 prefers predictable objects. +function Entry (key, value, lu, length, now, maxAge) { + this.key = key + this.value = value + this.lu = lu + this.length = length + this.now = now + if (maxAge) this.maxAge = maxAge +} + +})() diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/package.json new file mode 100644 index 0000000..f680462 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/package.json @@ -0,0 +1,58 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "2.6.4", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "keywords": [ + "mru", + "lru", + "cache" + ], + "scripts": { + "test": "tap test --gc" + }, + "main": "lib/lru-cache.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-lru-cache.git" + }, + "devDependencies": { + "tap": "^0.7.1", + "weak": "" + }, + "license": "ISC", + "gitHead": "aea58fc0a12714c6e1422963e7ebea66460ec39e", + "bugs": { + "url": "https://github.com/isaacs/node-lru-cache/issues" + }, + "homepage": "https://github.com/isaacs/node-lru-cache#readme", + "_id": "lru-cache@2.6.4", + "_shasum": "2675190ccd1b0701ec2f652a4d0d3d400d76c0dd", + "_from": "lru-cache@>=2.0.0 <3.0.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "2675190ccd1b0701ec2f652a4d0d3d400d76c0dd", + "tarball": "http://registry.npmjs.org/lru-cache/-/lru-cache-2.6.4.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.6.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/basic.js new file mode 100644 index 0000000..949113e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/basic.js @@ -0,0 +1,395 @@ +var test = require("tap").test + , LRU = require("../") + +test("basic", function (t) { + var cache = new LRU({max: 10}) + cache.set("key", "value") + t.equal(cache.get("key"), "value") + t.equal(cache.get("nada"), undefined) + t.equal(cache.length, 1) + t.equal(cache.max, 10) + t.end() +}) + +test("least recently set", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.set("b", "B") + cache.set("c", "C") + t.equal(cache.get("c"), "C") + t.equal(cache.get("b"), "B") + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("lru recently gotten", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.set("b", "B") + cache.get("a") + cache.set("c", "C") + t.equal(cache.get("c"), "C") + t.equal(cache.get("b"), undefined) + t.equal(cache.get("a"), "A") + t.end() +}) + +test("del", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.del("a") + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("max", function (t) { + var cache = new LRU(3) + + // test changing the max, verify that the LRU items get dropped. + cache.max = 100 + for (var i = 0; i < 100; i ++) cache.set(i, i) + t.equal(cache.length, 100) + for (var i = 0; i < 100; i ++) { + t.equal(cache.get(i), i) + } + cache.max = 3 + t.equal(cache.length, 3) + for (var i = 0; i < 97; i ++) { + t.equal(cache.get(i), undefined) + } + for (var i = 98; i < 100; i ++) { + t.equal(cache.get(i), i) + } + + // now remove the max restriction, and try again. + cache.max = "hello" + for (var i = 0; i < 100; i ++) cache.set(i, i) + t.equal(cache.length, 100) + for (var i = 0; i < 100; i ++) { + t.equal(cache.get(i), i) + } + // should trigger an immediate resize + cache.max = 3 + t.equal(cache.length, 3) + for (var i = 0; i < 97; i ++) { + t.equal(cache.get(i), undefined) + } + for (var i = 98; i < 100; i ++) { + t.equal(cache.get(i), i) + } + t.end() +}) + +test("reset", function (t) { + var cache = new LRU(10) + cache.set("a", "A") + cache.set("b", "B") + cache.reset() + t.equal(cache.length, 0) + t.equal(cache.max, 10) + t.equal(cache.get("a"), undefined) + t.equal(cache.get("b"), undefined) + t.end() +}) + + +// Note: `.dump()` is a debugging tool only. No guarantees are made +// about the format/layout of the response. +test("dump", function (t) { + var cache = new LRU(10) + var d = cache.dump(); + t.equal(Object.keys(d).length, 0, "nothing in dump for empty cache") + cache.set("a", "A") + var d = cache.dump() // { a: { key: "a", value: "A", lu: 0 } } + t.ok(d.a) + t.equal(d.a.key, "a") + t.equal(d.a.value, "A") + t.equal(d.a.lu, 0) + + cache.set("b", "B") + cache.get("b") + d = cache.dump() + t.ok(d.b) + t.equal(d.b.key, "b") + t.equal(d.b.value, "B") + t.equal(d.b.lu, 2) + + t.end() +}) + + +test("basic with weighed length", function (t) { + var cache = new LRU({ + max: 100, + length: function (item) { return item.size } + }) + cache.set("key", {val: "value", size: 50}) + t.equal(cache.get("key").val, "value") + t.equal(cache.get("nada"), undefined) + t.equal(cache.lengthCalculator(cache.get("key")), 50) + t.equal(cache.length, 50) + t.equal(cache.max, 100) + t.end() +}) + + +test("weighed length item too large", function (t) { + var cache = new LRU({ + max: 10, + length: function (item) { return item.size } + }) + t.equal(cache.max, 10) + + // should fall out immediately + cache.set("key", {val: "value", size: 50}) + + t.equal(cache.length, 0) + t.equal(cache.get("key"), undefined) + t.end() +}) + +test("least recently set with weighed length", function (t) { + var cache = new LRU({ + max:8, + length: function (item) { return item.length } + }) + cache.set("a", "A") + cache.set("b", "BB") + cache.set("c", "CCC") + cache.set("d", "DDDD") + t.equal(cache.get("d"), "DDDD") + t.equal(cache.get("c"), "CCC") + t.equal(cache.get("b"), undefined) + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("lru recently gotten with weighed length", function (t) { + var cache = new LRU({ + max: 8, + length: function (item) { return item.length } + }) + cache.set("a", "A") + cache.set("b", "BB") + cache.set("c", "CCC") + cache.get("a") + cache.get("b") + cache.set("d", "DDDD") + t.equal(cache.get("c"), undefined) + t.equal(cache.get("d"), "DDDD") + t.equal(cache.get("b"), "BB") + t.equal(cache.get("a"), "A") + t.end() +}) + +test("set returns proper booleans", function(t) { + var cache = new LRU({ + max: 5, + length: function (item) { return item.length } + }) + + t.equal(cache.set("a", "A"), true) + + // should return false for max exceeded + t.equal(cache.set("b", "donuts"), false) + + t.equal(cache.set("b", "B"), true) + t.equal(cache.set("c", "CCCC"), true) + t.end() +}) + +test("drop the old items", function(t) { + var cache = new LRU({ + max: 5, + maxAge: 50 + }) + + cache.set("a", "A") + + setTimeout(function () { + cache.set("b", "b") + t.equal(cache.get("a"), "A") + }, 25) + + setTimeout(function () { + cache.set("c", "C") + // timed out + t.notOk(cache.get("a")) + }, 60 + 25) + + setTimeout(function () { + t.notOk(cache.get("b")) + t.equal(cache.get("c"), "C") + }, 90) + + setTimeout(function () { + t.notOk(cache.get("c")) + t.end() + }, 155) +}) + +test("individual item can have it's own maxAge", function(t) { + var cache = new LRU({ + max: 5, + maxAge: 50 + }) + + cache.set("a", "A", 20) + setTimeout(function () { + t.notOk(cache.get("a")) + t.end() + }, 25) +}) + +test("individual item can have it's own maxAge > cache's", function(t) { + var cache = new LRU({ + max: 5, + maxAge: 20 + }) + + cache.set("a", "A", 50) + setTimeout(function () { + t.equal(cache.get("a"), "A") + t.end() + }, 25) +}) + +test("disposal function", function(t) { + var disposed = false + var cache = new LRU({ + max: 1, + dispose: function (k, n) { + disposed = n + } + }) + + cache.set(1, 1) + cache.set(2, 2) + t.equal(disposed, 1) + cache.set(3, 3) + t.equal(disposed, 2) + cache.reset() + t.equal(disposed, 3) + t.end() +}) + +test("disposal function on too big of item", function(t) { + var disposed = false + var cache = new LRU({ + max: 1, + length: function (k) { + return k.length + }, + dispose: function (k, n) { + disposed = n + } + }) + var obj = [ 1, 2 ] + + t.equal(disposed, false) + cache.set("obj", obj) + t.equal(disposed, obj) + t.end() +}) + +test("has()", function(t) { + var cache = new LRU({ + max: 1, + maxAge: 10 + }) + + cache.set('foo', 'bar') + t.equal(cache.has('foo'), true) + cache.set('blu', 'baz') + t.equal(cache.has('foo'), false) + t.equal(cache.has('blu'), true) + setTimeout(function() { + t.equal(cache.has('blu'), false) + t.end() + }, 15) +}) + +test("stale", function(t) { + var cache = new LRU({ + maxAge: 10, + stale: true + }) + + cache.set('foo', 'bar') + t.equal(cache.get('foo'), 'bar') + t.equal(cache.has('foo'), true) + setTimeout(function() { + t.equal(cache.has('foo'), false) + t.equal(cache.get('foo'), 'bar') + t.equal(cache.get('foo'), undefined) + t.end() + }, 15) +}) + +test("lru update via set", function(t) { + var cache = LRU({ max: 2 }); + + cache.set('foo', 1); + cache.set('bar', 2); + cache.del('bar'); + cache.set('baz', 3); + cache.set('qux', 4); + + t.equal(cache.get('foo'), undefined) + t.equal(cache.get('bar'), undefined) + t.equal(cache.get('baz'), 3) + t.equal(cache.get('qux'), 4) + t.end() +}) + +test("least recently set w/ peek", function (t) { + var cache = new LRU(2) + cache.set("a", "A") + cache.set("b", "B") + t.equal(cache.peek("a"), "A") + cache.set("c", "C") + t.equal(cache.get("c"), "C") + t.equal(cache.get("b"), "B") + t.equal(cache.get("a"), undefined) + t.end() +}) + +test("pop the least used item", function (t) { + var cache = new LRU(3) + , last + + cache.set("a", "A") + cache.set("b", "B") + cache.set("c", "C") + + t.equal(cache.length, 3) + t.equal(cache.max, 3) + + // Ensure we pop a, c, b + cache.get("b", "B") + + last = cache.pop() + t.equal(last.key, "a") + t.equal(last.value, "A") + t.equal(cache.length, 2) + t.equal(cache.max, 3) + + last = cache.pop() + t.equal(last.key, "c") + t.equal(last.value, "C") + t.equal(cache.length, 1) + t.equal(cache.max, 3) + + last = cache.pop() + t.equal(last.key, "b") + t.equal(last.value, "B") + t.equal(cache.length, 0) + t.equal(cache.max, 3) + + last = cache.pop() + t.equal(last, null) + t.equal(cache.length, 0) + t.equal(cache.max, 3) + + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/foreach.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/foreach.js new file mode 100644 index 0000000..429ebc1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/foreach.js @@ -0,0 +1,121 @@ +var test = require('tap').test +var LRU = require('../') + +test('forEach', function (t) { + var l = new LRU(5) + for (var i = 0; i < 10; i ++) { + l.set(i.toString(), i.toString(2)) + } + + var i = 9 + l.forEach(function (val, key, cache) { + t.equal(cache, l) + t.equal(key, i.toString()) + t.equal(val, i.toString(2)) + i -= 1 + }) + + // get in order of most recently used + l.get(6) + l.get(8) + + var order = [ 8, 6, 9, 7, 5 ] + var i = 0 + + l.forEach(function (val, key, cache) { + var j = order[i ++] + t.equal(cache, l) + t.equal(key, j.toString()) + t.equal(val, j.toString(2)) + }) + t.equal(i, order.length); + + t.end() +}) + +test('keys() and values()', function (t) { + var l = new LRU(5) + for (var i = 0; i < 10; i ++) { + l.set(i.toString(), i.toString(2)) + } + + t.similar(l.keys(), ['9', '8', '7', '6', '5']) + t.similar(l.values(), ['1001', '1000', '111', '110', '101']) + + // get in order of most recently used + l.get(6) + l.get(8) + + t.similar(l.keys(), ['8', '6', '9', '7', '5']) + t.similar(l.values(), ['1000', '110', '1001', '111', '101']) + + t.end() +}) + +test('all entries are iterated over', function(t) { + var l = new LRU(5) + for (var i = 0; i < 10; i ++) { + l.set(i.toString(), i.toString(2)) + } + + var i = 0 + l.forEach(function (val, key, cache) { + if (i > 0) { + cache.del(key) + } + i += 1 + }) + + t.equal(i, 5) + t.equal(l.keys().length, 1) + + t.end() +}) + +test('all stale entries are removed', function(t) { + var l = new LRU({ max: 5, maxAge: -5, stale: true }) + for (var i = 0; i < 10; i ++) { + l.set(i.toString(), i.toString(2)) + } + + var i = 0 + l.forEach(function () { + i += 1 + }) + + t.equal(i, 5) + t.equal(l.keys().length, 0) + + t.end() +}) + +test('expires', function (t) { + var l = new LRU({ + max: 10, + maxAge: 50 + }) + for (var i = 0; i < 10; i++) { + l.set(i.toString(), i.toString(2), ((i % 2) ? 25 : undefined)) + } + + var i = 0 + var order = [ 8, 6, 4, 2, 0 ] + setTimeout(function () { + l.forEach(function (val, key, cache) { + var j = order[i++] + t.equal(cache, l) + t.equal(key, j.toString()) + t.equal(val, j.toString(2)) + }) + t.equal(i, order.length); + t.end() + + setTimeout(function () { + var count = 0; + l.forEach(function (val, key, cache) { count++; }) + t.equal(0, count); + t.end() + }, 25) + + }, 26) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js new file mode 100644 index 0000000..7af45b0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js @@ -0,0 +1,50 @@ +#!/usr/bin/env node --expose_gc + +var weak = require('weak'); +var test = require('tap').test +var LRU = require('../') +var l = new LRU({ max: 10 }) +var refs = 0 +function X() { + refs ++ + weak(this, deref) +} + +function deref() { + refs -- +} + +test('no leaks', function (t) { + // fill up the cache + for (var i = 0; i < 100; i++) { + l.set(i, new X); + // throw some gets in there, too. + if (i % 2 === 0) + l.get(i / 2) + } + + gc() + + var start = process.memoryUsage() + + // capture the memory + var startRefs = refs + + // do it again, but more + for (var i = 0; i < 10000; i++) { + l.set(i, new X); + // throw some gets in there, too. + if (i % 2 === 0) + l.get(i / 2) + } + + gc() + + var end = process.memoryUsage() + t.equal(refs, startRefs, 'no leaky refs') + + console.error('start: %j\n' + + 'end: %j', start, end); + t.pass(); + t.end(); +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/README.md new file mode 100644 index 0000000..25a38a5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/README.md @@ -0,0 +1,53 @@ +# sigmund + +Quick and dirty signatures for Objects. + +This is like a much faster `deepEquals` comparison, which returns a +string key suitable for caches and the like. + +## Usage + +```javascript +function doSomething (someObj) { + var key = sigmund(someObj, maxDepth) // max depth defaults to 10 + var cached = cache.get(key) + if (cached) return cached + + var result = expensiveCalculation(someObj) + cache.set(key, result) + return result +} +``` + +The resulting key will be as unique and reproducible as calling +`JSON.stringify` or `util.inspect` on the object, but is much faster. +In order to achieve this speed, some differences are glossed over. +For example, the object `{0:'foo'}` will be treated identically to the +array `['foo']`. + +Also, just as there is no way to summon the soul from the scribblings +of a cocaine-addled psychoanalyst, there is no way to revive the object +from the signature string that sigmund gives you. In fact, it's +barely even readable. + +As with `util.inspect` and `JSON.stringify`, larger objects will +produce larger signature strings. + +Because sigmund is a bit less strict than the more thorough +alternatives, the strings will be shorter, and also there is a +slightly higher chance for collisions. For example, these objects +have the same signature: + + var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]} + var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']} + +Like a good Freudian, sigmund is most effective when you already have +some understanding of what you're looking for. It can help you help +yourself, but you must be willing to do some work as well. + +Cycles are handled, and cyclical objects are silently omitted (though +the key is included in the signature output.) + +The second argument is the maximum depth, which defaults to 10, +because that is the maximum object traversal depth covered by most +insurance carriers. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/bench.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/bench.js new file mode 100644 index 0000000..5acfd6d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/bench.js @@ -0,0 +1,283 @@ +// different ways to id objects +// use a req/res pair, since it's crazy deep and cyclical + +// sparseFE10 and sigmund are usually pretty close, which is to be expected, +// since they are essentially the same algorithm, except that sigmund handles +// regular expression objects properly. + + +var http = require('http') +var util = require('util') +var sigmund = require('./sigmund.js') +var sreq, sres, creq, cres, test + +http.createServer(function (q, s) { + sreq = q + sres = s + sres.end('ok') + this.close(function () { setTimeout(function () { + start() + }, 200) }) +}).listen(1337, function () { + creq = http.get({ port: 1337 }) + creq.on('response', function (s) { cres = s }) +}) + +function start () { + test = [sreq, sres, creq, cres] + // test = sreq + // sreq.sres = sres + // sreq.creq = creq + // sreq.cres = cres + + for (var i in exports.compare) { + console.log(i) + var hash = exports.compare[i]() + console.log(hash) + console.log(hash.length) + console.log('') + } + + require('bench').runMain() +} + +function customWs (obj, md, d) { + d = d || 0 + var to = typeof obj + if (to === 'undefined' || to === 'function' || to === null) return '' + if (d > md || !obj || to !== 'object') return ('' + obj).replace(/[\n ]+/g, '') + + if (Array.isArray(obj)) { + return obj.map(function (i, _, __) { + return customWs(i, md, d + 1) + }).reduce(function (a, b) { return a + b }, '') + } + + var keys = Object.keys(obj) + return keys.map(function (k, _, __) { + return k + ':' + customWs(obj[k], md, d + 1) + }).reduce(function (a, b) { return a + b }, '') +} + +function custom (obj, md, d) { + d = d || 0 + var to = typeof obj + if (to === 'undefined' || to === 'function' || to === null) return '' + if (d > md || !obj || to !== 'object') return '' + obj + + if (Array.isArray(obj)) { + return obj.map(function (i, _, __) { + return custom(i, md, d + 1) + }).reduce(function (a, b) { return a + b }, '') + } + + var keys = Object.keys(obj) + return keys.map(function (k, _, __) { + return k + ':' + custom(obj[k], md, d + 1) + }).reduce(function (a, b) { return a + b }, '') +} + +function sparseFE2 (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + Object.keys(v).forEach(function (k, _, __) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') return + var to = typeof v[k] + if (to === 'function' || to === 'undefined') return + soFar += k + ':' + ch(v[k], depth + 1) + }) + soFar += '}' + } + ch(obj, 0) + return soFar +} + +function sparseFE (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + Object.keys(v).forEach(function (k, _, __) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') return + var to = typeof v[k] + if (to === 'function' || to === 'undefined') return + soFar += k + ch(v[k], depth + 1) + }) + } + ch(obj, 0) + return soFar +} + +function sparse (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + for (var k in v) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') continue + var to = typeof v[k] + if (to === 'function' || to === 'undefined') continue + soFar += k + ch(v[k], depth + 1) + } + } + ch(obj, 0) + return soFar +} + +function noCommas (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + for (var k in v) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') continue + var to = typeof v[k] + if (to === 'function' || to === 'undefined') continue + soFar += k + ':' + ch(v[k], depth + 1) + } + soFar += '}' + } + ch(obj, 0) + return soFar +} + + +function flatten (obj, maxDepth) { + var seen = [] + var soFar = '' + function ch (v, depth) { + if (depth > maxDepth) return + if (typeof v === 'function' || typeof v === 'undefined') return + if (typeof v !== 'object' || !v) { + soFar += v + return + } + if (seen.indexOf(v) !== -1 || depth === maxDepth) return + seen.push(v) + soFar += '{' + for (var k in v) { + // pseudo-private values. skip those. + if (k.charAt(0) === '_') continue + var to = typeof v[k] + if (to === 'function' || to === 'undefined') continue + soFar += k + ':' + ch(v[k], depth + 1) + soFar += ',' + } + soFar += '}' + } + ch(obj, 0) + return soFar +} + +exports.compare = +{ + // 'custom 2': function () { + // return custom(test, 2, 0) + // }, + // 'customWs 2': function () { + // return customWs(test, 2, 0) + // }, + 'JSON.stringify (guarded)': function () { + var seen = [] + return JSON.stringify(test, function (k, v) { + if (typeof v !== 'object' || !v) return v + if (seen.indexOf(v) !== -1) return undefined + seen.push(v) + return v + }) + }, + + 'flatten 10': function () { + return flatten(test, 10) + }, + + // 'flattenFE 10': function () { + // return flattenFE(test, 10) + // }, + + 'noCommas 10': function () { + return noCommas(test, 10) + }, + + 'sparse 10': function () { + return sparse(test, 10) + }, + + 'sparseFE 10': function () { + return sparseFE(test, 10) + }, + + 'sparseFE2 10': function () { + return sparseFE2(test, 10) + }, + + sigmund: function() { + return sigmund(test, 10) + }, + + + // 'util.inspect 1': function () { + // return util.inspect(test, false, 1, false) + // }, + // 'util.inspect undefined': function () { + // util.inspect(test) + // }, + // 'util.inspect 2': function () { + // util.inspect(test, false, 2, false) + // }, + // 'util.inspect 3': function () { + // util.inspect(test, false, 3, false) + // }, + // 'util.inspect 4': function () { + // util.inspect(test, false, 4, false) + // }, + // 'util.inspect Infinity': function () { + // util.inspect(test, false, Infinity, false) + // } +} + +/** results +**/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/package.json new file mode 100644 index 0000000..4255e77 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/package.json @@ -0,0 +1,60 @@ +{ + "name": "sigmund", + "version": "1.0.1", + "description": "Quick and dirty signatures for Objects.", + "main": "sigmund.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "~0.3.0" + }, + "scripts": { + "test": "tap test/*.js", + "bench": "node bench.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/sigmund.git" + }, + "keywords": [ + "object", + "signature", + "key", + "data", + "psychoanalysis" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "ISC", + "gitHead": "527f97aa5bb253d927348698c0cd3bb267d098c6", + "bugs": { + "url": "https://github.com/isaacs/sigmund/issues" + }, + "homepage": "https://github.com/isaacs/sigmund#readme", + "_id": "sigmund@1.0.1", + "_shasum": "3ff21f198cad2175f9f3b781853fd94d0d19b590", + "_from": "sigmund@>=1.0.0 <1.1.0", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "3ff21f198cad2175f9f3b781853fd94d0d19b590", + "tarball": "http://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "_resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/sigmund.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/sigmund.js new file mode 100644 index 0000000..82c7ab8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/sigmund.js @@ -0,0 +1,39 @@ +module.exports = sigmund +function sigmund (subject, maxSessions) { + maxSessions = maxSessions || 10; + var notes = []; + var analysis = ''; + var RE = RegExp; + + function psychoAnalyze (subject, session) { + if (session > maxSessions) return; + + if (typeof subject === 'function' || + typeof subject === 'undefined') { + return; + } + + if (typeof subject !== 'object' || !subject || + (subject instanceof RE)) { + analysis += subject; + return; + } + + if (notes.indexOf(subject) !== -1 || session === maxSessions) return; + + notes.push(subject); + analysis += '{'; + Object.keys(subject).forEach(function (issue, _, __) { + // pseudo-private values. skip those. + if (issue.charAt(0) === '_') return; + var to = typeof subject[issue]; + if (to === 'function' || to === 'undefined') return; + analysis += issue; + psychoAnalyze(subject[issue], session + 1); + }); + } + psychoAnalyze(subject, 0); + return analysis; +} + +// vim: set softtabstop=4 shiftwidth=4: diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/test/basic.js new file mode 100644 index 0000000..50c53a1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/node_modules/sigmund/test/basic.js @@ -0,0 +1,24 @@ +var test = require('tap').test +var sigmund = require('../sigmund.js') + + +// occasionally there are duplicates +// that's an acceptable edge-case. JSON.stringify and util.inspect +// have some collision potential as well, though less, and collision +// detection is expensive. +var hash = '{abc/def/g{0h1i2{jkl' +var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]} +var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']} + +var obj3 = JSON.parse(JSON.stringify(obj1)) +obj3.c = /def/ +obj3.g[2].cycle = obj3 +var cycleHash = '{abc/def/g{0h1i2{jklcycle' + +test('basic', function (t) { + t.equal(sigmund(obj1), hash) + t.equal(sigmund(obj2), hash) + t.equal(sigmund(obj3), cycleHash) + t.end() +}) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/package.json new file mode 100644 index 0000000..f3b6156 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/package.json @@ -0,0 +1,42 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "minimatch", + "description": "a glob matcher in javascript", + "version": "0.2.14", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap test/*.js" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "lru-cache": "2", + "sigmund": "~1.0.0" + }, + "devDependencies": { + "tap": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" + }, + "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\nminimatch(\"bar.foo\", \"*.+(bar|foo)\", { debug: true }) // true, and noisy!\n```\n\n## Features\n\nSupports these glob features:\n\n* Brace Expansion\n* Extended glob matching\n* \"Globstar\" `**` matching\n\nSee:\n\n* `man sh`\n* `man bash`\n* `man 3 fnmatch`\n* `man 5 gitignore`\n\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself. When set, an empty list is returned if there are\nno matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n\n\n## Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch and other\nimplementations, and are intentional.\n\nIf the pattern starts with a `!` character, then it is negated. Set the\n`nonegate` flag to suppress this behavior, and treat leading `!`\ncharacters normally. This is perhaps relevant if you wish to start the\npattern with a negative extglob pattern like `!(a|B)`. Multiple `!`\ncharacters at the start of a pattern will negate the pattern multiple\ntimes.\n\nIf a pattern starts with `#`, then it is treated as a comment, and\nwill not match anything. Use `\\#` to match a literal `#` at the\nstart of a line, or set the `nocomment` flag to suppress this behavior.\n\nThe double-star character `**` is supported by default, unless the\n`noglobstar` flag is set. This is supported in the manner of bsdglob\nand bash 4.1, where `**` only has special significance if it is the only\nthing in a path part. That is, `a/**/b` will match `a/x/y/b`, but\n`a/**b` will not.\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`. This is akin to setting the `nullglob` option in bash, except\nthat it does not resolve escaped pattern characters.\n\nIf brace expansion is not disabled, then it is performed before any\nother interpretation of the glob pattern. Thus, a pattern like\n`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded\n**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are\nchecked for validity. Since those two are valid, matching proceeds.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "homepage": "https://github.com/isaacs/minimatch#readme", + "_id": "minimatch@0.2.14", + "_shasum": "c74e780574f63c6f9a090e90efbe6ef53a6a756a", + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.2.14.tgz", + "_from": "minimatch@>=0.2.0 <0.3.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/basic.js new file mode 100644 index 0000000..ae7ac73 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/basic.js @@ -0,0 +1,399 @@ +// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test +// +// TODO: Some of these tests do very bad things with backslashes, and will +// most likely fail badly on windows. They should probably be skipped. + +var tap = require("tap") + , globalBefore = Object.keys(global) + , mm = require("../") + , files = [ "a", "b", "c", "d", "abc" + , "abd", "abe", "bb", "bcd" + , "ca", "cb", "dd", "de" + , "bdir/", "bdir/cfile"] + , next = files.concat([ "a-b", "aXb" + , ".x", ".y" ]) + + +var patterns = + [ "http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test" + , ["a*", ["a", "abc", "abd", "abe"]] + , ["X*", ["X*"], {nonull: true}] + + // allow null glob expansion + , ["X*", []] + + // isaacs: Slightly different than bash/sh/ksh + // \\* is not un-escaped to literal "*" in a failed match, + // but it does make it get treated as a literal star + , ["\\*", ["\\*"], {nonull: true}] + , ["\\**", ["\\**"], {nonull: true}] + , ["\\*\\*", ["\\*\\*"], {nonull: true}] + + , ["b*/", ["bdir/"]] + , ["c*", ["c", "ca", "cb"]] + , ["**", files] + + , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] + , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] + + , "legendary larry crashes bashes" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] + + , "character classes" + , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] + , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", + "bdir/", "ca", "cb", "dd", "de"]] + , ["a*[^c]", ["abd", "abe"]] + , function () { files.push("a-b", "aXb") } + , ["a[X-]b", ["a-b", "aXb"]] + , function () { files.push(".x", ".y") } + , ["[^a-c]*", ["d", "dd", "de"]] + , function () { files.push("a*b/", "a*b/ooo") } + , ["a\\*b/*", ["a*b/ooo"]] + , ["a\\*?/*", ["a*b/ooo"]] + , ["*\\\\!*", [], {null: true}, ["echo !7"]] + , ["*\\!*", ["echo !7"], null, ["echo !7"]] + , ["*.\\*", ["r.*"], null, ["r.*"]] + , ["a[b]c", ["abc"]] + , ["a[\\b]c", ["abc"]] + , ["a?c", ["abc"]] + , ["a\\*c", [], {null: true}, ["abc"]] + , ["", [""], { null: true }, [""]] + + , "http://www.opensource.apple.com/source/bash/bash-23/" + + "bash/tests/glob-test" + , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } + , ["*/man*/bash.*", ["man/man1/bash.1"]] + , ["man/man1/bash.1", ["man/man1/bash.1"]] + , ["a***c", ["abc"], null, ["abc"]] + , ["a*****?c", ["abc"], null, ["abc"]] + , ["?*****??", ["abc"], null, ["abc"]] + , ["*****??", ["abc"], null, ["abc"]] + , ["?*****?c", ["abc"], null, ["abc"]] + , ["?***?****c", ["abc"], null, ["abc"]] + , ["?***?****?", ["abc"], null, ["abc"]] + , ["?***?****", ["abc"], null, ["abc"]] + , ["*******c", ["abc"], null, ["abc"]] + , ["*******?", ["abc"], null, ["abc"]] + , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["[-abc]", ["-"], null, ["-"]] + , ["[abc-]", ["-"], null, ["-"]] + , ["\\", ["\\"], null, ["\\"]] + , ["[\\\\]", ["\\"], null, ["\\"]] + , ["[[]", ["["], null, ["["]] + , ["[", ["["], null, ["["]] + , ["[*", ["[abc"], null, ["[abc"]] + , "a right bracket shall lose its special meaning and\n" + + "represent itself in a bracket expression if it occurs\n" + + "first in the list. -- POSIX.2 2.8.3.2" + , ["[]]", ["]"], null, ["]"]] + , ["[]-]", ["]"], null, ["]"]] + , ["[a-\z]", ["p"], null, ["p"]] + , ["??**********?****?", [], { null: true }, ["abc"]] + , ["??**********?****c", [], { null: true }, ["abc"]] + , ["?************c****?****", [], { null: true }, ["abc"]] + , ["*c*?**", [], { null: true }, ["abc"]] + , ["a*****c*?**", [], { null: true }, ["abc"]] + , ["a********???*******", [], { null: true }, ["abc"]] + , ["[]", [], { null: true }, ["a"]] + , ["[abc", [], { null: true }, ["["]] + + , "nocase tests" + , ["XYZ", ["xYz"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["ab*", ["ABC"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + + // [ pattern, [matches], MM opts, files, TAP opts] + , "onestar/twostar" + , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] + , ["{/?,*}", ["/a", "bb"], {null: true} + , ["/a", "/b/b", "/a/b/c", "bb"]] + + , "dots should not match unless requested" + , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] + + // .. and . can only match patterns starting with ., + // even when options.dot is set. + , function () { + files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] + } + , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] + , ["a/*/b", ["a/c/b"], {dot:false}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] + + + // this also tests that changing the options needs + // to change the cache key, even if the pattern is + // the same! + , ["**", ["a/b","a/.d",".a/.d"], { dot: true } + , [ ".a/.d", "a/.d", "a/b"]] + + , "paren sets cannot contain slashes" + , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] + + // brace sets trump all else. + // + // invalid glob pattern. fails on bash4 and bsdglob. + // however, in this implementation, it's easier just + // to do the intuitive thing, and let brace-expansion + // actually come before parsing any extglob patterns, + // like the documentation seems to say. + // + // XXX: if anyone complains about this, either fix it + // or tell them to grow up and stop complaining. + // + // bash/bsdglob says this: + // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] + // but we do this instead: + , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] + + // test partial parsing in the presence of comment/negation chars + , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] + , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] + + // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. + , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] + , {} + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] + + + // crazy nested {,,} and *(||) tests. + , function () { + files = [ "a", "b", "c", "d" + , "ab", "ac", "ad" + , "bc", "cb" + , "bc,d", "c,db", "c,d" + , "d)", "(b|c", "*(b|c" + , "b|c", "b|cc", "cb|c" + , "x(a|b|c)", "x(a|c)" + , "(a|b|c)", "(a|c)"] + } + , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] + , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] + // a + // *(b|c) + // *(b|d) + , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] + , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] + + + // test various flag settings. + , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] + , { noext: true } ] + , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} + , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] + , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] + + + // begin channelling Boole and deMorgan... + , "negation tests" + , function () { + files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] + } + + // anything that is NOT a* matches. + , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] + + // anything that IS !a* matches. + , ["!a*", ["!ab", "!abc"], {nonegate: true}] + + // anything that IS a* matches + , ["!!a*", ["a!b"]] + + // anything that is NOT !a* matches + , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] + + // negation nestled within a pattern + , function () { + files = [ "foo.js" + , "foo.bar" + // can't match this one without negative lookbehind. + , "foo.js.js" + , "blar.js" + , "foo." + , "boo.js.boo" ] + } + , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ] + + // https://github.com/isaacs/minimatch/issues/5 + , function () { + files = [ 'a/b/.x/c' + , 'a/b/.x/c/d' + , 'a/b/.x/c/d/e' + , 'a/b/.x' + , 'a/b/.x/' + , 'a/.x/b' + , '.x' + , '.x/' + , '.x/a' + , '.x/a/b' + , 'a/.x/b/.x/c' + , '.x/.x' ] + } + , ["**/.x/**", [ '.x/' + , '.x/a' + , '.x/a/b' + , 'a/.x/b' + , 'a/b/.x/' + , 'a/b/.x/c' + , 'a/b/.x/c/d' + , 'a/b/.x/c/d/e' ] ] + + ] + +var regexps = + [ '/^(?:(?=.)a[^/]*?)$/', + '/^(?:(?=.)X[^/]*?)$/', + '/^(?:(?=.)X[^/]*?)$/', + '/^(?:\\*)$/', + '/^(?:(?=.)\\*[^/]*?)$/', + '/^(?:\\*\\*)$/', + '/^(?:(?=.)b[^/]*?\\/)$/', + '/^(?:(?=.)c[^/]*?)$/', + '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/', + '/^(?:\\.\\.\\/(?!\\.)(?=.)[^/]*?\\/)$/', + '/^(?:s\\/(?=.)\\.\\.[^/]*?\\/)$/', + '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/1\\/)$/', + '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/\u0001\\/)$/', + '/^(?:(?!\\.)(?=.)[a-c]b[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[a-y][^/]*?[^c])$/', + '/^(?:(?=.)a[^/]*?[^c])$/', + '/^(?:(?=.)a[X-]b)$/', + '/^(?:(?!\\.)(?=.)[^a-c][^/]*?)$/', + '/^(?:a\\*b\\/(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?=.)a\\*[^/]\\/(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\\\\\![^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\![^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\.\\*)$/', + '/^(?:(?=.)a[b]c)$/', + '/^(?:(?=.)a[b]c)$/', + '/^(?:(?=.)a[^/]c)$/', + '/^(?:a\\*c)$/', + 'false', + '/^(?:(?!\\.)(?=.)[^/]*?\\/(?=.)man[^/]*?\\/(?=.)bash\\.[^/]*?)$/', + '/^(?:man\\/man1\\/bash\\.1)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/', + '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', + '/^(?:(?=.)a[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k[^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[-abc])$/', + '/^(?:(?!\\.)(?=.)[abc-])$/', + '/^(?:\\\\)$/', + '/^(?:(?!\\.)(?=.)[\\\\])$/', + '/^(?:(?!\\.)(?=.)[\\[])$/', + '/^(?:\\[)$/', + '/^(?:(?=.)\\[(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[\\]])$/', + '/^(?:(?!\\.)(?=.)[\\]-])$/', + '/^(?:(?!\\.)(?=.)[a-z])$/', + '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', + '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/', + '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/', + '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/', + '/^(?:\\[\\])$/', + '/^(?:\\[abc)$/', + '/^(?:(?=.)XYZ)$/i', + '/^(?:(?=.)ab[^/]*?)$/i', + '/^(?:(?!\\.)(?=.)[ia][^/][ck])$/i', + '/^(?:\\/(?!\\.)(?=.)[^/]*?|(?!\\.)(?=.)[^/]*?)$/', + '/^(?:\\/(?!\\.)(?=.)[^/]|(?!\\.)(?=.)[^/]*?)$/', + '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/', + '/^(?:a\\/(?!(?:^|\\/)\\.{1,2}(?:$|\\/))(?=.)[^/]*?\\/b)$/', + '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/', + '/^(?:a\\/(?!\\.)(?=.)[^/]*?\\/b)$/', + '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/', + '/^(?:(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\/b\\))$/', + '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/', + '/^(?:(?=.)\\[(?=.)\\!a[^/]*?)$/', + '/^(?:(?=.)\\[(?=.)#a[^/]*?)$/', + '/^(?:(?=.)\\+\\(a\\|[^/]*?\\|c\\\\\\\\\\|d\\\\\\\\\\|e\\\\\\\\\\\\\\\\\\|f\\\\\\\\\\\\\\\\\\|g)$/', + '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/', + '/^(?:a|(?!\\.)(?=.)[^/]*?\\(b\\|c|d\\))$/', + '/^(?:a|(?!\\.)(?=.)(?:b|c)*|(?!\\.)(?=.)(?:b|d)*)$/', + '/^(?:(?!\\.)(?=.)(?:a|b|c)*|(?!\\.)(?=.)(?:a|c)*)$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\|b\\|c\\)|(?!\\.)(?=.)[^/]*?\\(a\\|c\\))$/', + '/^(?:(?=.)a[^/]b)$/', + '/^(?:(?=.)#[^/]*?)$/', + '/^(?!^(?:(?=.)a[^/]*?)$).*$/', + '/^(?:(?=.)\\!a[^/]*?)$/', + '/^(?:(?=.)a[^/]*?)$/', + '/^(?!^(?:(?=.)\\!a[^/]*?)$).*$/', + '/^(?:(?!\\.)(?=.)[^/]*?\\.(?:(?!js)[^/]*?))$/', + '/^(?:(?:(?!(?:\\/|^)\\.).)*?\\/\\.x\\/(?:(?!(?:\\/|^)\\.).)*?)$/' ] +var re = 0; + +tap.test("basic tests", function (t) { + var start = Date.now() + + // [ pattern, [matches], MM opts, files, TAP opts] + patterns.forEach(function (c) { + if (typeof c === "function") return c() + if (typeof c === "string") return t.comment(c) + + var pattern = c[0] + , expect = c[1].sort(alpha) + , options = c[2] || {} + , f = c[3] || files + , tapOpts = c[4] || {} + + // options.debug = true + var m = new mm.Minimatch(pattern, options) + var r = m.makeRe() + var expectRe = regexps[re++] + tapOpts.re = String(r) || JSON.stringify(r) + tapOpts.files = JSON.stringify(f) + tapOpts.pattern = pattern + tapOpts.set = m.set + tapOpts.negated = m.negate + + var actual = mm.match(f, pattern, options) + actual.sort(alpha) + + t.equivalent( actual, expect + , JSON.stringify(pattern) + " " + JSON.stringify(expect) + , tapOpts ) + + t.equal(tapOpts.re, expectRe, tapOpts) + }) + + t.comment("time=" + (Date.now() - start) + "ms") + t.end() +}) + +tap.test("global leak test", function (t) { + var globalAfter = Object.keys(global) + t.equivalent(globalAfter, globalBefore, "no new globals, please") + t.end() +}) + +function alpha (a, b) { + return a > b ? 1 : -1 +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/brace-expand.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/brace-expand.js new file mode 100644 index 0000000..7ee278a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/brace-expand.js @@ -0,0 +1,33 @@ +var tap = require("tap") + , minimatch = require("../") + +tap.test("brace expansion", function (t) { + // [ pattern, [expanded] ] + ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}" + , [ "abxy" + , "abxz" + , "acdxy" + , "acdxz" + , "acexy" + , "acexz" + , "afhxy" + , "afhxz" + , "aghxy" + , "aghxz" ] ] + , [ "a{1..5}b" + , [ "a1b" + , "a2b" + , "a3b" + , "a4b" + , "a5b" ] ] + , [ "a{b}c", ["a{b}c"] ] + ].forEach(function (tc) { + var p = tc[0] + , expect = tc[1] + t.equivalent(minimatch.braceExpand(p), expect, p) + }) + console.error("ending") + t.end() +}) + + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/caching.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/caching.js new file mode 100644 index 0000000..0fec4b0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/caching.js @@ -0,0 +1,14 @@ +var Minimatch = require("../minimatch.js").Minimatch +var tap = require("tap") +tap.test("cache test", function (t) { + var mm1 = new Minimatch("a?b") + var mm2 = new Minimatch("a?b") + t.equal(mm1, mm2, "should get the same object") + // the lru should drop it after 100 entries + for (var i = 0; i < 100; i ++) { + new Minimatch("a"+i) + } + mm2 = new Minimatch("a?b") + t.notEqual(mm1, mm2, "cache should have dropped") + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/defaults.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/defaults.js new file mode 100644 index 0000000..25f1f60 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/defaults.js @@ -0,0 +1,274 @@ +// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test +// +// TODO: Some of these tests do very bad things with backslashes, and will +// most likely fail badly on windows. They should probably be skipped. + +var tap = require("tap") + , globalBefore = Object.keys(global) + , mm = require("../") + , files = [ "a", "b", "c", "d", "abc" + , "abd", "abe", "bb", "bcd" + , "ca", "cb", "dd", "de" + , "bdir/", "bdir/cfile"] + , next = files.concat([ "a-b", "aXb" + , ".x", ".y" ]) + +tap.test("basic tests", function (t) { + var start = Date.now() + + // [ pattern, [matches], MM opts, files, TAP opts] + ; [ "http://www.bashcookbook.com/bashinfo" + + "/source/bash-1.14.7/tests/glob-test" + , ["a*", ["a", "abc", "abd", "abe"]] + , ["X*", ["X*"], {nonull: true}] + + // allow null glob expansion + , ["X*", []] + + // isaacs: Slightly different than bash/sh/ksh + // \\* is not un-escaped to literal "*" in a failed match, + // but it does make it get treated as a literal star + , ["\\*", ["\\*"], {nonull: true}] + , ["\\**", ["\\**"], {nonull: true}] + , ["\\*\\*", ["\\*\\*"], {nonull: true}] + + , ["b*/", ["bdir/"]] + , ["c*", ["c", "ca", "cb"]] + , ["**", files] + + , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] + , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] + + , "legendary larry crashes bashes" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" + , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] + + , "character classes" + , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] + , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", + "bdir/", "ca", "cb", "dd", "de"]] + , ["a*[^c]", ["abd", "abe"]] + , function () { files.push("a-b", "aXb") } + , ["a[X-]b", ["a-b", "aXb"]] + , function () { files.push(".x", ".y") } + , ["[^a-c]*", ["d", "dd", "de"]] + , function () { files.push("a*b/", "a*b/ooo") } + , ["a\\*b/*", ["a*b/ooo"]] + , ["a\\*?/*", ["a*b/ooo"]] + , ["*\\\\!*", [], {null: true}, ["echo !7"]] + , ["*\\!*", ["echo !7"], null, ["echo !7"]] + , ["*.\\*", ["r.*"], null, ["r.*"]] + , ["a[b]c", ["abc"]] + , ["a[\\b]c", ["abc"]] + , ["a?c", ["abc"]] + , ["a\\*c", [], {null: true}, ["abc"]] + , ["", [""], { null: true }, [""]] + + , "http://www.opensource.apple.com/source/bash/bash-23/" + + "bash/tests/glob-test" + , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } + , ["*/man*/bash.*", ["man/man1/bash.1"]] + , ["man/man1/bash.1", ["man/man1/bash.1"]] + , ["a***c", ["abc"], null, ["abc"]] + , ["a*****?c", ["abc"], null, ["abc"]] + , ["?*****??", ["abc"], null, ["abc"]] + , ["*****??", ["abc"], null, ["abc"]] + , ["?*****?c", ["abc"], null, ["abc"]] + , ["?***?****c", ["abc"], null, ["abc"]] + , ["?***?****?", ["abc"], null, ["abc"]] + , ["?***?****", ["abc"], null, ["abc"]] + , ["*******c", ["abc"], null, ["abc"]] + , ["*******?", ["abc"], null, ["abc"]] + , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] + , ["[-abc]", ["-"], null, ["-"]] + , ["[abc-]", ["-"], null, ["-"]] + , ["\\", ["\\"], null, ["\\"]] + , ["[\\\\]", ["\\"], null, ["\\"]] + , ["[[]", ["["], null, ["["]] + , ["[", ["["], null, ["["]] + , ["[*", ["[abc"], null, ["[abc"]] + , "a right bracket shall lose its special meaning and\n" + + "represent itself in a bracket expression if it occurs\n" + + "first in the list. -- POSIX.2 2.8.3.2" + , ["[]]", ["]"], null, ["]"]] + , ["[]-]", ["]"], null, ["]"]] + , ["[a-\z]", ["p"], null, ["p"]] + , ["??**********?****?", [], { null: true }, ["abc"]] + , ["??**********?****c", [], { null: true }, ["abc"]] + , ["?************c****?****", [], { null: true }, ["abc"]] + , ["*c*?**", [], { null: true }, ["abc"]] + , ["a*****c*?**", [], { null: true }, ["abc"]] + , ["a********???*******", [], { null: true }, ["abc"]] + , ["[]", [], { null: true }, ["a"]] + , ["[abc", [], { null: true }, ["["]] + + , "nocase tests" + , ["XYZ", ["xYz"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["ab*", ["ABC"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } + , ["xYz", "ABC", "IjK"]] + + // [ pattern, [matches], MM opts, files, TAP opts] + , "onestar/twostar" + , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] + , ["{/?,*}", ["/a", "bb"], {null: true} + , ["/a", "/b/b", "/a/b/c", "bb"]] + + , "dots should not match unless requested" + , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] + + // .. and . can only match patterns starting with ., + // even when options.dot is set. + , function () { + files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] + } + , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] + , ["a/*/b", ["a/c/b"], {dot:false}] + , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] + + + // this also tests that changing the options needs + // to change the cache key, even if the pattern is + // the same! + , ["**", ["a/b","a/.d",".a/.d"], { dot: true } + , [ ".a/.d", "a/.d", "a/b"]] + + , "paren sets cannot contain slashes" + , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] + + // brace sets trump all else. + // + // invalid glob pattern. fails on bash4 and bsdglob. + // however, in this implementation, it's easier just + // to do the intuitive thing, and let brace-expansion + // actually come before parsing any extglob patterns, + // like the documentation seems to say. + // + // XXX: if anyone complains about this, either fix it + // or tell them to grow up and stop complaining. + // + // bash/bsdglob says this: + // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] + // but we do this instead: + , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] + + // test partial parsing in the presence of comment/negation chars + , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] + , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] + + // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. + , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] + , {} + , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] + + + // crazy nested {,,} and *(||) tests. + , function () { + files = [ "a", "b", "c", "d" + , "ab", "ac", "ad" + , "bc", "cb" + , "bc,d", "c,db", "c,d" + , "d)", "(b|c", "*(b|c" + , "b|c", "b|cc", "cb|c" + , "x(a|b|c)", "x(a|c)" + , "(a|b|c)", "(a|c)"] + } + , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] + , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] + // a + // *(b|c) + // *(b|d) + , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] + , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] + + + // test various flag settings. + , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] + , { noext: true } ] + , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} + , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] + , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] + + + // begin channelling Boole and deMorgan... + , "negation tests" + , function () { + files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] + } + + // anything that is NOT a* matches. + , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] + + // anything that IS !a* matches. + , ["!a*", ["!ab", "!abc"], {nonegate: true}] + + // anything that IS a* matches + , ["!!a*", ["a!b"]] + + // anything that is NOT !a* matches + , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] + + // negation nestled within a pattern + , function () { + files = [ "foo.js" + , "foo.bar" + // can't match this one without negative lookbehind. + , "foo.js.js" + , "blar.js" + , "foo." + , "boo.js.boo" ] + } + , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ] + + ].forEach(function (c) { + if (typeof c === "function") return c() + if (typeof c === "string") return t.comment(c) + + var pattern = c[0] + , expect = c[1].sort(alpha) + , options = c[2] || {} + , f = c[3] || files + , tapOpts = c[4] || {} + + // options.debug = true + var Class = mm.defaults(options).Minimatch + var m = new Class(pattern, {}) + var r = m.makeRe() + tapOpts.re = String(r) || JSON.stringify(r) + tapOpts.files = JSON.stringify(f) + tapOpts.pattern = pattern + tapOpts.set = m.set + tapOpts.negated = m.negate + + var actual = mm.match(f, pattern, options) + actual.sort(alpha) + + t.equivalent( actual, expect + , JSON.stringify(pattern) + " " + JSON.stringify(expect) + , tapOpts ) + }) + + t.comment("time=" + (Date.now() - start) + "ms") + t.end() +}) + +tap.test("global leak test", function (t) { + var globalAfter = Object.keys(global) + t.equivalent(globalAfter, globalBefore, "no new globals, please") + t.end() +}) + +function alpha (a, b) { + return a > b ? 1 : -1 +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/extglob-ending-with-state-char.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/extglob-ending-with-state-char.js new file mode 100644 index 0000000..6676e26 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/node_modules/minimatch/test/extglob-ending-with-state-char.js @@ -0,0 +1,8 @@ +var test = require('tap').test +var minimatch = require('../') + +test('extglob ending with statechar', function(t) { + t.notOk(minimatch('ax', 'a?(b*)')) + t.ok(minimatch('ax', '?(a*|b)')) + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/package.json new file mode 100644 index 0000000..d71faf6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/package.json @@ -0,0 +1,54 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "fstream-ignore", + "description": "A thing for ignoring files based on globs", + "version": "0.0.7", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/fstream-ignore.git" + }, + "main": "ignore.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "minimatch": "~0.2.0", + "fstream": "~0.1.17", + "inherits": "2" + }, + "devDependencies": { + "tap": "", + "rimraf": "", + "mkdirp": "" + }, + "license": "BSD", + "bugs": { + "url": "https://github.com/isaacs/fstream-ignore/issues" + }, + "_id": "fstream-ignore@0.0.7", + "dist": { + "shasum": "eea3033f0c3728139de7b57ab1b0d6d89c353c63", + "tarball": "http://registry.npmjs.org/fstream-ignore/-/fstream-ignore-0.0.7.tgz" + }, + "_from": "fstream-ignore@0.0.7", + "_npmVersion": "1.2.23", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "eea3033f0c3728139de7b57ab1b0d6d89c353c63", + "_resolved": "https://registry.npmjs.org/fstream-ignore/-/fstream-ignore-0.0.7.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/fstream-ignore#readme" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.ignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.ignore new file mode 100644 index 0000000..773679d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.ignore @@ -0,0 +1,2 @@ +.gitignore +.*.swp diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.npmignore new file mode 100644 index 0000000..1b26d0d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/.npmignore @@ -0,0 +1 @@ +*/a diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/00-setup.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/00-setup.js new file mode 100644 index 0000000..7d7e4a1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/00-setup.js @@ -0,0 +1,71 @@ +// The test fixtures work like this: +// These dirs are all created: {a,b,c}/{a,b,c}/{a,b,c}/ +// in each one, these files are created: +// {.,}{a,b,c}{a,b,c}{a,b,c} +// +// So, there'll be a/b/c/abc, a/b/c/aba, etc., and dot-versions of each. +// +// Each test then writes their own ignore file rules for their purposes, +// and is responsible for removing them afterwards. + +var mkdirp = require("mkdirp") +var path = require("path") +var i = 0 +var tap = require("tap") +var fs = require("fs") +var rimraf = require("rimraf") +var fixtures = path.resolve(__dirname, "fixtures") + +var chars = ['a', 'b', 'c'] +var dirs = [] + +for (var i = 0; i < 3; i ++) { + for (var j = 0; j < 3; j ++) { + for (var k = 0; k < 3; k ++) { + dirs.push(chars[i] + '/' + chars[j] + '/' + chars[k]) + } + } +} + +var files = [] + +for (var i = 0; i < 3; i ++) { + for (var j = 0; j < 3; j ++) { + for (var k = 0; k < 3; k ++) { + files.push(chars[i] + chars[j] + chars[k]) + files.push('.' + chars[i] + chars[j] + chars[k]) + } + } +} + +tap.test("remove fixtures", function (t) { + rimraf(path.resolve(__dirname, "fixtures"), function (er) { + t.ifError(er, "remove fixtures") + t.end() + }) +}) + +tap.test("create fixtures", function (t) { + dirs.forEach(function (dir) { + dir = path.resolve(fixtures, dir) + t.test("mkdir "+dir, function (t) { + mkdirp(dir, function (er) { + t.ifError(er, "mkdir "+dir) + if (er) return t.end() + + files.forEach(function (file) { + file = path.resolve(dir, file) + t.test("writeFile "+file, function (t) { + fs.writeFile(file, path.basename(file), function (er) { + t.ifError(er, "writing "+file) + t.end() + }) + }) + }) + t.end() + }) + }) + }) + t.end() +}) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/basic.js new file mode 100644 index 0000000..3718076 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/basic.js @@ -0,0 +1,28 @@ +var IgnoreFile = require("../") + +// set the ignores just for this test +var c = require("./common.js") +c.ignores({ "a/.basic-ignore": ["b/", "aca"] }) + +// the files that we expect to not see +var notAllowed = + [ /^\/a\/b\/.*/ + , /^\/a\/.*\/aca$/ ] + + +require("tap").test("basic ignore rules", function (t) { + t.pass("start") + + IgnoreFile({ path: __dirname + "/fixtures" + , ignoreFiles: [".basic-ignore"] }) + .on("ignoreFile", function (e) { + console.error("ignore file!", e) + }) + .on("child", function (e) { + var p = e.path.substr(e.root.path.length) + notAllowed.forEach(function (na) { + t.dissimilar(p, na) + }) + }) + .on("close", t.end.bind(t)) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/common.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/common.js new file mode 100644 index 0000000..0e6cd98 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/common.js @@ -0,0 +1,40 @@ +if (require.main === module) { + console.log("0..1") + console.log("ok 1 trivial pass") + return +} + +var fs = require("fs") +var path = require("path") +var rimraf = require("rimraf") + +exports.ignores = ignores +exports.writeIgnoreFile = writeIgnoreFile +exports.writeIgnores = writeIgnores +exports.clearIgnores = clearIgnores + +function writeIgnoreFile (file, rules) { + file = path.resolve(__dirname, "fixtures", file) + if (Array.isArray(rules)) { + rules = rules.join("\n") + } + fs.writeFileSync(file, rules) + console.error(file, rules) +} + +function writeIgnores (set) { + Object.keys(set).forEach(function (f) { + writeIgnoreFile(f, set[f]) + }) +} + +function clearIgnores (set) { + Object.keys(set).forEach(function (file) { + fs.unlinkSync(path.resolve(__dirname, "fixtures", file)) + }) +} + +function ignores (set) { + writeIgnores(set) + process.on("exit", clearIgnores.bind(null, set)) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/ignore-most.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/ignore-most.js new file mode 100644 index 0000000..43eec4b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/ignore-most.js @@ -0,0 +1,41 @@ +// ignore most things +var IgnoreFile = require("../") + +// set the ignores just for this test +var c = require("./common.js") +c.ignores({ ".ignore": ["*", "!a/b/c/.abc", "!/c/b/a/cba"] }) + +// the only files we expect to see +var expected = + [ "/a/b/c/.abc" + , "/a" + , "/a/b" + , "/a/b/c" + , "/c/b/a/cba" + , "/c" + , "/c/b" + , "/c/b/a" ] + +require("tap").test("basic ignore rules", function (t) { + t.pass("start") + + IgnoreFile({ path: __dirname + "/fixtures" + , ignoreFiles: [".ignore"] }) + .on("ignoreFile", function (e) { + console.error("ignore file!", e) + }) + .on("child", function (e) { + var p = e.path.substr(e.root.path.length) + var i = expected.indexOf(p) + if (i === -1) { + t.fail("unexpected file found", {file: p}) + } else { + t.pass(p) + expected.splice(i, 1) + } + }) + .on("close", function () { + t.notOk(expected.length, "all expected files should be seen") + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/nested-ignores.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/nested-ignores.js new file mode 100644 index 0000000..a9ede59 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/nested-ignores.js @@ -0,0 +1,51 @@ +// ignore most things +var IgnoreFile = require("../") + +// set the ignores just for this test +var c = require("./common.js") +c.ignores( + { ".ignore": ["*", "a", "c", "!a/b/c/.abc", "!/c/b/a/cba"] + , "a/.ignore": [ "!*", ".ignore" ] // unignore everything + , "a/a/.ignore": [ "*" ] // re-ignore everything + , "a/b/.ignore": [ "*", "!/c/.abc" ] // original unignore + , "a/c/.ignore": [ "*" ] // ignore everything again + , "c/b/a/.ignore": [ "!cba", "!.cba", "!/a{bc,cb}" ] + }) + +// the only files we expect to see +var expected = + [ "/a" + , "/a/a" + , "/a/b" + , "/a/b/c" + , "/a/b/c/.abc" + , "/a/c" + , "/c" + , "/c/b" + , "/c/b/a" + , "/c/b/a/cba" + , "/c/b/a/.cba" + , "/c/b/a/abc" + , "/c/b/a/acb" ] + +require("tap").test("basic ignore rules", function (t) { + t.pass("start") + + IgnoreFile({ path: __dirname + "/fixtures" + , ignoreFiles: [".ignore"] }) + .on("child", function (e) { + var p = e.path.substr(e.root.path.length) + var i = expected.indexOf(p) + if (i === -1) { + console.log("not ok "+p) + t.fail("unexpected file found", {found: p}) + } else { + t.pass(p) + expected.splice(i, 1) + } + }) + .on("close", function () { + t.deepEqual(expected, [], "all expected files should be seen") + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/unignore-child.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/unignore-child.js new file mode 100644 index 0000000..5812354 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/unignore-child.js @@ -0,0 +1,38 @@ +// ignore most things +var IgnoreFile = require("../") + +// set the ignores just for this test +var c = require("./common.js") +c.ignores({ ".ignore": ["*", "a", "c", "!a/b/c/.abc", "!/c/b/a/cba"] }) + +// the only files we expect to see +var expected = + [ "/a/b/c/.abc" + , "/a" + , "/a/b" + , "/a/b/c" + , "/c/b/a/cba" + , "/c" + , "/c/b" + , "/c/b/a" ] + +require("tap").test("basic ignore rules", function (t) { + t.pass("start") + + IgnoreFile({ path: __dirname + "/fixtures" + , ignoreFiles: [".ignore"] }) + .on("child", function (e) { + var p = e.path.substr(e.root.path.length) + var i = expected.indexOf(p) + if (i === -1) { + t.fail("unexpected file found", {f: p}) + } else { + t.pass(p) + expected.splice(i, 1) + } + }) + .on("close", function () { + t.notOk(expected.length, "all expected files should be seen") + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/zz-cleanup.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/zz-cleanup.js new file mode 100644 index 0000000..82f064a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream-ignore/test/zz-cleanup.js @@ -0,0 +1,10 @@ +var tap = require("tap") +, rimraf = require("rimraf") +, path = require("path") + +tap.test("remove fixtures", function (t) { + rimraf(path.resolve(__dirname, "fixtures"), function (er) { + t.ifError(er, "remove fixtures") + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.npmignore new file mode 100644 index 0000000..494272a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.npmignore @@ -0,0 +1,5 @@ +.*.swp +node_modules/ +examples/deep-copy/ +examples/path/ +examples/filter-copy/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.travis.yml new file mode 100644 index 0000000..2d26206 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.6 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/README.md new file mode 100644 index 0000000..9d8cb77 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/README.md @@ -0,0 +1,76 @@ +Like FS streams, but with stat on them, and supporting directories and +symbolic links, as well as normal files. Also, you can use this to set +the stats on a file, even if you don't change its contents, or to create +a symlink, etc. + +So, for example, you can "write" a directory, and it'll call `mkdir`. You +can specify a uid and gid, and it'll call `chown`. You can specify a +`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink +and provide a `linkpath` and it'll call `symlink`. + +Note that it won't automatically resolve symbolic links. So, if you +call `fstream.Reader('/some/symlink')` then you'll get an object +that stats and then ends immediately (since it has no data). To follow +symbolic links, do this: `fstream.Reader({path:'/some/symlink', follow: +true })`. + +There are various checks to make sure that the bytes emitted are the +same as the intended size, if the size is set. + +## Examples + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + }) + .write("hello\n") + .end() +``` + +This will create the directories if they're missing, and then write +`hello\n` into the file, chmod it to 0755, and assert that 6 bytes have +been written when it's done. + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + , flags: "a" + }) + .write("hello\n") + .end() +``` + +You can pass flags in, if you want to append to a file. + +```javascript +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , SymbolicLink: true + , mode: "0755" // octal strings supported + }) + .end() +``` + +If isSymbolicLink is a function, it'll be called, and if it returns +true, then it'll treat it as a symlink. If it's not a function, then +any truish value will make a symlink, or you can set `type: +'SymbolicLink'`, which does the same thing. + +Note that the linkpath is relative to the symbolic link location, not +the parent dir or cwd. + +```javascript +fstream + .Reader("path/to/dir") + .pipe(fstream.Writer("path/to/other/dir")) +``` + +This will do like `cp -Rp path/to/dir path/to/other/dir`. If the other +dir exists and isn't a directory, then it'll emit an error. It'll also +set the uid, gid, mode, etc. to be identical. In this way, it's more +like `rsync -a` than simply a copy. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/filter-pipe.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/filter-pipe.js new file mode 100644 index 0000000..c6b55b3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/filter-pipe.js @@ -0,0 +1,131 @@ +var fstream = require("../fstream.js") +var path = require("path") + +var r = fstream.Reader({ path: path.dirname(__dirname) + , filter: function () { + return !this.basename.match(/^\./) && + !this.basename.match(/^node_modules$/) + !this.basename.match(/^deep-copy$/) + !this.basename.match(/^filter-copy$/) + } + }) + +// this writer will only write directories +var w = fstream.Writer({ path: path.resolve(__dirname, "filter-copy") + , type: "Directory" + , filter: function () { + return this.type === "Directory" + } + }) + +var indent = "" +var escape = {} + +r.on("entry", appears) +r.on("ready", function () { + console.error("ready to begin!", r.path) +}) + +function appears (entry) { + console.error(indent + "a %s appears!", entry.type, entry.basename, typeof entry.basename) + if (foggy) { + console.error("FOGGY!") + var p = entry + do { + console.error(p.depth, p.path, p._paused) + } while (p = p.parent) + + throw new Error("\033[mshould not have entries while foggy") + } + indent += "\t" + entry.on("data", missile(entry)) + entry.on("end", runaway(entry)) + entry.on("entry", appears) +} + +var foggy +function missile (entry) { + if (entry.type === "Directory") { + var ended = false + entry.once("end", function () { ended = true }) + return function (c) { + // throw in some pathological pause()/resume() behavior + // just for extra fun. + process.nextTick(function () { + if (!foggy && !ended) { // && Math.random() < 0.3) { + console.error(indent +"%s casts a spell", entry.basename) + console.error("\na slowing fog comes over the battlefield...\n\033[32m") + entry.pause() + entry.once("resume", liftFog) + foggy = setTimeout(liftFog, 1000) + + function liftFog (who) { + if (!foggy) return + if (who) { + console.error("%s breaks the spell!", who && who.path) + } else { + console.error("the spell expires!") + } + console.error("\033[mthe fog lifts!\n") + clearTimeout(foggy) + foggy = null + if (entry._paused) entry.resume() + } + + } + }) + } + } + + return function (c) { + var e = Math.random() < 0.5 + console.error(indent + "%s %s for %d damage!", + entry.basename, + e ? "is struck" : "fires a chunk", + c.length) + } +} + +function runaway (entry) { return function () { + var e = Math.random() < 0.5 + console.error(indent + "%s %s", + entry.basename, + e ? "turns to flee" : "is vanquished!") + indent = indent.slice(0, -1) +}} + + +w.on("entry", attacks) +//w.on("ready", function () { attacks(w) }) +function attacks (entry) { + console.error(indent + "%s %s!", entry.basename, + entry.type === "Directory" ? "calls for backup" : "attacks") + entry.on("entry", attacks) +} + +ended = false +var i = 1 +r.on("end", function () { + if (foggy) clearTimeout(foggy) + console.error("\033[mIT'S OVER!!") + console.error("A WINNAR IS YOU!") + + console.log("ok " + (i ++) + " A WINNAR IS YOU") + ended = true + // now go through and verify that everything in there is a dir. + var p = path.resolve(__dirname, "filter-copy") + var checker = fstream.Reader({ path: p }) + checker.checker = true + checker.on("child", function (e) { + var ok = e.type === "Directory" + console.log((ok ? "" : "not ") + "ok " + (i ++) + + " should be a dir: " + + e.path.substr(checker.path.length + 1)) + }) +}) + +process.on("exit", function () { + console.log((ended ? "" : "not ") + "ok " + (i ++) + " ended") +}) + +r.pipe(w) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/pipe.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/pipe.js new file mode 100644 index 0000000..648ec84 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/pipe.js @@ -0,0 +1,115 @@ +var fstream = require("../fstream.js") +var path = require("path") + +var r = fstream.Reader({ path: path.dirname(__dirname) + , filter: function () { + return !this.basename.match(/^\./) && + !this.basename.match(/^node_modules$/) + !this.basename.match(/^deep-copy$/) + } + }) + +var w = fstream.Writer({ path: path.resolve(__dirname, "deep-copy") + , type: "Directory" + }) + +var indent = "" +var escape = {} + +r.on("entry", appears) +r.on("ready", function () { + console.error("ready to begin!", r.path) +}) + +function appears (entry) { + console.error(indent + "a %s appears!", entry.type, entry.basename, typeof entry.basename, entry) + if (foggy) { + console.error("FOGGY!") + var p = entry + do { + console.error(p.depth, p.path, p._paused) + } while (p = p.parent) + + throw new Error("\033[mshould not have entries while foggy") + } + indent += "\t" + entry.on("data", missile(entry)) + entry.on("end", runaway(entry)) + entry.on("entry", appears) +} + +var foggy +function missile (entry) { + if (entry.type === "Directory") { + var ended = false + entry.once("end", function () { ended = true }) + return function (c) { + // throw in some pathological pause()/resume() behavior + // just for extra fun. + process.nextTick(function () { + if (!foggy && !ended) { // && Math.random() < 0.3) { + console.error(indent +"%s casts a spell", entry.basename) + console.error("\na slowing fog comes over the battlefield...\n\033[32m") + entry.pause() + entry.once("resume", liftFog) + foggy = setTimeout(liftFog, 10) + + function liftFog (who) { + if (!foggy) return + if (who) { + console.error("%s breaks the spell!", who && who.path) + } else { + console.error("the spell expires!") + } + console.error("\033[mthe fog lifts!\n") + clearTimeout(foggy) + foggy = null + if (entry._paused) entry.resume() + } + + } + }) + } + } + + return function (c) { + var e = Math.random() < 0.5 + console.error(indent + "%s %s for %d damage!", + entry.basename, + e ? "is struck" : "fires a chunk", + c.length) + } +} + +function runaway (entry) { return function () { + var e = Math.random() < 0.5 + console.error(indent + "%s %s", + entry.basename, + e ? "turns to flee" : "is vanquished!") + indent = indent.slice(0, -1) +}} + + +w.on("entry", attacks) +//w.on("ready", function () { attacks(w) }) +function attacks (entry) { + console.error(indent + "%s %s!", entry.basename, + entry.type === "Directory" ? "calls for backup" : "attacks") + entry.on("entry", attacks) +} + +ended = false +r.on("end", function () { + if (foggy) clearTimeout(foggy) + console.error("\033[mIT'S OVER!!") + console.error("A WINNAR IS YOU!") + + console.log("ok 1 A WINNAR IS YOU") + ended = true +}) + +process.on("exit", function () { + console.log((ended ? "" : "not ") + "ok 2 ended") +}) + +r.pipe(w) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/reader.js new file mode 100644 index 0000000..9aa1a95 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/reader.js @@ -0,0 +1,54 @@ +var fstream = require("../fstream.js") +var tap = require("tap") +var fs = require("fs") +var path = require("path") +var children = -1 +var dir = path.dirname(__dirname) + +var gotReady = false +var ended = false + +tap.test("reader test", function (t) { + + var r = fstream.Reader({ path: dir + , filter: function () { + // return this.parent === r + return this.parent === r || this === r + } + }) + + r.on("ready", function () { + gotReady = true + children = fs.readdirSync(dir).length + console.error("Setting expected children to "+children) + t.equal(r.type, "Directory", "should be a directory") + }) + + r.on("entry", function (entry) { + children -- + if (!gotReady) { + t.fail("children before ready!") + } + t.equal(entry.dirname, r.path, "basename is parent dir") + }) + + r.on("error", function (er) { + t.fail(er) + t.end() + process.exit(1) + }) + + r.on("end", function () { + t.equal(children, 0, "should have seen all children") + ended = true + }) + + var closed = false + r.on("close", function () { + t.ok(ended, "saw end before close") + t.notOk(closed, "close should only happen once") + closed = true + t.end() + }) + +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/symlink-write.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/symlink-write.js new file mode 100644 index 0000000..d7816d2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/examples/symlink-write.js @@ -0,0 +1,24 @@ +var fstream = require("../fstream.js") + , closed = false + +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , isSymbolicLink: true + , mode: "0755" // octal strings supported + }) + .on("close", function () { + closed = true + var fs = require("fs") + var s = fs.lstatSync("path/to/symlink") + var isSym = s.isSymbolicLink() + console.log((isSym?"":"not ") +"ok 1 should be symlink") + var t = fs.readlinkSync("path/to/symlink") + var isTarget = t === "./file" + console.log((isTarget?"":"not ") +"ok 2 should link to ./file") + }) + .end() + +process.on("exit", function () { + console.log((closed?"":"not ")+"ok 3 should be closed") +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/fstream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/fstream.js new file mode 100644 index 0000000..c66d26f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/fstream.js @@ -0,0 +1,31 @@ +exports.Abstract = require("./lib/abstract.js") +exports.Reader = require("./lib/reader.js") +exports.Writer = require("./lib/writer.js") + +exports.File = + { Reader: require("./lib/file-reader.js") + , Writer: require("./lib/file-writer.js") } + +exports.Dir = + { Reader : require("./lib/dir-reader.js") + , Writer : require("./lib/dir-writer.js") } + +exports.Link = + { Reader : require("./lib/link-reader.js") + , Writer : require("./lib/link-writer.js") } + +exports.Proxy = + { Reader : require("./lib/proxy-reader.js") + , Writer : require("./lib/proxy-writer.js") } + +exports.Reader.Dir = exports.DirReader = exports.Dir.Reader +exports.Reader.File = exports.FileReader = exports.File.Reader +exports.Reader.Link = exports.LinkReader = exports.Link.Reader +exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader + +exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer +exports.Writer.File = exports.FileWriter = exports.File.Writer +exports.Writer.Link = exports.LinkWriter = exports.Link.Writer +exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer + +exports.collect = require("./lib/collect.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/abstract.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/abstract.js new file mode 100644 index 0000000..11ef0e2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/abstract.js @@ -0,0 +1,85 @@ +// the parent class for all fstreams. + +module.exports = Abstract + +var Stream = require("stream").Stream + , inherits = require("inherits") + +function Abstract () { + Stream.call(this) +} + +inherits(Abstract, Stream) + +Abstract.prototype.on = function (ev, fn) { + if (ev === "ready" && this.ready) { + process.nextTick(fn.bind(this)) + } else { + Stream.prototype.on.call(this, ev, fn) + } + return this +} + +Abstract.prototype.abort = function () { + this._aborted = true + this.emit("abort") +} + +Abstract.prototype.destroy = function () {} + +Abstract.prototype.warn = function (msg, code) { + var me = this + , er = decorate(msg, code, me) + if (!me.listeners("warn")) { + console.error("%s %s\n" + + "path = %s\n" + + "syscall = %s\n" + + "fstream_type = %s\n" + + "fstream_path = %s\n" + + "fstream_unc_path = %s\n" + + "fstream_class = %s\n" + + "fstream_stack =\n%s\n", + code || "UNKNOWN", + er.stack, + er.path, + er.syscall, + er.fstream_type, + er.fstream_path, + er.fstream_unc_path, + er.fstream_class, + er.fstream_stack.join("\n")) + } else { + me.emit("warn", er) + } +} + +Abstract.prototype.info = function (msg, code) { + this.emit("info", msg, code) +} + +Abstract.prototype.error = function (msg, code, th) { + var er = decorate(msg, code, this) + if (th) throw er + else this.emit("error", er) +} + +function decorate (er, code, me) { + if (!(er instanceof Error)) er = new Error(er) + er.code = er.code || code + er.path = er.path || me.path + er.fstream_type = er.fstream_type || me.type + er.fstream_path = er.fstream_path || me.path + if (me._path !== me.path) { + er.fstream_unc_path = er.fstream_unc_path || me._path + } + if (me.linkpath) { + er.fstream_linkpath = er.fstream_linkpath || me.linkpath + } + er.fstream_class = er.fstream_class || me.constructor.name + er.fstream_stack = er.fstream_stack || + new Error().stack.split(/\n/).slice(3).map(function (s) { + return s.replace(/^ at /, "") + }) + + return er +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/collect.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/collect.js new file mode 100644 index 0000000..a36f780 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/collect.js @@ -0,0 +1,67 @@ +module.exports = collect + +function collect (stream) { + if (stream._collected) return + + stream._collected = true + stream.pause() + + stream.on("data", save) + stream.on("end", save) + var buf = [] + function save (b) { + if (typeof b === "string") b = new Buffer(b) + if (Buffer.isBuffer(b) && !b.length) return + buf.push(b) + } + + stream.on("entry", saveEntry) + var entryBuffer = [] + function saveEntry (e) { + collect(e) + entryBuffer.push(e) + } + + stream.on("proxy", proxyPause) + function proxyPause (p) { + p.pause() + } + + + // replace the pipe method with a new version that will + // unlock the buffered stuff. if you just call .pipe() + // without a destination, then it'll re-play the events. + stream.pipe = (function (orig) { return function (dest) { + // console.error(" === open the pipes", dest && dest.path) + + // let the entries flow through one at a time. + // Once they're all done, then we can resume completely. + var e = 0 + ;(function unblockEntry () { + var entry = entryBuffer[e++] + // console.error(" ==== unblock entry", entry && entry.path) + if (!entry) return resume() + entry.on("end", unblockEntry) + if (dest) dest.add(entry) + else stream.emit("entry", entry) + })() + + function resume () { + stream.removeListener("entry", saveEntry) + stream.removeListener("data", save) + stream.removeListener("end", save) + + stream.pipe = orig + if (dest) stream.pipe(dest) + + buf.forEach(function (b) { + if (b) stream.emit("data", b) + else stream.emit("end") + }) + + stream.resume() + } + + return dest + }})(stream.pipe) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-reader.js new file mode 100644 index 0000000..346ac2b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-reader.js @@ -0,0 +1,251 @@ +// A thing that emits "entry" events with Reader objects +// Pausing it causes it to stop emitting entry events, and also +// pauses the current entry if there is one. + +module.exports = DirReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("inherits") + , mkdir = require("mkdirp") + , path = require("path") + , Reader = require("./reader.js") + , assert = require("assert").ok + +inherits(DirReader, Reader) + +function DirReader (props) { + var me = this + if (!(me instanceof DirReader)) throw new Error( + "DirReader must be called as constructor.") + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + throw new Error("Non-directory type "+ props.type) + } + + me.entries = null + me._index = -1 + me._paused = false + me._length = -1 + + if (props.sort) { + this.sort = props.sort + } + + Reader.call(this, props) +} + +DirReader.prototype._getEntries = function () { + var me = this + + // race condition. might pause() before calling _getEntries, + // and then resume, and try to get them a second time. + if (me._gotEntries) return + me._gotEntries = true + + fs.readdir(me._path, function (er, entries) { + if (er) return me.error(er) + + me.entries = entries + + me.emit("entries", entries) + if (me._paused) me.once("resume", processEntries) + else processEntries() + + function processEntries () { + me._length = me.entries.length + if (typeof me.sort === "function") { + me.entries = me.entries.sort(me.sort.bind(me)) + } + me._read() + } + }) +} + +// start walking the dir, and emit an "entry" event for each one. +DirReader.prototype._read = function () { + var me = this + + if (!me.entries) return me._getEntries() + + if (me._paused || me._currentEntry || me._aborted) { + // console.error("DR paused=%j, current=%j, aborted=%j", me._paused, !!me._currentEntry, me._aborted) + return + } + + me._index ++ + if (me._index >= me.entries.length) { + if (!me._ended) { + me._ended = true + me.emit("end") + me.emit("close") + } + return + } + + // ok, handle this one, then. + + // save creating a proxy, by stat'ing the thing now. + var p = path.resolve(me._path, me.entries[me._index]) + assert(p !== me._path) + assert(me.entries[me._index]) + + // set this to prevent trying to _read() again in the stat time. + me._currentEntry = p + fs[ me.props.follow ? "stat" : "lstat" ](p, function (er, stat) { + if (er) return me.error(er) + + var who = me._proxy || me + + stat.path = p + stat.basename = path.basename(p) + stat.dirname = path.dirname(p) + var childProps = me.getChildProps.call(who, stat) + childProps.path = p + childProps.basename = path.basename(p) + childProps.dirname = path.dirname(p) + + var entry = Reader(childProps, stat) + + // console.error("DR Entry", p, stat.size) + + me._currentEntry = entry + + // "entry" events are for direct entries in a specific dir. + // "child" events are for any and all children at all levels. + // This nomenclature is not completely final. + + entry.on("pause", function (who) { + if (!me._paused && !entry._disowned) { + me.pause(who) + } + }) + + entry.on("resume", function (who) { + if (me._paused && !entry._disowned) { + me.resume(who) + } + }) + + entry.on("stat", function (props) { + me.emit("_entryStat", entry, props) + if (entry._aborted) return + if (entry._paused) entry.once("resume", function () { + me.emit("entryStat", entry, props) + }) + else me.emit("entryStat", entry, props) + }) + + entry.on("ready", function EMITCHILD () { + // console.error("DR emit child", entry._path) + if (me._paused) { + // console.error(" DR emit child - try again later") + // pause the child, and emit the "entry" event once we drain. + // console.error("DR pausing child entry") + entry.pause(me) + return me.once("resume", EMITCHILD) + } + + // skip over sockets. they can't be piped around properly, + // so there's really no sense even acknowledging them. + // if someone really wants to see them, they can listen to + // the "socket" events. + if (entry.type === "Socket") { + me.emit("socket", entry) + } else { + me.emitEntry(entry) + } + }) + + var ended = false + entry.on("close", onend) + entry.on("disown", onend) + function onend () { + if (ended) return + ended = true + me.emit("childEnd", entry) + me.emit("entryEnd", entry) + me._currentEntry = null + if (!me._paused) { + me._read() + } + } + + // XXX Remove this. Works in node as of 0.6.2 or so. + // Long filenames should not break stuff. + entry.on("error", function (er) { + if (entry._swallowErrors) { + me.warn(er) + entry.emit("end") + entry.emit("close") + } else { + me.emit("error", er) + } + }) + + // proxy up some events. + ; [ "child" + , "childEnd" + , "warn" + ].forEach(function (ev) { + entry.on(ev, me.emit.bind(me, ev)) + }) + }) +} + +DirReader.prototype.disown = function (entry) { + entry.emit("beforeDisown") + entry._disowned = true + entry.parent = entry.root = null + if (entry === this._currentEntry) { + this._currentEntry = null + } + entry.emit("disown") +} + +DirReader.prototype.getChildProps = function (stat) { + return { depth: this.depth + 1 + , root: this.root || this + , parent: this + , follow: this.follow + , filter: this.filter + , sort: this.props.sort + , hardlinks: this.props.hardlinks + } +} + +DirReader.prototype.pause = function (who) { + var me = this + if (me._paused) return + who = who || me + me._paused = true + if (me._currentEntry && me._currentEntry.pause) { + me._currentEntry.pause(who) + } + me.emit("pause", who) +} + +DirReader.prototype.resume = function (who) { + var me = this + if (!me._paused) return + who = who || me + + me._paused = false + // console.error("DR Emit Resume", me._path) + me.emit("resume", who) + if (me._paused) { + // console.error("DR Re-paused", me._path) + return + } + + if (me._currentEntry) { + if (me._currentEntry.resume) me._currentEntry.resume(who) + } else me._read() +} + +DirReader.prototype.emitEntry = function (entry) { + this.emit("entry", entry) + this.emit("child", entry) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-writer.js new file mode 100644 index 0000000..7073b88 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/dir-writer.js @@ -0,0 +1,171 @@ +// It is expected that, when .add() returns false, the consumer +// of the DirWriter will pause until a "drain" event occurs. Note +// that this is *almost always going to be the case*, unless the +// thing being written is some sort of unsupported type, and thus +// skipped over. + +module.exports = DirWriter + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , Writer = require("./writer.js") + , inherits = require("inherits") + , mkdir = require("mkdirp") + , path = require("path") + , collect = require("./collect.js") + +inherits(DirWriter, Writer) + +function DirWriter (props) { + var me = this + if (!(me instanceof DirWriter)) me.error( + "DirWriter must be called as constructor.", null, true) + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + me.error("Non-directory type "+ props.type + " " + + JSON.stringify(props), null, true) + } + + Writer.call(this, props) +} + +DirWriter.prototype._create = function () { + var me = this + mkdir(me._path, Writer.dirmode, function (er) { + if (er) return me.error(er) + // ready to start getting entries! + me.ready = true + me.emit("ready") + me._process() + }) +} + +// a DirWriter has an add(entry) method, but its .write() doesn't +// do anything. Why a no-op rather than a throw? Because this +// leaves open the door for writing directory metadata for +// gnu/solaris style dumpdirs. +DirWriter.prototype.write = function () { + return true +} + +DirWriter.prototype.end = function () { + this._ended = true + this._process() +} + +DirWriter.prototype.add = function (entry) { + var me = this + + // console.error("\tadd", entry._path, "->", me._path) + collect(entry) + if (!me.ready || me._currentEntry) { + me._buffer.push(entry) + return false + } + + // create a new writer, and pipe the incoming entry into it. + if (me._ended) { + return me.error("add after end") + } + + me._buffer.push(entry) + me._process() + + return 0 === this._buffer.length +} + +DirWriter.prototype._process = function () { + var me = this + + // console.error("DW Process p=%j", me._processing, me.basename) + + if (me._processing) return + + var entry = me._buffer.shift() + if (!entry) { + // console.error("DW Drain") + me.emit("drain") + if (me._ended) me._finish() + return + } + + me._processing = true + // console.error("DW Entry", entry._path) + + me.emit("entry", entry) + + // ok, add this entry + // + // don't allow recursive copying + var p = entry + do { + var pp = p._path || p.path + if (pp === me.root._path || pp === me._path || + (pp && pp.indexOf(me._path) === 0)) { + // console.error("DW Exit (recursive)", entry.basename, me._path) + me._processing = false + if (entry._collected) entry.pipe() + return me._process() + } + } while (p = p.parent) + + // console.error("DW not recursive") + + // chop off the entry's root dir, replace with ours + var props = { parent: me + , root: me.root || me + , type: entry.type + , depth: me.depth + 1 } + + var p = entry._path || entry.path || entry.props.path + if (entry.parent) { + p = p.substr(entry.parent._path.length + 1) + } + // get rid of any ../../ shenanigans + props.path = path.join(me.path, path.join("/", p)) + + // if i have a filter, the child should inherit it. + props.filter = me.filter + + // all the rest of the stuff, copy over from the source. + Object.keys(entry.props).forEach(function (k) { + if (!props.hasOwnProperty(k)) { + props[k] = entry.props[k] + } + }) + + // not sure at this point what kind of writer this is. + var child = me._currentChild = new Writer(props) + child.on("ready", function () { + // console.error("DW Child Ready", child.type, child._path) + // console.error(" resuming", entry._path) + entry.pipe(child) + entry.resume() + }) + + // XXX Make this work in node. + // Long filenames should not break stuff. + child.on("error", function (er) { + if (child._swallowErrors) { + me.warn(er) + child.emit("end") + child.emit("close") + } else { + me.emit("error", er) + } + }) + + // we fire _end internally *after* end, so that we don't move on + // until any "end" listeners have had their chance to do stuff. + child.on("close", onend) + var ended = false + function onend () { + if (ended) return + ended = true + // console.error("* DW Child end", child.basename) + me._currentChild = null + me._processing = false + me._process() + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-reader.js new file mode 100644 index 0000000..b1f9861 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-reader.js @@ -0,0 +1,147 @@ +// Basically just a wrapper around an fs.ReadStream + +module.exports = FileReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("inherits") + , mkdir = require("mkdirp") + , Reader = require("./reader.js") + , EOF = {EOF: true} + , CLOSE = {CLOSE: true} + +inherits(FileReader, Reader) + +function FileReader (props) { + // console.error(" FR create", props.path, props.size, new Error().stack) + var me = this + if (!(me instanceof FileReader)) throw new Error( + "FileReader must be called as constructor.") + + // should already be established as a File type + // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, + // with a HardLinkReader class. + if (!((props.type === "Link" && props.Link) || + (props.type === "File" && props.File))) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesEmitted = 0 + Reader.call(me, props) +} + +FileReader.prototype._getStream = function () { + var me = this + , stream = me._stream = fs.createReadStream(me._path, me.props) + + if (me.props.blksize) { + stream.bufferSize = me.props.blksize + } + + stream.on("open", me.emit.bind(me, "open")) + + stream.on("data", function (c) { + // console.error("\t\t%d %s", c.length, me.basename) + me._bytesEmitted += c.length + // no point saving empty chunks + if (!c.length) return + else if (me._paused || me._buffer.length) { + me._buffer.push(c) + me._read() + } else me.emit("data", c) + }) + + stream.on("end", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering End", me._path) + me._buffer.push(EOF) + me._read() + } else { + me.emit("end") + } + + if (me._bytesEmitted !== me.props.size) { + me.error("Didn't get expected byte count\n"+ + "expect: "+me.props.size + "\n" + + "actual: "+me._bytesEmitted) + } + }) + + stream.on("close", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering Close", me._path) + me._buffer.push(CLOSE) + me._read() + } else { + // console.error("FR close 1", me._path) + me.emit("close") + } + }) + + me._read() +} + +FileReader.prototype._read = function () { + var me = this + // console.error("FR _read", me._path) + if (me._paused) { + // console.error("FR _read paused", me._path) + return + } + + if (!me._stream) { + // console.error("FR _getStream calling", me._path) + return me._getStream() + } + + // clear out the buffer, if there is one. + if (me._buffer.length) { + // console.error("FR _read has buffer", me._buffer.length, me._path) + var buf = me._buffer + for (var i = 0, l = buf.length; i < l; i ++) { + var c = buf[i] + if (c === EOF) { + // console.error("FR Read emitting buffered end", me._path) + me.emit("end") + } else if (c === CLOSE) { + // console.error("FR Read emitting buffered close", me._path) + me.emit("close") + } else { + // console.error("FR Read emitting buffered data", me._path) + me.emit("data", c) + } + + if (me._paused) { + // console.error("FR Read Re-pausing at "+i, me._path) + me._buffer = buf.slice(i) + return + } + } + me._buffer.length = 0 + } + // console.error("FR _read done") + // that's about all there is to it. +} + +FileReader.prototype.pause = function (who) { + var me = this + // console.error("FR Pause", me._path) + if (me._paused) return + who = who || me + me._paused = true + if (me._stream) me._stream.pause() + me.emit("pause", who) +} + +FileReader.prototype.resume = function (who) { + var me = this + // console.error("FR Resume", me._path) + if (!me._paused) return + who = who || me + me.emit("resume", who) + me._paused = false + if (me._stream) me._stream.resume() + me._read() +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-writer.js new file mode 100644 index 0000000..5e9902a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/file-writer.js @@ -0,0 +1,104 @@ +module.exports = FileWriter + +var fs = require("graceful-fs") + , mkdir = require("mkdirp") + , Writer = require("./writer.js") + , inherits = require("inherits") + , EOF = {} + +inherits(FileWriter, Writer) + +function FileWriter (props) { + var me = this + if (!(me instanceof FileWriter)) throw new Error( + "FileWriter must be called as constructor.") + + // should already be established as a File type + if (props.type !== "File" || !props.File) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesWritten = 0 + + Writer.call(this, props) +} + +FileWriter.prototype._create = function () { + var me = this + if (me._stream) return + + var so = {} + if (me.props.flags) so.flags = me.props.flags + so.mode = Writer.filemode + if (me._old && me._old.blksize) so.bufferSize = me._old.blksize + + me._stream = fs.createWriteStream(me._path, so) + + me._stream.on("open", function (fd) { + // console.error("FW open", me._buffer, me._path) + me.ready = true + me._buffer.forEach(function (c) { + if (c === EOF) me._stream.end() + else me._stream.write(c) + }) + me.emit("ready") + // give this a kick just in case it needs it. + me.emit("drain") + }) + + me._stream.on("drain", function () { me.emit("drain") }) + + me._stream.on("close", function () { + // console.error("\n\nFW Stream Close", me._path, me.size) + me._finish() + }) +} + +FileWriter.prototype.write = function (c) { + var me = this + + me._bytesWritten += c.length + + if (!me.ready) { + if (!Buffer.isBuffer(c) && typeof c !== 'string') + throw new Error('invalid write data') + me._buffer.push(c) + return false + } + + var ret = me._stream.write(c) + // console.error("\t-- fw wrote, _stream says", ret, me._stream._queue.length) + + // allow 2 buffered writes, because otherwise there's just too + // much stop and go bs. + if (ret === false && me._stream._queue) { + return me._stream._queue.length <= 2; + } else { + return ret; + } +} + +FileWriter.prototype.end = function (c) { + var me = this + + if (c) me.write(c) + + if (!me.ready) { + me._buffer.push(EOF) + return false + } + + return me._stream.end() +} + +FileWriter.prototype._finish = function () { + var me = this + if (typeof me.size === "number" && me._bytesWritten != me.size) { + me.error( + "Did not get expected byte count.\n" + + "expect: " + me.size + "\n" + + "actual: " + me._bytesWritten) + } + Writer.prototype._finish.call(me) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/get-type.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/get-type.js new file mode 100644 index 0000000..cd65c41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/get-type.js @@ -0,0 +1,32 @@ +module.exports = getType + +function getType (st) { + var types = + [ "Directory" + , "File" + , "SymbolicLink" + , "Link" // special for hardlinks from tarballs + , "BlockDevice" + , "CharacterDevice" + , "FIFO" + , "Socket" ] + , type + + if (st.type && -1 !== types.indexOf(st.type)) { + st[st.type] = true + return st.type + } + + for (var i = 0, l = types.length; i < l; i ++) { + type = types[i] + var is = st[type] || st["is" + type] + if (typeof is === "function") is = is.call(st) + if (is) { + st[type] = true + st.type = type + return type + } + } + + return null +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-reader.js new file mode 100644 index 0000000..7e7ab6c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-reader.js @@ -0,0 +1,54 @@ +// Basically just a wrapper around an fs.readlink +// +// XXX: Enhance this to support the Link type, by keeping +// a lookup table of {:}, so that hardlinks +// can be preserved in tarballs. + +module.exports = LinkReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , inherits = require("inherits") + , mkdir = require("mkdirp") + , Reader = require("./reader.js") + +inherits(LinkReader, Reader) + +function LinkReader (props) { + var me = this + if (!(me instanceof LinkReader)) throw new Error( + "LinkReader must be called as constructor.") + + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + Reader.call(me, props) +} + +// When piping a LinkReader into a LinkWriter, we have to +// already have the linkpath property set, so that has to +// happen *before* the "ready" event, which means we need to +// override the _stat method. +LinkReader.prototype._stat = function (currentStat) { + var me = this + fs.readlink(me._path, function (er, linkpath) { + if (er) return me.error(er) + me.linkpath = me.props.linkpath = linkpath + me.emit("linkpath", linkpath) + Reader.prototype._stat.call(me, currentStat) + }) +} + +LinkReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we need + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-writer.js new file mode 100644 index 0000000..5c8f1e7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/link-writer.js @@ -0,0 +1,95 @@ + +module.exports = LinkWriter + +var fs = require("graceful-fs") + , Writer = require("./writer.js") + , inherits = require("inherits") + , path = require("path") + , rimraf = require("rimraf") + +inherits(LinkWriter, Writer) + +function LinkWriter (props) { + var me = this + if (!(me instanceof LinkWriter)) throw new Error( + "LinkWriter must be called as constructor.") + + // should already be established as a Link type + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + if (props.linkpath === "") props.linkpath = "." + if (!props.linkpath) { + me.error("Need linkpath property to create " + props.type) + } + + Writer.call(this, props) +} + +LinkWriter.prototype._create = function () { + // console.error(" LW _create") + var me = this + , hard = me.type === "Link" || process.platform === "win32" + , link = hard ? "link" : "symlink" + , lp = hard ? path.resolve(me.dirname, me.linkpath) : me.linkpath + + // can only change the link path by clobbering + // For hard links, let's just assume that's always the case, since + // there's no good way to read them if we don't already know. + if (hard) return clobber(me, lp, link) + + fs.readlink(me._path, function (er, p) { + // only skip creation if it's exactly the same link + if (p && p === lp) return finish(me) + clobber(me, lp, link) + }) +} + +function clobber (me, lp, link) { + rimraf(me._path, function (er) { + if (er) return me.error(er) + create(me, lp, link) + }) +} + +function create (me, lp, link) { + fs[link](lp, me._path, function (er) { + // if this is a hard link, and we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier in. + // Additionally, an EPERM or EACCES can happen on win32 if it's trying + // to make a link to a directory. Again, just skip it. + // A better solution would be to have fs.symlink be supported on + // windows in some nice fashion. + if (er) { + if ((er.code === "ENOENT" || + er.code === "EACCES" || + er.code === "EPERM" ) && process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + } else return me.error(er) + } + finish(me) + }) +} + +function finish (me) { + me.ready = true + me.emit("ready") + if (me._ended && !me._finished) me._finish() +} + +LinkWriter.prototype.end = function () { + // console.error("LW finish in end") + this._ended = true + if (this.ready) { + this._finished = true + this._finish() + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-reader.js new file mode 100644 index 0000000..a0ece34 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-reader.js @@ -0,0 +1,93 @@ +// A reader for when we don't yet know what kind of thing +// the thing is. + +module.exports = ProxyReader + +var Reader = require("./reader.js") + , getType = require("./get-type.js") + , inherits = require("inherits") + , fs = require("graceful-fs") + +inherits(ProxyReader, Reader) + +function ProxyReader (props) { + var me = this + if (!(me instanceof ProxyReader)) throw new Error( + "ProxyReader must be called as constructor.") + + me.props = props + me._buffer = [] + me.ready = false + + Reader.call(me, props) +} + +ProxyReader.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Reader(props, current)) + }) +} + +ProxyReader.prototype._addProxy = function (proxy) { + var me = this + if (me._proxyTarget) { + return me.error("proxy already set") + } + + me._proxyTarget = proxy + proxy._proxy = me + + ; [ "error" + , "data" + , "end" + , "close" + , "linkpath" + , "entry" + , "entryEnd" + , "child" + , "childEnd" + , "warn" + , "stat" + ].forEach(function (ev) { + // console.error("~~ proxy event", ev, me.path) + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + proxy.on("ready", function () { + // console.error("~~ proxy is ready!", me.path) + me.ready = true + me.emit("ready") + }) + + var calls = me._buffer + me._buffer.length = 0 + calls.forEach(function (c) { + proxy[c[0]].apply(proxy, c[1]) + }) +} + +ProxyReader.prototype.pause = function () { + return this._proxyTarget ? this._proxyTarget.pause() : false +} + +ProxyReader.prototype.resume = function () { + return this._proxyTarget ? this._proxyTarget.resume() : false +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-writer.js new file mode 100644 index 0000000..b047663 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/proxy-writer.js @@ -0,0 +1,109 @@ +// A writer for when we don't know what kind of thing +// the thing is. That is, it's not explicitly set, +// so we're going to make it whatever the thing already +// is, or "File" +// +// Until then, collect all events. + +module.exports = ProxyWriter + +var Writer = require("./writer.js") + , getType = require("./get-type.js") + , inherits = require("inherits") + , collect = require("./collect.js") + , fs = require("fs") + +inherits(ProxyWriter, Writer) + +function ProxyWriter (props) { + var me = this + if (!(me instanceof ProxyWriter)) throw new Error( + "ProxyWriter must be called as constructor.") + + me.props = props + me._needDrain = false + + Writer.call(me, props) +} + +ProxyWriter.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Writer(props, current)) + }) +} + +ProxyWriter.prototype._addProxy = function (proxy) { + // console.error("~~ set proxy", this.path) + var me = this + if (me._proxy) { + return me.error("proxy already set") + } + + me._proxy = proxy + ; [ "ready" + , "error" + , "close" + , "pipe" + , "drain" + , "warn" + ].forEach(function (ev) { + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + var calls = me._buffer + calls.forEach(function (c) { + // console.error("~~ ~~ proxy buffered call", c[0], c[1]) + proxy[c[0]].apply(proxy, c[1]) + }) + me._buffer.length = 0 + if (me._needsDrain) me.emit("drain") +} + +ProxyWriter.prototype.add = function (entry) { + // console.error("~~ proxy add") + collect(entry) + + if (!this._proxy) { + this._buffer.push(["add", [entry]]) + this._needDrain = true + return false + } + return this._proxy.add(entry) +} + +ProxyWriter.prototype.write = function (c) { + // console.error("~~ proxy write") + if (!this._proxy) { + this._buffer.push(["write", [c]]) + this._needDrain = true + return false + } + return this._proxy.write(c) +} + +ProxyWriter.prototype.end = function (c) { + // console.error("~~ proxy end") + if (!this._proxy) { + this._buffer.push(["end", [c]]) + return false + } + return this._proxy.end(c) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/reader.js new file mode 100644 index 0000000..0edb794 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/reader.js @@ -0,0 +1,262 @@ + +module.exports = Reader + +var fs = require("graceful-fs") + , Stream = require("stream").Stream + , inherits = require("inherits") + , path = require("path") + , getType = require("./get-type.js") + , hardLinks = Reader.hardLinks = {} + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Reader, Abstract) + +var DirReader = require("./dir-reader.js") + , FileReader = require("./file-reader.js") + , LinkReader = require("./link-reader.js") + , SocketReader = require("./socket-reader.js") + , ProxyReader = require("./proxy-reader.js") + +function Reader (props, currentStat) { + var me = this + if (!(me instanceof Reader)) return new Reader(props, currentStat) + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) { + me.error("Must provide a path", null, true) + } + + // polymorphism. + // call fstream.Reader(dir) to get a DirReader object, etc. + // Note that, unlike in the Writer case, ProxyReader is going + // to be the *normal* state of affairs, since we rarely know + // the type of a file prior to reading it. + + + var type + , ClassType + + if (props.type && typeof props.type === "function") { + type = props.type + ClassType = type + } else { + type = getType(props) + ClassType = Reader + } + + if (currentStat && !type) { + type = getType(currentStat) + props[type] = true + props.type = type + } + + switch (type) { + case "Directory": + ClassType = DirReader + break + + case "Link": + // XXX hard links are just files. + // However, it would be good to keep track of files' dev+inode + // and nlink values, and create a HardLinkReader that emits + // a linkpath value of the original copy, so that the tar + // writer can preserve them. + // ClassType = HardLinkReader + // break + + case "File": + ClassType = FileReader + break + + case "SymbolicLink": + ClassType = LinkReader + break + + case "Socket": + ClassType = SocketReader + break + + case null: + ClassType = ProxyReader + break + } + + if (!(me instanceof ClassType)) { + return new ClassType(props) + } + + Abstract.call(me) + + me.readable = true + me.writable = false + + me.type = type + me.props = props + me.depth = props.depth = props.depth || 0 + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + // how DOES one create files on the moon? + // if the path has spaces in it, then UNC will fail. + me._swallowErrors = true + //if (me._path.indexOf(" ") === -1) { + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + //} + } + } + me.basename = props.basename = path.basename(me.path) + me.dirname = props.dirname = path.dirname(me.path) + + // these have served their purpose, and are now just noisy clutter + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + me.filter = typeof props.filter === "function" ? props.filter : null + if (props.sort === "alpha") props.sort = alphasort + + // start the ball rolling. + // this will stat the thing, and then call me._read() + // to start reading whatever it is. + // console.error("calling stat", props.path, currentStat) + me._stat(currentStat) +} + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + +Reader.prototype._stat = function (currentStat) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + // console.error("Reader._stat", me._path, currentStat) + if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) + else fs[stat](me._path, statCb) + + + function statCb (er, props_) { + // console.error("Reader._stat, statCb", me._path, props_, props_.nlink) + if (er) return me.error(er) + + Object.keys(props_).forEach(function (k) { + props[k] = props_[k] + }) + + // if it's not the expected size, then abort here. + if (undefined !== me.size && props.size !== me.size) { + return me.error("incorrect size") + } + me.size = props.size + + var type = getType(props) + var handleHardlinks = props.hardlinks !== false + + // special little thing for handling hardlinks. + if (handleHardlinks && type !== "Directory" && props.nlink && props.nlink > 1) { + var k = props.dev + ":" + props.ino + // console.error("Reader has nlink", me._path, k) + if (hardLinks[k] === me._path || !hardLinks[k]) hardLinks[k] = me._path + else { + // switch into hardlink mode. + type = me.type = me.props.type = "Link" + me.Link = me.props.Link = true + me.linkpath = me.props.linkpath = hardLinks[k] + // console.error("Hardlink detected, switching mode", me._path, me.linkpath) + // Setting __proto__ would arguably be the "correct" + // approach here, but that just seems too wrong. + me._stat = me._read = LinkReader.prototype._read + } + } + + if (me.type && me.type !== type) { + me.error("Unexpected type: " + type) + } + + // if the filter doesn't pass, then just skip over this one. + // still have to emit end so that dir-walking can move on. + if (me.filter) { + var who = me._proxy || me + // special handling for ProxyReaders + if (!me.filter.call(who, who, props)) { + if (!me._disowned) { + me.abort() + me.emit("end") + me.emit("close") + } + return + } + } + + // last chance to abort or disown before the flow starts! + var events = ["_stat", "stat", "ready"] + var e = 0 + ;(function go () { + if (me._aborted) { + me.emit("end") + me.emit("close") + return + } + + if (me._paused && me.type !== "Directory") { + me.once("resume", go) + return + } + + var ev = events[e ++] + if (!ev) { + return me._read() + } + me.emit(ev, props) + go() + })() + } +} + +Reader.prototype.pipe = function (dest, opts) { + var me = this + if (typeof dest.add === "function") { + // piping to a multi-compatible, and we've got directory entries. + me.on("entry", function (entry) { + var ret = dest.add(entry) + if (false === ret) { + me.pause() + } + }) + } + + // console.error("R Pipe apply Stream Pipe") + return Stream.prototype.pipe.apply(this, arguments) +} + +Reader.prototype.pause = function (who) { + this._paused = true + who = who || this + this.emit("pause", who) + if (this._stream) this._stream.pause(who) +} + +Reader.prototype.resume = function (who) { + this._paused = false + who = who || this + this.emit("resume", who) + if (this._stream) this._stream.resume(who) + this._read() +} + +Reader.prototype._read = function () { + this.error("Cannot read unknown type: "+this.type) +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/socket-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/socket-reader.js new file mode 100644 index 0000000..e89c173 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/socket-reader.js @@ -0,0 +1,38 @@ +// Just get the stats, and then don't do anything. +// You can't really "read" from a socket. You "connect" to it. +// Mostly, this is here so that reading a dir with a socket in it +// doesn't blow up. + +module.exports = SocketReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , inherits = require("inherits") + , mkdir = require("mkdirp") + , Reader = require("./reader.js") + +inherits(SocketReader, Reader) + +function SocketReader (props) { + var me = this + if (!(me instanceof SocketReader)) throw new Error( + "SocketReader must be called as constructor.") + + if (!(props.type === "Socket" && props.Socket)) { + throw new Error("Non-socket type "+ props.type) + } + + Reader.call(me, props) +} + +SocketReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we have + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/writer.js new file mode 100644 index 0000000..5599fb2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/lib/writer.js @@ -0,0 +1,389 @@ + +module.exports = Writer + +var fs = require("graceful-fs") + , inherits = require("inherits") + , rimraf = require("rimraf") + , mkdir = require("mkdirp") + , path = require("path") + , umask = process.platform === "win32" ? 0 : process.umask() + , getType = require("./get-type.js") + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Writer, Abstract) + +Writer.dirmode = 0777 & (~umask) +Writer.filemode = 0666 & (~umask) + +var DirWriter = require("./dir-writer.js") + , LinkWriter = require("./link-writer.js") + , FileWriter = require("./file-writer.js") + , ProxyWriter = require("./proxy-writer.js") + +// props is the desired state. current is optionally the current stat, +// provided here so that subclasses can avoid statting the target +// more than necessary. +function Writer (props, current) { + var me = this + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) me.error("Must provide a path", null, true) + + // polymorphism. + // call fstream.Writer(dir) to get a DirWriter object, etc. + var type = getType(props) + , ClassType = Writer + + switch (type) { + case "Directory": + ClassType = DirWriter + break + case "File": + ClassType = FileWriter + break + case "Link": + case "SymbolicLink": + ClassType = LinkWriter + break + case null: + // Don't know yet what type to create, so we wrap in a proxy. + ClassType = ProxyWriter + break + } + + if (!(me instanceof ClassType)) return new ClassType(props) + + // now get down to business. + + Abstract.call(me) + + // props is what we want to set. + // set some convenience properties as well. + me.type = props.type + me.props = props + me.depth = props.depth || 0 + me.clobber = false === props.clobber ? props.clobber : true + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + me._swallowErrors = true + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + } + } + me.basename = path.basename(props.path) + me.dirname = path.dirname(props.path) + me.linkpath = props.linkpath || null + + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + + if (typeof props.mode === "string") { + props.mode = parseInt(props.mode, 8) + } + + me.readable = false + me.writable = true + + // buffer until ready, or while handling another entry + me._buffer = [] + me.ready = false + + me.filter = typeof props.filter === "function" ? props.filter: null + + // start the ball rolling. + // this checks what's there already, and then calls + // me._create() to call the impl-specific creation stuff. + me._stat(current) +} + +// Calling this means that it's something we can't create. +// Just assert that it's already there, otherwise raise a warning. +Writer.prototype._create = function () { + var me = this + fs[me.props.follow ? "stat" : "lstat"](me._path, function (er, current) { + if (er) { + return me.warn("Cannot create " + me._path + "\n" + + "Unsupported type: "+me.type, "ENOTSUP") + } + me._finish() + }) +} + +Writer.prototype._stat = function (current) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + , who = me._proxy || me + + if (current) statCb(null, current) + else fs[stat](me._path, statCb) + + function statCb (er, current) { + if (me.filter && !me.filter.call(who, who, current)) { + me._aborted = true + me.emit("end") + me.emit("close") + return + } + + // if it's not there, great. We'll just create it. + // if it is there, then we'll need to change whatever differs + if (er || !current) { + return create(me) + } + + me._old = current + var currentType = getType(current) + + // if it's a type change, then we need to clobber or error. + // if it's not a type change, then let the impl take care of it. + if (currentType !== me.type) { + return rimraf(me._path, function (er) { + if (er) return me.error(er) + me._old = null + create(me) + }) + } + + // otherwise, just handle in the app-specific way + // this creates a fs.WriteStream, or mkdir's, or whatever + create(me) + } +} + +function create (me) { + // console.error("W create", me._path, Writer.dirmode) + + // XXX Need to clobber non-dirs that are in the way, + // unless { clobber: false } in the props. + mkdir(path.dirname(me._path), Writer.dirmode, function (er, made) { + // console.error("W created", path.dirname(me._path), er) + if (er) return me.error(er) + + // later on, we have to set the mode and owner for these + me._madeDir = made + return me._create() + }) +} + +function endChmod (me, want, current, path, cb) { + var wantMode = want.mode + , chmod = want.follow || me.type !== "SymbolicLink" + ? "chmod" : "lchmod" + + if (!fs[chmod]) return cb() + if (typeof wantMode !== "number") return cb() + + var curMode = current.mode & 0777 + wantMode = wantMode & 0777 + if (wantMode === curMode) return cb() + + fs[chmod](path, wantMode, cb) +} + + +function endChown (me, want, current, path, cb) { + // Don't even try it unless root. Too easy to EPERM. + if (process.platform === "win32") return cb() + if (!process.getuid || !process.getuid() === 0) return cb() + if (typeof want.uid !== "number" && + typeof want.gid !== "number" ) return cb() + + if (current.uid === want.uid && + current.gid === want.gid) return cb() + + var chown = (me.props.follow || me.type !== "SymbolicLink") + ? "chown" : "lchown" + if (!fs[chown]) return cb() + + if (typeof want.uid !== "number") want.uid = current.uid + if (typeof want.gid !== "number") want.gid = current.gid + + fs[chown](path, want.uid, want.gid, cb) +} + +function endUtimes (me, want, current, path, cb) { + if (!fs.utimes || process.platform === "win32") return cb() + + var utimes = (want.follow || me.type !== "SymbolicLink") + ? "utimes" : "lutimes" + + if (utimes === "lutimes" && !fs[utimes]) { + utimes = "utimes" + } + + if (!fs[utimes]) return cb() + + var curA = current.atime + , curM = current.mtime + , meA = want.atime + , meM = want.mtime + + if (meA === undefined) meA = curA + if (meM === undefined) meM = curM + + if (!isDate(meA)) meA = new Date(meA) + if (!isDate(meM)) meA = new Date(meM) + + if (meA.getTime() === curA.getTime() && + meM.getTime() === curM.getTime()) return cb() + + fs[utimes](path, meA, meM, cb) +} + + +// XXX This function is beastly. Break it up! +Writer.prototype._finish = function () { + var me = this + + // console.error(" W Finish", me._path, me.size) + + // set up all the things. + // At this point, we're already done writing whatever we've gotta write, + // adding files to the dir, etc. + var todo = 0 + var errState = null + var done = false + + if (me._old) { + // the times will almost *certainly* have changed. + // adds the utimes syscall, but remove another stat. + me._old.atime = new Date(0) + me._old.mtime = new Date(0) + // console.error(" W Finish Stale Stat", me._path, me.size) + setProps(me._old) + } else { + var stat = me.props.follow ? "stat" : "lstat" + // console.error(" W Finish Stating", me._path, me.size) + fs[stat](me._path, function (er, current) { + // console.error(" W Finish Stated", me._path, me.size, current) + if (er) { + // if we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier on. + if (er.code === "ENOENT" && + (me.type === "Link" || me.type === "SymbolicLink") && + process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + return + } else return me.error(er) + } + setProps(me._old = current) + }) + } + + return + + function setProps (current) { + todo += 3 + endChmod(me, me.props, current, me._path, next("chmod")) + endChown(me, me.props, current, me._path, next("chown")) + endUtimes(me, me.props, current, me._path, next("utimes")) + } + + function next (what) { + return function (er) { + // console.error(" W Finish", what, todo) + if (errState) return + if (er) { + er.fstream_finish_call = what + return me.error(errState = er) + } + if (--todo > 0) return + if (done) return + done = true + + // we may still need to set the mode/etc. on some parent dirs + // that were created previously. delay end/close until then. + if (!me._madeDir) return end() + else endMadeDir(me, me._path, end) + + function end (er) { + if (er) { + er.fstream_finish_call = "setupMadeDir" + return me.error(er) + } + // all the props have been set, so we're completely done. + me.emit("end") + me.emit("close") + } + } + } +} + +function endMadeDir (me, p, cb) { + var made = me._madeDir + // everything *between* made and path.dirname(me._path) + // needs to be set up. Note that this may just be one dir. + var d = path.dirname(p) + + endMadeDir_(me, d, function (er) { + if (er) return cb(er) + if (d === made) { + return cb() + } + endMadeDir(me, d, cb) + }) +} + +function endMadeDir_ (me, p, cb) { + var dirProps = {} + Object.keys(me.props).forEach(function (k) { + dirProps[k] = me.props[k] + + // only make non-readable dirs if explicitly requested. + if (k === "mode" && me.type !== "Directory") { + dirProps[k] = dirProps[k] | 0111 + } + }) + + var todo = 3 + , errState = null + fs.stat(p, function (er, current) { + if (er) return cb(errState = er) + endChmod(me, dirProps, current, p, next) + endChown(me, dirProps, current, p, next) + endUtimes(me, dirProps, current, p, next) + }) + + function next (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- todo === 0) return cb() + } +} + +Writer.prototype.pipe = function () { + this.error("Can't pipe from writable stream") +} + +Writer.prototype.add = function () { + this.error("Cannot add to non-Directory type") +} + +Writer.prototype.write = function () { + return true +} + +function objectToString (d) { + return Object.prototype.toString.call(d) +} + +function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/.npmignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..13a2e86 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/README.md @@ -0,0 +1,36 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](http://api.nodejs.org/fs.html) + +graceful-fs: + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFileSync('some-file-or-whatever') +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/fs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/fs.js new file mode 100644 index 0000000..64ad980 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/fs.js @@ -0,0 +1,11 @@ +// eeeeeevvvvviiiiiiillllll +// more evil than monkey-patching the native builtin? +// Not sure. + +var mod = require("module") +var pre = '(function (exports, require, module, __filename, __dirname) { ' +var post = '});' +var src = pre + process.binding('natives').fs + post +var vm = require('vm') +var fn = vm.runInThisContext(src) +fn(exports, require, module, __filename, __dirname) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..fb206b8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,158 @@ +// Monkey-patching the fs module. +// It's ugly, but there is simply no other way to do this. +var fs = module.exports = require('./fs.js') + +var assert = require('assert') + +// fix up some busted stuff, mostly on windows and old nodes +require('./polyfills.js') + +var util = require('util') + +function noop () {} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs') +else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS: ' + m.split(/\n/).join('\nGFS: ') + console.error(m) + } + +if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug('fds', fds) + debug(queue) + assert.equal(queue.length, 0) + }) +} + + +var originalOpen = fs.open +fs.open = open + +function open(path, flags, mode, cb) { + if (typeof mode === "function") cb = mode, mode = null + if (typeof cb !== "function") cb = noop + new OpenReq(path, flags, mode, cb) +} + +function OpenReq(path, flags, mode, cb) { + this.path = path + this.flags = flags + this.mode = mode + this.cb = cb + Req.call(this) +} + +util.inherits(OpenReq, Req) + +OpenReq.prototype.process = function() { + originalOpen.call(fs, this.path, this.flags, this.mode, this.done) +} + +var fds = {} +OpenReq.prototype.done = function(er, fd) { + debug('open done', er, fd) + if (fd) + fds['fd' + fd] = this.path + Req.prototype.done.call(this, er, fd) +} + + +var originalReaddir = fs.readdir +fs.readdir = readdir + +function readdir(path, cb) { + if (typeof cb !== "function") cb = noop + new ReaddirReq(path, cb) +} + +function ReaddirReq(path, cb) { + this.path = path + this.cb = cb + Req.call(this) +} + +util.inherits(ReaddirReq, Req) + +ReaddirReq.prototype.process = function() { + originalReaddir.call(fs, this.path, this.done) +} + +ReaddirReq.prototype.done = function(er, files) { + if (files && files.sort) + files = files.sort() + Req.prototype.done.call(this, er, files) + onclose() +} + + +var originalClose = fs.close +fs.close = close + +function close (fd, cb) { + debug('close', fd) + if (typeof cb !== "function") cb = noop + delete fds['fd' + fd] + originalClose.call(fs, fd, function(er) { + onclose() + cb(er) + }) +} + + +var originalCloseSync = fs.closeSync +fs.closeSync = closeSync + +function closeSync (fd) { + try { + return originalCloseSync(fd) + } finally { + onclose() + } +} + + +// Req class +function Req () { + // start processing + this.done = this.done.bind(this) + this.failures = 0 + this.process() +} + +Req.prototype.done = function (er, result) { + var tryAgain = false + if (er) { + var code = er.code + var tryAgain = code === "EMFILE" || code === "ENFILE" + if (process.platform === "win32") + tryAgain = tryAgain || code === "OK" + } + + if (tryAgain) { + this.failures ++ + enqueue(this) + } else { + var cb = this.cb + cb(er, result) + } +} + +var queue = [] + +function enqueue(req) { + queue.push(req) + debug('enqueue %d %s', queue.length, req.constructor.name, req) +} + +function onclose() { + var req = queue.shift() + if (req) { + debug('process', req.constructor.name, req) + req.process() + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..08930cf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/package.json @@ -0,0 +1,71 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "3.0.8", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-graceful-fs.git" + }, + "main": "graceful-fs.js", + "engines": { + "node": ">=0.4.0" + }, + "directories": { + "test": "test" + }, + "scripts": { + "test": "tap test/*.js" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "devDependencies": { + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^1.2.0" + }, + "gitHead": "45c57aa5e323c35a985a525de6f0c9a6ef59e1f8", + "bugs": { + "url": "https://github.com/isaacs/node-graceful-fs/issues" + }, + "homepage": "https://github.com/isaacs/node-graceful-fs#readme", + "_id": "graceful-fs@3.0.8", + "_shasum": "ce813e725fa82f7e6147d51c9a5ca68270551c22", + "_from": "graceful-fs@>=3.0.0 <4.0.0", + "_npmVersion": "2.10.1", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "ce813e725fa82f7e6147d51c9a5ca68270551c22", + "tarball": "http://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.8.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "_resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.8.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/polyfills.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000..4270539 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,255 @@ +var fs = require('./fs.js') +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} + +// (re-)implement some things that are known busted or missing. + +// lchmod, broken prior to 0.6.2 +// back-port the fix here. +if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + fs.lchmod = function (path, mode, callback) { + callback = callback || noop + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var err, err2 + try { + var ret = fs.fchmodSync(fd, mode) + } catch (er) { + err = er + } + try { + fs.closeSync(fd) + } catch (er) { + err2 = er + } + if (err || err2) throw (err || err2) + return ret + } +} + + +// lutimes implementation, or no-op +if (!fs.lutimes) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + cb = cb || noop + if (er) return cb(er) + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + return cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + , err + , err2 + , ret + + try { + var ret = fs.futimesSync(fd, at, mt) + } catch (er) { + err = er + } + try { + fs.closeSync(fd) + } catch (er) { + err2 = er + } + if (err || err2) throw (err || err2) + return ret + } + + } else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) { + // maybe utimensat will be bound soonish? + fs.lutimes = function (path, at, mt, cb) { + fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb) + } + + fs.lutimesSync = function (path, at, mt) { + return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW) + } + + } else { + fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) } + fs.lutimesSync = function () {} + } +} + + +// https://github.com/isaacs/node-graceful-fs/issues/4 +// Chown should not fail on einval or eperm if non-root. +// It should not fail on enosys ever, as this just indicates +// that a fs doesn't support the intended operation. + +fs.chown = chownFix(fs.chown) +fs.fchown = chownFix(fs.fchown) +fs.lchown = chownFix(fs.lchown) + +fs.chmod = chownFix(fs.chmod) +fs.fchmod = chownFix(fs.fchmod) +fs.lchmod = chownFix(fs.lchmod) + +fs.chownSync = chownFixSync(fs.chownSync) +fs.fchownSync = chownFixSync(fs.fchownSync) +fs.lchownSync = chownFixSync(fs.lchownSync) + +fs.chmodSync = chownFix(fs.chmodSync) +fs.fchmodSync = chownFix(fs.fchmodSync) +fs.lchmodSync = chownFix(fs.lchmodSync) + +function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er, res) { + if (chownErOk(er)) er = null + cb(er, res) + }) + } +} + +function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } +} + +// ENOSYS means that the fs doesn't support the op. Just ignore +// that, because it doesn't matter. +// +// if there's no getuid, or if getuid() is something other +// than 0, and the error is EINVAL or EPERM, then just ignore +// it. +// +// This specific case is a silent failure in cp, install, tar, +// and most other unix tools that manage permissions. +// +// When running as root, or if other types of errors are +// encountered, then it's strict. +function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false +} + + +// if lchmod/lchown do not exist, then make them no-ops +if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + process.nextTick(cb) + } + fs.lchmodSync = function () {} +} +if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + process.nextTick(cb) + } + fs.lchownSync = function () {} +} + + + +// on Windows, A/V software can lock the directory, causing this +// to fail with an EACCES or EPERM if the directory contains newly +// created files. Try again on failure, for up to 1 second. +if (process.platform === "win32") { + var rename_ = fs.rename + fs.rename = function rename (from, to, cb) { + var start = Date.now() + rename_(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 1000) { + return rename_(from, to, CB) + } + if(cb) cb(er) + }) + } +} + + +// if read() returns EAGAIN, then just try it again. +var read = fs.read +fs.read = function (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return read.call(fs, fd, buffer, offset, length, position, callback) +} + +var readSync = fs.readSync +fs.readSync = function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/max-open.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/max-open.js new file mode 100644 index 0000000..a6b9ba4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/max-open.js @@ -0,0 +1,69 @@ +var test = require('tap').test +var fs = require('../') + +test('open lots of stuff', function (t) { + // Get around EBADF from libuv by making sure that stderr is opened + // Otherwise Darwin will refuse to give us a FD for stderr! + process.stderr.write('') + + // How many parallel open()'s to do + var n = 1024 + var opens = 0 + var fds = [] + var going = true + var closing = false + var doneCalled = 0 + + for (var i = 0; i < n; i++) { + go() + } + + function go() { + opens++ + fs.open(__filename, 'r', function (er, fd) { + if (er) throw er + fds.push(fd) + if (going) go() + }) + } + + // should hit ulimit pretty fast + setTimeout(function () { + going = false + t.equal(opens - fds.length, n) + done() + }, 100) + + + function done () { + if (closing) return + doneCalled++ + + if (fds.length === 0) { + console.error('done called %d times', doneCalled) + // First because of the timeout + // Then to close the fd's opened afterwards + // Then this time, to complete. + // Might take multiple passes, depending on CPU speed + // and ulimit, but at least 3 in every case. + t.ok(doneCalled >= 2) + return t.end() + } + + closing = true + setTimeout(function () { + // console.error('do closing again') + closing = false + done() + }, 100) + + // console.error('closing time') + var closes = fds.slice(0) + fds.length = 0 + closes.forEach(function (fd) { + fs.close(fd, function (er) { + if (er) throw er + }) + }) + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/open.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/open.js new file mode 100644 index 0000000..85732f2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/open.js @@ -0,0 +1,39 @@ +var test = require('tap').test +var fs = require('../graceful-fs.js') + +test('graceful fs is monkeypatched fs', function (t) { + t.equal(fs, require('../fs.js')) + t.end() +}) + +test('open an existing file works', function (t) { + var fd = fs.openSync(__filename, 'r') + fs.closeSync(fd) + fs.open(__filename, 'r', function (er, fd) { + if (er) throw er + fs.close(fd, function (er) { + if (er) throw er + t.pass('works') + t.end() + }) + }) +}) + +test('open a non-existing file throws', function (t) { + var er + try { + var fd = fs.openSync('this file does not exist', 'r') + } catch (x) { + er = x + } + t.ok(er, 'should throw') + t.notOk(fd, 'should not get an fd') + t.equal(er.code, 'ENOENT') + + fs.open('neither does this file', 'r', function (er, fd) { + t.ok(er, 'should throw') + t.notOk(fd, 'should not get an fd') + t.equal(er.code, 'ENOENT') + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js new file mode 100644 index 0000000..cb63a68 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js @@ -0,0 +1,20 @@ +var test = require("tap").test +var fs = require("../fs.js") + +var readdir = fs.readdir +fs.readdir = function(path, cb) { + process.nextTick(function() { + cb(null, ["b", "z", "a"]) + }) +} + +var g = require("../") + +test("readdir reorder", function (t) { + g.readdir("whatevers", function (er, files) { + if (er) + throw er + t.same(files, [ "a", "b", "z" ]) + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js new file mode 100644 index 0000000..21e4c26 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js @@ -0,0 +1,47 @@ +var fs = require('../'); +var rimraf = require('rimraf'); +var mkdirp = require('mkdirp'); +var test = require('tap').test; +var p = require('path').resolve(__dirname, 'files'); + +process.chdir(__dirname) + +// Make sure to reserve the stderr fd +process.stderr.write(''); + +var num = 4097; +var paths = new Array(num); + +test('make files', function (t) { + rimraf.sync(p); + mkdirp.sync(p); + + for (var i = 0; i < num; ++i) { + paths[i] = 'files/file-' + i; + fs.writeFileSync(paths[i], 'content'); + } + + t.end(); +}) + +test('read files', function (t) { + // now read them + var done = 0; + for (var i = 0; i < num; ++i) { + fs.readFile(paths[i], function(err, data) { + if (err) + throw err; + + ++done; + if (done === num) { + t.pass('success'); + t.end() + } + }); + } +}); + +test('cleanup', function (t) { + rimraf.sync(p); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/package.json new file mode 100644 index 0000000..48b1200 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.0 <2.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/package.json new file mode 100644 index 0000000..8653c5f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/fstream/package.json @@ -0,0 +1,41 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "fstream", + "description": "Advanced file system stream things", + "version": "0.1.31", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/fstream.git" + }, + "main": "fstream.js", + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "graceful-fs": "~3.0.2", + "inherits": "~2.0.0", + "mkdirp": "0.5", + "rimraf": "2" + }, + "devDependencies": { + "tap": "" + }, + "scripts": { + "test": "tap examples/*.js" + }, + "license": "BSD", + "readme": "Like FS streams, but with stat on them, and supporting directories and\nsymbolic links, as well as normal files. Also, you can use this to set\nthe stats on a file, even if you don't change its contents, or to create\na symlink, etc.\n\nSo, for example, you can \"write\" a directory, and it'll call `mkdir`. You\ncan specify a uid and gid, and it'll call `chown`. You can specify a\n`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink\nand provide a `linkpath` and it'll call `symlink`.\n\nNote that it won't automatically resolve symbolic links. So, if you\ncall `fstream.Reader('/some/symlink')` then you'll get an object\nthat stats and then ends immediately (since it has no data). To follow\nsymbolic links, do this: `fstream.Reader({path:'/some/symlink', follow:\ntrue })`.\n\nThere are various checks to make sure that the bytes emitted are the\nsame as the intended size, if the size is set.\n\n## Examples\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n })\n .write(\"hello\\n\")\n .end()\n```\n\nThis will create the directories if they're missing, and then write\n`hello\\n` into the file, chmod it to 0755, and assert that 6 bytes have\nbeen written when it's done.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n , flags: \"a\"\n })\n .write(\"hello\\n\")\n .end()\n```\n\nYou can pass flags in, if you want to append to a file.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/symlink\"\n , linkpath: \"./file\"\n , SymbolicLink: true\n , mode: \"0755\" // octal strings supported\n })\n .end()\n```\n\nIf isSymbolicLink is a function, it'll be called, and if it returns\ntrue, then it'll treat it as a symlink. If it's not a function, then\nany truish value will make a symlink, or you can set `type:\n'SymbolicLink'`, which does the same thing.\n\nNote that the linkpath is relative to the symbolic link location, not\nthe parent dir or cwd.\n\n```javascript\nfstream\n .Reader(\"path/to/dir\")\n .pipe(fstream.Writer(\"path/to/other/dir\"))\n```\n\nThis will do like `cp -Rp path/to/dir path/to/other/dir`. If the other\ndir exists and isn't a directory, then it'll emit an error. It'll also\nset the uid, gid, mode, etc. to be identical. In this way, it's more\nlike `rsync -a` than simply a copy.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/fstream/issues" + }, + "homepage": "https://github.com/isaacs/fstream#readme", + "_id": "fstream@0.1.31", + "_shasum": "7337f058fbbbbefa8c9f561a28cab0849202c988", + "_resolved": "https://registry.npmjs.org/fstream/-/fstream-0.1.31.tgz", + "_from": "fstream@>=0.1.22 <0.2.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/.npmignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..01af3d6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/README.md @@ -0,0 +1,33 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over fs module + +graceful-fs: + +* keeps track of how many file descriptors are open, and by default + limits this to 1024. Any further requests to open a file are put in a + queue until new slots become available. If 1024 turns out to be too + much, it decreases the limit further. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## Configuration + +The maximum number of open file descriptors that graceful-fs manages may +be adjusted by setting `fs.MAX_OPEN` to a different number. The default +is 1024. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/graceful-fs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..ca91152 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,442 @@ +// this keeps a queue of opened file descriptors, and will make +// fs operations wait until some have closed before trying to open more. + +var fs = exports = module.exports = {} +fs._originalFs = require("fs") + +Object.getOwnPropertyNames(fs._originalFs).forEach(function(prop) { + var desc = Object.getOwnPropertyDescriptor(fs._originalFs, prop) + Object.defineProperty(fs, prop, desc) +}) + +var queue = [] + , constants = require("constants") + +fs._curOpen = 0 + +fs.MIN_MAX_OPEN = 64 +fs.MAX_OPEN = 1024 + +// prevent EMFILE errors +function OpenReq (path, flags, mode, cb) { + this.path = path + this.flags = flags + this.mode = mode + this.cb = cb +} + +function noop () {} + +fs.open = gracefulOpen + +function gracefulOpen (path, flags, mode, cb) { + if (typeof mode === "function") cb = mode, mode = null + if (typeof cb !== "function") cb = noop + + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new OpenReq(path, flags, mode, cb)) + setTimeout(flush) + return + } + open(path, flags, mode, function (er, fd) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + // that was too many. reduce max, get back in queue. + // this should only happen once in a great while, and only + // if the ulimit -n is set lower than 1024. + fs.MAX_OPEN = fs._curOpen - 1 + return fs.open(path, flags, mode, cb) + } + cb(er, fd) + }) +} + +function open (path, flags, mode, cb) { + cb = cb || noop + fs._curOpen ++ + fs._originalFs.open.call(fs, path, flags, mode, function (er, fd) { + if (er) onclose() + cb(er, fd) + }) +} + +fs.openSync = function (path, flags, mode) { + var ret + ret = fs._originalFs.openSync.call(fs, path, flags, mode) + fs._curOpen ++ + return ret +} + +function onclose () { + fs._curOpen -- + flush() +} + +function flush () { + while (fs._curOpen < fs.MAX_OPEN) { + var req = queue.shift() + if (!req) return + switch (req.constructor.name) { + case 'OpenReq': + open(req.path, req.flags || "r", req.mode || 0777, req.cb) + break + case 'ReaddirReq': + readdir(req.path, req.cb) + break + case 'ReadFileReq': + readFile(req.path, req.options, req.cb) + break + case 'WriteFileReq': + writeFile(req.path, req.data, req.options, req.cb) + break + default: + throw new Error('Unknown req type: ' + req.constructor.name) + } + } +} + +fs.close = function (fd, cb) { + cb = cb || noop + fs._originalFs.close.call(fs, fd, function (er) { + onclose() + cb(er) + }) +} + +fs.closeSync = function (fd) { + try { + return fs._originalFs.closeSync.call(fs, fd) + } finally { + onclose() + } +} + + +// readdir takes a fd as well. +// however, the sync version closes it right away, so +// there's no need to wrap. +// It would be nice to catch when it throws an EMFILE, +// but that's relatively rare anyway. + +fs.readdir = gracefulReaddir + +function gracefulReaddir (path, cb) { + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new ReaddirReq(path, cb)) + setTimeout(flush) + return + } + + readdir(path, function (er, files) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + fs.MAX_OPEN = fs._curOpen - 1 + return fs.readdir(path, cb) + } + cb(er, files) + }) +} + +function readdir (path, cb) { + cb = cb || noop + fs._curOpen ++ + fs._originalFs.readdir.call(fs, path, function (er, files) { + onclose() + cb(er, files) + }) +} + +function ReaddirReq (path, cb) { + this.path = path + this.cb = cb +} + + +fs.readFile = gracefulReadFile + +function gracefulReadFile(path, options, cb) { + if (typeof options === "function") cb = options, options = null + if (typeof cb !== "function") cb = noop + + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new ReadFileReq(path, options, cb)) + setTimeout(flush) + return + } + + readFile(path, options, function (er, data) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + fs.MAX_OPEN = fs._curOpen - 1 + return fs.readFile(path, options, cb) + } + cb(er, data) + }) +} + +function readFile (path, options, cb) { + cb = cb || noop + fs._curOpen ++ + fs._originalFs.readFile.call(fs, path, options, function (er, data) { + onclose() + cb(er, data) + }) +} + +function ReadFileReq (path, options, cb) { + this.path = path + this.options = options + this.cb = cb +} + + + + +fs.writeFile = gracefulWriteFile + +function gracefulWriteFile(path, data, options, cb) { + if (typeof options === "function") cb = options, options = null + if (typeof cb !== "function") cb = noop + + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new WriteFileReq(path, data, options, cb)) + setTimeout(flush) + return + } + + writeFile(path, data, options, function (er) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + fs.MAX_OPEN = fs._curOpen - 1 + return fs.writeFile(path, data, options, cb) + } + cb(er) + }) +} + +function writeFile (path, data, options, cb) { + cb = cb || noop + fs._curOpen ++ + fs._originalFs.writeFile.call(fs, path, data, options, function (er) { + onclose() + cb(er) + }) +} + +function WriteFileReq (path, data, options, cb) { + this.path = path + this.data = data + this.options = options + this.cb = cb +} + + +// (re-)implement some things that are known busted or missing. + +var constants = require("constants") + +// lchmod, broken prior to 0.6.2 +// back-port the fix here. +if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + fs.lchmod = function (path, mode, callback) { + callback = callback || noop + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var err, err2 + try { + var ret = fs.fchmodSync(fd, mode) + } catch (er) { + err = er + } + try { + fs.closeSync(fd) + } catch (er) { + err2 = er + } + if (err || err2) throw (err || err2) + return ret + } +} + + +// lutimes implementation, or no-op +if (!fs.lutimes) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + cb = cb || noop + if (er) return cb(er) + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + return cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + , err + , err2 + , ret + + try { + var ret = fs.futimesSync(fd, at, mt) + } catch (er) { + err = er + } + try { + fs.closeSync(fd) + } catch (er) { + err2 = er + } + if (err || err2) throw (err || err2) + return ret + } + + } else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) { + // maybe utimensat will be bound soonish? + fs.lutimes = function (path, at, mt, cb) { + fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb) + } + + fs.lutimesSync = function (path, at, mt) { + return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW) + } + + } else { + fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) } + fs.lutimesSync = function () {} + } +} + + +// https://github.com/isaacs/node-graceful-fs/issues/4 +// Chown should not fail on einval or eperm if non-root. + +fs.chown = chownFix(fs.chown) +fs.fchown = chownFix(fs.fchown) +fs.lchown = chownFix(fs.lchown) + +fs.chownSync = chownFixSync(fs.chownSync) +fs.fchownSync = chownFixSync(fs.fchownSync) +fs.lchownSync = chownFixSync(fs.lchownSync) + +function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er, res) { + if (chownErOk(er)) er = null + cb(er, res) + }) + } +} + +function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } +} + +function chownErOk (er) { + // if there's no getuid, or if getuid() is something other than 0, + // and the error is EINVAL or EPERM, then just ignore it. + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // When running as root, or if other types of errors are encountered, + // then it's strict. + if (!er || (!process.getuid || process.getuid() !== 0) + && (er.code === "EINVAL" || er.code === "EPERM")) return true +} + + +// if lchmod/lchown do not exist, then make them no-ops +if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + process.nextTick(cb) + } + fs.lchmodSync = function () {} +} +if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + process.nextTick(cb) + } + fs.lchownSync = function () {} +} + + + +// on Windows, A/V software can lock the directory, causing this +// to fail with an EACCES or EPERM if the directory contains newly +// created files. Try again on failure, for up to 1 second. +if (process.platform === "win32") { + var rename_ = fs.rename + fs.rename = function rename (from, to, cb) { + var start = Date.now() + rename_(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 1000) { + return rename_(from, to, CB) + } + cb(er) + }) + } +} + + +// if read() returns EAGAIN, then just try it again. +var read = fs.read +fs.read = function (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return read.call(fs, fd, buffer, offset, length, position, callback) +} + +var readSync = fs.readSync +fs.readSync = function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..15ee4f6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/package.json @@ -0,0 +1,51 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "1.2.3", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-graceful-fs.git" + }, + "main": "graceful-fs.js", + "engines": { + "node": ">=0.4.0" + }, + "directories": { + "test": "test" + }, + "scripts": { + "test": "tap test/*.js" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "BSD", + "readme": "# graceful-fs\n\ngraceful-fs functions as a drop-in replacement for the fs module,\nmaking various improvements.\n\nThe improvements are meant to normalize behavior across different\nplatforms and environments, and to make filesystem access more\nresilient to errors.\n\n## Improvements over fs module\n\ngraceful-fs:\n\n* keeps track of how many file descriptors are open, and by default\n limits this to 1024. Any further requests to open a file are put in a\n queue until new slots become available. If 1024 turns out to be too\n much, it decreases the limit further.\n* fixes `lchmod` for Node versions prior to 0.6.2.\n* implements `fs.lutimes` if possible. Otherwise it becomes a noop.\n* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or\n `lchown` if the user isn't root.\n* makes `lchmod` and `lchown` become noops, if not available.\n* retries reading a file if `read` results in EAGAIN error.\n\nOn Windows, it retries renaming a file for up to one second if `EACCESS`\nor `EPERM` error occurs, likely because antivirus software has locked\nthe directory.\n\n## Configuration\n\nThe maximum number of open file descriptors that graceful-fs manages may\nbe adjusted by setting `fs.MAX_OPEN` to a different number. The default\nis 1024.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/node-graceful-fs/issues" + }, + "homepage": "https://github.com/isaacs/node-graceful-fs#readme", + "_id": "graceful-fs@1.2.3", + "_shasum": "15a4806a57547cb2d2dbf27f42e89a8c3451b364", + "_resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-1.2.3.tgz", + "_from": "graceful-fs@>=1.2.0 <1.3.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/open.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/open.js new file mode 100644 index 0000000..930d532 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/open.js @@ -0,0 +1,46 @@ +var test = require('tap').test +var fs = require('../graceful-fs.js') + +test('graceful fs is not fs', function (t) { + t.notEqual(fs, require('fs')) + t.end() +}) + +test('open an existing file works', function (t) { + var start = fs._curOpen + var fd = fs.openSync(__filename, 'r') + t.equal(fs._curOpen, start + 1) + fs.closeSync(fd) + t.equal(fs._curOpen, start) + fs.open(__filename, 'r', function (er, fd) { + if (er) throw er + t.equal(fs._curOpen, start + 1) + fs.close(fd, function (er) { + if (er) throw er + t.equal(fs._curOpen, start) + t.end() + }) + }) +}) + +test('open a non-existing file throws', function (t) { + var start = fs._curOpen + var er + try { + var fd = fs.openSync('this file does not exist', 'r') + } catch (x) { + er = x + } + t.ok(er, 'should throw') + t.notOk(fd, 'should not get an fd') + t.equal(er.code, 'ENOENT') + t.equal(fs._curOpen, start) + + fs.open('neither does this file', 'r', function (er, fd) { + t.ok(er, 'should throw') + t.notOk(fd, 'should not get an fd') + t.equal(er.code, 'ENOENT') + t.equal(fs._curOpen, start) + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/ulimit.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/ulimit.js new file mode 100644 index 0000000..8d0882d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/graceful-fs/test/ulimit.js @@ -0,0 +1,158 @@ +var test = require('tap').test + +// simulated ulimit +// this is like graceful-fs, but in reverse +var fs_ = require('fs') +var fs = require('../graceful-fs.js') +var files = fs.readdirSync(__dirname) + +// Ok, no more actual file reading! + +var fds = 0 +var nextFd = 60 +var limit = 8 +fs_.open = function (path, flags, mode, cb) { + process.nextTick(function() { + ++fds + if (fds >= limit) { + --fds + var er = new Error('EMFILE Curses!') + er.code = 'EMFILE' + er.path = path + return cb(er) + } else { + cb(null, nextFd++) + } + }) +} + +fs_.openSync = function (path, flags, mode) { + if (fds >= limit) { + var er = new Error('EMFILE Curses!') + er.code = 'EMFILE' + er.path = path + throw er + } else { + ++fds + return nextFd++ + } +} + +fs_.close = function (fd, cb) { + process.nextTick(function () { + --fds + cb() + }) +} + +fs_.closeSync = function (fd) { + --fds +} + +fs_.readdir = function (path, cb) { + process.nextTick(function() { + if (fds >= limit) { + var er = new Error('EMFILE Curses!') + er.code = 'EMFILE' + er.path = path + return cb(er) + } else { + ++fds + process.nextTick(function () { + --fds + cb(null, [__filename, "some-other-file.js"]) + }) + } + }) +} + +fs_.readdirSync = function (path) { + if (fds >= limit) { + var er = new Error('EMFILE Curses!') + er.code = 'EMFILE' + er.path = path + throw er + } else { + return [__filename, "some-other-file.js"] + } +} + + +test('open emfile autoreduce', function (t) { + fs.MIN_MAX_OPEN = 4 + t.equal(fs.MAX_OPEN, 1024) + + var max = 12 + for (var i = 0; i < max; i++) { + fs.open(__filename, 'r', next(i)) + } + + var phase = 0 + + var expect = + [ [ 0, 60, null, 1024, 4, 12, 1 ], + [ 1, 61, null, 1024, 4, 12, 2 ], + [ 2, 62, null, 1024, 4, 12, 3 ], + [ 3, 63, null, 1024, 4, 12, 4 ], + [ 4, 64, null, 1024, 4, 12, 5 ], + [ 5, 65, null, 1024, 4, 12, 6 ], + [ 6, 66, null, 1024, 4, 12, 7 ], + [ 7, 67, null, 6, 4, 5, 1 ], + [ 8, 68, null, 6, 4, 5, 2 ], + [ 9, 69, null, 6, 4, 5, 3 ], + [ 10, 70, null, 6, 4, 5, 4 ], + [ 11, 71, null, 6, 4, 5, 5 ] ] + + var actual = [] + + function next (i) { return function (er, fd) { + if (er) + throw er + actual.push([i, fd, er, fs.MAX_OPEN, fs.MIN_MAX_OPEN, fs._curOpen, fds]) + + if (i === max - 1) { + t.same(actual, expect) + t.ok(fs.MAX_OPEN < limit) + t.end() + } + + fs.close(fd) + } } +}) + +test('readdir emfile autoreduce', function (t) { + fs.MAX_OPEN = 1024 + var max = 12 + for (var i = 0; i < max; i ++) { + fs.readdir(__dirname, next(i)) + } + + var expect = + [ [0,[__filename,"some-other-file.js"],null,7,4,7,7], + [1,[__filename,"some-other-file.js"],null,7,4,7,6], + [2,[__filename,"some-other-file.js"],null,7,4,7,5], + [3,[__filename,"some-other-file.js"],null,7,4,7,4], + [4,[__filename,"some-other-file.js"],null,7,4,7,3], + [5,[__filename,"some-other-file.js"],null,7,4,6,2], + [6,[__filename,"some-other-file.js"],null,7,4,5,1], + [7,[__filename,"some-other-file.js"],null,7,4,4,0], + [8,[__filename,"some-other-file.js"],null,7,4,3,3], + [9,[__filename,"some-other-file.js"],null,7,4,2,2], + [10,[__filename,"some-other-file.js"],null,7,4,1,1], + [11,[__filename,"some-other-file.js"],null,7,4,0,0] ] + + var actual = [] + + function next (i) { return function (er, files) { + if (er) + throw er + var line = [i, files, er, fs.MAX_OPEN, fs.MIN_MAX_OPEN, fs._curOpen, fds ] + actual.push(line) + + if (i === max - 1) { + t.ok(fs.MAX_OPEN < limit) + t.same(actual, expect) + t.end() + } + } } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/README.md new file mode 100644 index 0000000..e833b83 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/README.md @@ -0,0 +1,33 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/once.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/once.js new file mode 100644 index 0000000..effc50a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/once.js @@ -0,0 +1,19 @@ +module.exports = once + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) +}) + +function once (fn) { + var called = false + return function () { + if (called) return + called = true + return fn.apply(this, arguments) + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/package.json new file mode 100644 index 0000000..e0ea089 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/package.json @@ -0,0 +1,56 @@ +{ + "name": "once", + "version": "1.1.1", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "tap": "~0.3.0" + }, + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once.git" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "BSD", + "_id": "once@1.1.1", + "dist": { + "shasum": "9db574933ccb08c3a7614d154032c09ea6f339e7", + "tarball": "http://registry.npmjs.org/once/-/once-1.1.1.tgz" + }, + "_npmVersion": "1.1.48", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "_shasum": "9db574933ccb08c3a7614d154032c09ea6f339e7", + "_resolved": "https://registry.npmjs.org/once/-/once-1.1.1.tgz", + "_from": "once@>=1.1.1 <1.2.0", + "bugs": { + "url": "https://github.com/isaacs/once/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/once#readme" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/test/once.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/test/once.js new file mode 100644 index 0000000..f0291a4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/once/test/once.js @@ -0,0 +1,18 @@ +var test = require('tap').test +var once = require('../once.js') + +test('once', function (t) { + var f = 0 + var foo = once(function (g) { + t.equal(f, 0) + f ++ + return f + g + this + }) + for (var i = 0; i < 1E3; i++) { + t.same(f, i === 0 ? 0 : 1) + var g = foo.call(1, 1) + t.same(g, i === 0 ? 3 : undefined) + t.same(f, 1) + } + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/README.md new file mode 100644 index 0000000..3fb3e80 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/duplex.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; + + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; + + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} + +function emitReadable_(stream) { + stream.emit('readable'); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } + + function onend() { + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); + + state.flowing = true; + process.nextTick(function() { + flow(src); + }); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; +} + +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } + + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } + + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; + + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } + + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; +} + +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; + +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; + +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; + + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } + + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + process.nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + cb(er); + }); + else + cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..9074e8e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..b673333 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,37 @@ +{ + "name": "core-util-is", + "version": "1.0.1", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.1", + "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz", + "_from": "core-util-is@>=1.0.0 <1.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/util.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/util.js new file mode 100644 index 0000000..007fa10 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/core-util-is/util.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && objectToString(e) === '[object Error]'; +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..933382a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.1 <2.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/build/build.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/component.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..fb1eb37 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,38 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies 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 THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@0.0.1", + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "_from": "isarray@0.0.1" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..ee70702 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "readme": "**string_decoder.js** (`require('string_decoder')`) from Node.js core\n\nCopyright Joyent, Inc. and other Node contributors. See LICENCE file for details.\n\nVersion numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**\n\nThe *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_from": "string_decoder@>=0.10.0 <0.11.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/package.json new file mode 100644 index 0000000..9d78e5d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/package.json @@ -0,0 +1,46 @@ +{ + "name": "readable-stream", + "version": "1.0.33", + "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "devDependencies": { + "tap": "~0.2.6" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "readme": "# readable-stream\n\n***Node-core streams for userland***\n\n[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)\n[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)\n\nThis package is a mirror of the Streams2 and Streams3 implementations in Node-core.\n\nIf you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *\"stream\"* module in Node-core.\n\n**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12.\n\n**readable-stream** uses proper patch-level versioning so if you pin to `\"~1.0.0\"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `\"~1.1.0\"`\n\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream#readme", + "_id": "readable-stream@1.0.33", + "_shasum": "3a360dd66c1b1d7fd4705389860eda1d0f61126c", + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz", + "_from": "readable-stream@>=1.0.2 <1.1.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/passthrough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/readable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..8b5337b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/readable.js @@ -0,0 +1,8 @@ +var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/transform.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/writable.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/AUTHORS b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/AUTHORS new file mode 100644 index 0000000..247b754 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/AUTHORS @@ -0,0 +1,6 @@ +# Authors sorted by whether or not they're me. +Isaac Z. Schlueter (http://blog.izs.me) +Wayne Larsen (http://github.com/wvl) +ritch +Marcel Laverdet +Yosef Dinerstein diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/LICENSE new file mode 100644 index 0000000..05a4010 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/LICENSE @@ -0,0 +1,23 @@ +Copyright 2009, 2010, 2011 Isaac Z. Schlueter. +All rights reserved. + +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/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/README.md new file mode 100644 index 0000000..cd123b6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/README.md @@ -0,0 +1,30 @@ +`rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, callback)` + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of + `opts.maxBusyTries` times before giving up. +* `ENOENT` - If the file doesn't exist, rimraf will return + successfully, since your desired outcome is already the case. + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. + +## CLI + +If installed with `npm install rimraf -g` it can be used as a global +command `rimraf ` which is useful for cross platform support. + +## mkdirp + +If you need to create a directory recursively, check out +[mkdirp](https://github.com/substack/node-mkdirp). diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/bin.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/bin.js new file mode 100755 index 0000000..29bfa8a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/bin.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var rimraf = require('./') + +var help = false +var dashdash = false +var args = process.argv.slice(2).filter(function(arg) { + if (dashdash) + return !!arg + else if (arg === '--') + dashdash = true + else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/)) + help = true + else + return !!arg +}); + +if (help || args.length === 0) { + // If they didn't ask for help, then this is not a "success" + var log = help ? console.log : console.error + log('Usage: rimraf ') + log('') + log(' Deletes all files and folders at "path" recursively.') + log('') + log('Options:') + log('') + log(' -h, --help Display this usage info') + process.exit(help ? 0 : 1) +} else { + args.forEach(function(arg) { + rimraf.sync(arg) + }) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/package.json new file mode 100644 index 0000000..deea055 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/package.json @@ -0,0 +1,58 @@ +{ + "name": "rimraf", + "version": "2.2.8", + "main": "rimraf.js", + "description": "A deep deletion module for node (like `rm -rf`)", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": { + "type": "MIT", + "url": "https://github.com/isaacs/rimraf/raw/master/LICENSE" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/rimraf.git" + }, + "scripts": { + "test": "cd test && bash run.sh" + }, + "bin": { + "rimraf": "./bin.js" + }, + "contributors": [ + { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + { + "name": "Wayne Larsen", + "email": "wayne@larsen.st", + "url": "http://github.com/wvl" + }, + { + "name": "ritch", + "email": "skawful@gmail.com" + }, + { + "name": "Marcel Laverdet" + }, + { + "name": "Yosef Dinerstein", + "email": "yosefd@microsoft.com" + } + ], + "readme": "`rm -rf` for node.\n\nInstall with `npm install rimraf`, or just drop rimraf.js somewhere.\n\n## API\n\n`rimraf(f, callback)`\n\nThe callback will be called with an error if there is one. Certain\nerrors are handled for you:\n\n* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of\n `opts.maxBusyTries` times before giving up.\n* `ENOENT` - If the file doesn't exist, rimraf will return\n successfully, since your desired outcome is already the case.\n\n## rimraf.sync\n\nIt can remove stuff synchronously, too. But that's not so good. Use\nthe async API. It's better.\n\n## CLI\n\nIf installed with `npm install rimraf -g` it can be used as a global\ncommand `rimraf ` which is useful for cross platform support.\n\n## mkdirp\n\nIf you need to create a directory recursively, check out\n[mkdirp](https://github.com/substack/node-mkdirp).\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/rimraf/issues" + }, + "homepage": "https://github.com/isaacs/rimraf#readme", + "_id": "rimraf@2.2.8", + "_shasum": "e439be2aaee327321952730f99a8929e4fc50582", + "_resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.2.8.tgz", + "_from": "rimraf@>=2.2.0 <2.3.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/rimraf.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/rimraf.js new file mode 100644 index 0000000..eb96c46 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/rimraf.js @@ -0,0 +1,248 @@ +module.exports = rimraf +rimraf.sync = rimrafSync + +var assert = require("assert") +var path = require("path") +var fs = require("fs") + +// for EMFILE handling +var timeout = 0 +exports.EMFILE_MAX = 1000 +exports.BUSYTRIES_MAX = 3 + +var isWindows = (process.platform === "win32") + +function defaults (options) { + var methods = [ + 'unlink', + 'chmod', + 'stat', + 'rmdir', + 'readdir' + ] + methods.forEach(function(m) { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) +} + +function rimraf (p, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + assert(p) + assert(options) + assert(typeof cb === 'function') + + defaults(options) + + if (!cb) throw new Error("No callback passed to rimraf()") + + var busyTries = 0 + rimraf_(p, options, function CB (er) { + if (er) { + if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") && + busyTries < exports.BUSYTRIES_MAX) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, options, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) { + return setTimeout(function () { + rimraf_(p, options, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + cb(er) + }) +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.unlink(p, function (er) { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) + + options.chmod(p, 666, function (er2) { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, function(er3, stats) { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} + +function fixWinEPERMSync (p, options, er) { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) + + try { + options.chmodSync(p, 666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } + + try { + var stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } + + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} + +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} + +function rmkids(p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return options.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), options, function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + options = options || {} + defaults(options) + + assert(p) + assert(options) + + try { + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er + rmdirSync(p, options, er) + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f), options) + }) + options.rmdirSync(p, options) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/run.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/run.sh new file mode 100644 index 0000000..653ff9b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/run.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -e +code=0 +for i in test-*.js; do + echo -n $i ... + bash setup.sh + node $i + if [ -d target ]; then + echo "fail" + code=1 + else + echo "pass" + fi +done +rm -rf target +exit $code diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/setup.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/setup.sh new file mode 100644 index 0000000..2602e63 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/setup.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +set -e + +files=10 +folders=2 +depth=4 +target="$PWD/target" + +rm -rf target + +fill () { + local depth=$1 + local files=$2 + local folders=$3 + local target=$4 + + if ! [ -d $target ]; then + mkdir -p $target + fi + + local f + + f=$files + while [ $f -gt 0 ]; do + touch "$target/f-$depth-$f" + let f-- + done + + let depth-- + + if [ $depth -le 0 ]; then + return 0 + fi + + f=$folders + while [ $f -gt 0 ]; do + mkdir "$target/folder-$depth-$f" + fill $depth $files $folders "$target/d-$depth-$f" + let f-- + done +} + +fill $depth $files $folders $target + +# sanity assert +[ -d $target ] diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-async.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-async.js new file mode 100644 index 0000000..9c2e0b7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-async.js @@ -0,0 +1,5 @@ +var rimraf = require("../rimraf") + , path = require("path") +rimraf(path.join(__dirname, "target"), function (er) { + if (er) throw er +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-sync.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-sync.js new file mode 100644 index 0000000..eb71f10 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/rimraf/test/test-sync.js @@ -0,0 +1,3 @@ +var rimraf = require("../rimraf") + , path = require("path") +rimraf.sync(path.join(__dirname, "target")) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.npmignore new file mode 100644 index 0000000..c167ad5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.npmignore @@ -0,0 +1,5 @@ +.*.swp +node_modules +examples/extract/ +test/tmp/ +test/fixtures/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.travis.yml new file mode 100644 index 0000000..2d26206 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.6 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/LICENCE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/LICENCE new file mode 100644 index 0000000..74489e2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/README.md new file mode 100644 index 0000000..424a278 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/README.md @@ -0,0 +1,48 @@ +# node-tar + +Tar for Node.js. + +[![NPM](https://nodei.co/npm/tar.png)](https://nodei.co/npm/tar/) + +## API + +See `examples/` for usage examples. + +### var tar = require('tar') + +Returns an object with `.Pack`, `.Extract` and `.Parse` methods. + +### tar.Pack([properties]) + +Returns a through stream. Use +[fstream](https://npmjs.org/package/fstream) to write files into the +pack stream and you will receive tar archive data from the pack +stream. + +This only works with directories, it does not work with individual files. + +The optional `properties` object are used to set properties in the tar +'Global Extended Header'. + +### tar.Extract([options]) + +Returns a through stream. Write tar data to the stream and the files +in the tarball will be extracted onto the filesystem. + +`options` can be: + +```js +{ + path: '/path/to/extract/tar/into', + strip: 0, // how many path segments to strip from the root when extracting +} +``` + +`options` also get passed to the `fstream.Writer` instance that `tar` +uses internally. + +### tar.Parse() + +Returns a writable stream. Write tar data to it and it will emit +`entry` events for each entry parsed from the tarball. This is used by +`tar.Extract`. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/extracter.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/extracter.js new file mode 100644 index 0000000..e150abf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/extracter.js @@ -0,0 +1,11 @@ +var tar = require("../tar.js") + , fs = require("fs") + +fs.createReadStream(__dirname + "/../test/fixtures/c.tar") + .pipe(tar.Extract({ path: __dirname + "/extract" })) + .on("error", function (er) { + console.error("error here") + }) + .on("end", function () { + console.error("done") + }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/packer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/packer.js new file mode 100644 index 0000000..ebe3892 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/packer.js @@ -0,0 +1,10 @@ +var tar = require("../tar.js") + , fstream = require("fstream") + , fs = require("fs") + +var dir_destination = fs.createWriteStream('dir.tar') + +// This must be a "directory" +fstream.Reader({ path: __dirname, type: "Directory" }) + .pipe(tar.Pack({ noProprietary: true })) + .pipe(dir_destination) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/reader.js new file mode 100644 index 0000000..39f3f08 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/examples/reader.js @@ -0,0 +1,36 @@ +var tar = require("../tar.js") + , fs = require("fs") + +fs.createReadStream(__dirname + "/../test/fixtures/c.tar") + .pipe(tar.Parse()) + .on("extendedHeader", function (e) { + console.error("extended pax header", e.props) + e.on("end", function () { + console.error("extended pax fields:", e.fields) + }) + }) + .on("ignoredEntry", function (e) { + console.error("ignoredEntry?!?", e.props) + }) + .on("longLinkpath", function (e) { + console.error("longLinkpath entry", e.props) + e.on("end", function () { + console.error("value=%j", e.body.toString()) + }) + }) + .on("longPath", function (e) { + console.error("longPath entry", e.props) + e.on("end", function () { + console.error("value=%j", e.body.toString()) + }) + }) + .on("entry", function (e) { + console.error("entry", e.props) + e.on("data", function (c) { + console.error(" >>>" + c.toString().replace(/\n/g, "\\n")) + }) + e.on("end", function () { + console.error(" << 0 + return !this._needDrain +} + +EntryWriter.prototype.end = function (c) { + // console.error(".. ew end") + if (c) this._buffer.push(c) + this._buffer.push(EOF) + this._ended = true + this._process() + this._needDrain = this._buffer.length > 0 +} + +EntryWriter.prototype.pause = function () { + // console.error(".. ew pause") + this._paused = true + this.emit("pause") +} + +EntryWriter.prototype.resume = function () { + // console.error(".. ew resume") + this._paused = false + this.emit("resume") + this._process() +} + +EntryWriter.prototype.add = function (entry) { + // console.error(".. ew add") + if (!this.parent) return this.emit("error", new Error("no parent")) + + // make sure that the _header and such is emitted, and clear out + // the _currentEntry link on the parent. + if (!this._ended) this.end() + + return this.parent.add(entry) +} + +EntryWriter.prototype._header = function () { + // console.error(".. ew header") + if (this._didHeader) return + this._didHeader = true + + var headerBlock = TarHeader.encode(this.props) + + if (this.props.needExtended && !this._meta) { + var me = this + + ExtendedHeaderWriter = ExtendedHeaderWriter || + require("./extended-header-writer.js") + + ExtendedHeaderWriter(this.props) + .on("data", function (c) { + me.emit("data", c) + }) + .on("error", function (er) { + me.emit("error", er) + }) + .end() + } + + // console.error(".. .. ew headerBlock emitting") + this.emit("data", headerBlock) + this.emit("header") +} + +EntryWriter.prototype._process = function () { + // console.error(".. .. ew process") + if (!this._didHeader && !this._meta) { + this._header() + } + + if (this._paused || this._processing) { + // console.error(".. .. .. paused=%j, processing=%j", this._paused, this._processing) + return + } + + this._processing = true + + var buf = this._buffer + for (var i = 0; i < buf.length; i ++) { + // console.error(".. .. .. i=%d", i) + + var c = buf[i] + + if (c === EOF) this._stream.end() + else this._stream.write(c) + + if (this._paused) { + // console.error(".. .. .. paused mid-emission") + this._processing = false + if (i < buf.length) { + this._needDrain = true + this._buffer = buf.slice(i + 1) + } + return + } + } + + // console.error(".. .. .. emitted") + this._buffer.length = 0 + this._processing = false + + // console.error(".. .. .. emitting drain") + this.emit("drain") +} + +EntryWriter.prototype.destroy = function () {} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/entry.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/entry.js new file mode 100644 index 0000000..4af5c41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/entry.js @@ -0,0 +1,213 @@ +// A passthrough read/write stream that sets its properties +// based on a header, extendedHeader, and globalHeader +// +// Can be either a file system object of some sort, or +// a pax/ustar metadata entry. + +module.exports = Entry + +var TarHeader = require("./header.js") + , tar = require("../tar") + , assert = require("assert").ok + , Stream = require("stream").Stream + , inherits = require("inherits") + , fstream = require("fstream").Abstract + +function Entry (header, extended, global) { + Stream.call(this) + this.readable = true + this.writable = true + + this._needDrain = false + this._paused = false + this._reading = false + this._ending = false + this._ended = false + this._remaining = 0 + this._queue = [] + this._index = 0 + this._queueLen = 0 + + this._read = this._read.bind(this) + + this.props = {} + this._header = header + this._extended = extended || {} + + // globals can change throughout the course of + // a file parse operation. Freeze it at its current state. + this._global = {} + var me = this + Object.keys(global || {}).forEach(function (g) { + me._global[g] = global[g] + }) + + this._setProps() +} + +inherits(Entry, Stream) + +Entry.prototype.write = function (c) { + if (this._ending) this.error("write() after end()", null, true) + if (this._remaining === 0) { + this.error("invalid bytes past eof") + } + + // often we'll get a bunch of \0 at the end of the last write, + // since chunks will always be 512 bytes when reading a tarball. + if (c.length > this._remaining) { + c = c.slice(0, this._remaining) + } + this._remaining -= c.length + + // put it on the stack. + var ql = this._queueLen + this._queue.push(c) + this._queueLen ++ + + this._read() + + // either paused, or buffered + if (this._paused || ql > 0) { + this._needDrain = true + return false + } + + return true +} + +Entry.prototype.end = function (c) { + if (c) this.write(c) + this._ending = true + this._read() +} + +Entry.prototype.pause = function () { + this._paused = true + this.emit("pause") +} + +Entry.prototype.resume = function () { + // console.error(" Tar Entry resume", this.path) + this.emit("resume") + this._paused = false + this._read() + return this._queueLen - this._index > 1 +} + + // This is bound to the instance +Entry.prototype._read = function () { + // console.error(" Tar Entry _read", this.path) + + if (this._paused || this._reading || this._ended) return + + // set this flag so that event handlers don't inadvertently + // get multiple _read() calls running. + this._reading = true + + // have any data to emit? + while (this._index < this._queueLen && !this._paused) { + var chunk = this._queue[this._index ++] + this.emit("data", chunk) + } + + // check if we're drained + if (this._index >= this._queueLen) { + this._queue.length = this._queueLen = this._index = 0 + if (this._needDrain) { + this._needDrain = false + this.emit("drain") + } + if (this._ending) { + this._ended = true + this.emit("end") + } + } + + // if the queue gets too big, then pluck off whatever we can. + // this should be fairly rare. + var mql = this._maxQueueLen + if (this._queueLen > mql && this._index > 0) { + mql = Math.min(this._index, mql) + this._index -= mql + this._queueLen -= mql + this._queue = this._queue.slice(mql) + } + + this._reading = false +} + +Entry.prototype._setProps = function () { + // props = extended->global->header->{} + var header = this._header + , extended = this._extended + , global = this._global + , props = this.props + + // first get the values from the normal header. + var fields = tar.fields + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = header[field] + if (typeof val !== "undefined") props[field] = val + } + + // next, the global header for this file. + // numeric values, etc, will have already been parsed. + ;[global, extended].forEach(function (p) { + Object.keys(p).forEach(function (f) { + if (typeof p[f] !== "undefined") props[f] = p[f] + }) + }) + + // no nulls allowed in path or linkpath + ;["path", "linkpath"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = props[p].split("\0")[0] + } + }) + + + // set date fields to be a proper date + ;["mtime", "ctime", "atime"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = new Date(props[p] * 1000) + } + }) + + // set the type so that we know what kind of file to create + var type + switch (tar.types[props.type]) { + case "OldFile": + case "ContiguousFile": + type = "File" + break + + case "GNUDumpDir": + type = "Directory" + break + + case undefined: + type = "Unknown" + break + + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + default: + type = tar.types[props.type] + } + + this.type = type + this.path = props.path + this.size = props.size + + // size is special, since it signals when the file needs to end. + this._remaining = props.size +} + +Entry.prototype.warn = fstream.warn +Entry.prototype.error = fstream.error diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header-writer.js new file mode 100644 index 0000000..1728c45 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header-writer.js @@ -0,0 +1,191 @@ + +module.exports = ExtendedHeaderWriter + +var inherits = require("inherits") + , EntryWriter = require("./entry-writer.js") + +inherits(ExtendedHeaderWriter, EntryWriter) + +var tar = require("../tar.js") + , path = require("path") + , TarHeader = require("./header.js") + +// props is the props of the thing we need to write an +// extended header for. +// Don't be shy with it. Just encode everything. +function ExtendedHeaderWriter (props) { + // console.error(">> ehw ctor") + var me = this + + if (!(me instanceof ExtendedHeaderWriter)) { + return new ExtendedHeaderWriter(props) + } + + me.fields = props + + var p = + { path : ("PaxHeader" + path.join("/", props.path || "")) + .replace(/\\/g, "/").substr(0, 100) + , mode : props.mode || 0666 + , uid : props.uid || 0 + , gid : props.gid || 0 + , size : 0 // will be set later + , mtime : props.mtime || Date.now() / 1000 + , type : "x" + , linkpath : "" + , ustar : "ustar\0" + , ustarver : "00" + , uname : props.uname || "" + , gname : props.gname || "" + , devmaj : props.devmaj || 0 + , devmin : props.devmin || 0 + } + + + EntryWriter.call(me, p) + // console.error(">> ehw props", me.props) + me.props = p + + me._meta = true +} + +ExtendedHeaderWriter.prototype.end = function () { + // console.error(">> ehw end") + var me = this + + if (me._ended) return + me._ended = true + + me._encodeFields() + + if (me.props.size === 0) { + // nothing to write! + me._ready = true + me._stream.end() + return + } + + me._stream.write(TarHeader.encode(me.props)) + me.body.forEach(function (l) { + me._stream.write(l) + }) + me._ready = true + + // console.error(">> ehw _process calling end()", me.props) + this._stream.end() +} + +ExtendedHeaderWriter.prototype._encodeFields = function () { + // console.error(">> ehw _encodeFields") + this.body = [] + if (this.fields.prefix) { + this.fields.path = this.fields.prefix + "/" + this.fields.path + this.fields.prefix = "" + } + encodeFields(this.fields, "", this.body, this.fields.noProprietary) + var me = this + this.body.forEach(function (l) { + me.props.size += l.length + }) +} + +function encodeFields (fields, prefix, body, nop) { + // console.error(">> >> ehw encodeFields") + // "%d %s=%s\n", , , + // The length is a decimal number, and includes itself and the \n + // Numeric values are decimal strings. + + Object.keys(fields).forEach(function (k) { + var val = fields[k] + , numeric = tar.numeric[k] + + if (prefix) k = prefix + "." + k + + // already including NODETAR.type, don't need File=true also + if (k === fields.type && val === true) return + + switch (k) { + // don't include anything that's always handled just fine + // in the normal header, or only meaningful in the context + // of nodetar + case "mode": + case "cksum": + case "ustar": + case "ustarver": + case "prefix": + case "basename": + case "dirname": + case "needExtended": + case "block": + case "filter": + return + + case "rdev": + if (val === 0) return + break + + case "nlink": + case "dev": // Truly a hero among men, Creator of Star! + case "ino": // Speak his name with reverent awe! It is: + k = "SCHILY." + k + break + + default: break + } + + if (val && typeof val === "object" && + !Buffer.isBuffer(val)) encodeFields(val, k, body, nop) + else if (val === null || val === undefined) return + else body.push.apply(body, encodeField(k, val, nop)) + }) + + return body +} + +function encodeField (k, v, nop) { + // lowercase keys must be valid, otherwise prefix with + // "NODETAR." + if (k.charAt(0) === k.charAt(0).toLowerCase()) { + var m = k.split(".")[0] + if (!tar.knownExtended[m]) k = "NODETAR." + k + } + + // no proprietary + if (nop && k.charAt(0) !== k.charAt(0).toLowerCase()) { + return [] + } + + if (typeof val === "number") val = val.toString(10) + + var s = new Buffer(" " + k + "=" + v + "\n") + , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1 + + // console.error("1 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + // if adding that many digits will make it go over that length, + // then add one to it. For example, if the string is: + // " foo=bar\n" + // then that's 9 characters. With the "9", that bumps the length + // up to 10. However, this is invalid: + // "10 foo=bar\n" + // but, since that's actually 11 characters, since 10 adds another + // character to the length, and the length includes the number + // itself. In that case, just bump it up again. + if (s.length + digits >= Math.pow(10, digits)) digits += 1 + // console.error("2 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + var len = digits + s.length + // console.error("3 s=%j digits=%j s.length=%d len=%d", s.toString(), digits, s.length, len) + var lenBuf = new Buffer("" + len) + if (lenBuf.length + s.length !== len) { + throw new Error("Bad length calculation\n"+ + "len="+len+"\n"+ + "lenBuf="+JSON.stringify(lenBuf.toString())+"\n"+ + "lenBuf.length="+lenBuf.length+"\n"+ + "digits="+digits+"\n"+ + "s="+JSON.stringify(s.toString())+"\n"+ + "s.length="+s.length) + } + + return [lenBuf, s] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header.js new file mode 100644 index 0000000..74f432c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header.js @@ -0,0 +1,140 @@ +// An Entry consisting of: +// +// "%d %s=%s\n", , , +// +// The length is a decimal number, and includes itself and the \n +// \0 does not terminate anything. Only the length terminates the string. +// Numeric values are decimal strings. + +module.exports = ExtendedHeader + +var Entry = require("./entry.js") + , inherits = require("inherits") + , tar = require("../tar.js") + , numeric = tar.numeric + , keyTrans = { "SCHILY.dev": "dev" + , "SCHILY.ino": "ino" + , "SCHILY.nlink": "nlink" } + +function ExtendedHeader () { + Entry.apply(this, arguments) + this.on("data", this._parse) + this.fields = {} + this._position = 0 + this._fieldPos = 0 + this._state = SIZE + this._sizeBuf = [] + this._keyBuf = [] + this._valBuf = [] + this._size = -1 + this._key = "" +} + +inherits(ExtendedHeader, Entry) +ExtendedHeader.prototype._parse = parse + +var s = 0 + , states = ExtendedHeader.states = {} + , SIZE = states.SIZE = s++ + , KEY = states.KEY = s++ + , VAL = states.VAL = s++ + , ERR = states.ERR = s++ + +Object.keys(states).forEach(function (s) { + states[states[s]] = states[s] +}) + +states[s] = null + +// char code values for comparison +var _0 = "0".charCodeAt(0) + , _9 = "9".charCodeAt(0) + , point = ".".charCodeAt(0) + , a = "a".charCodeAt(0) + , Z = "Z".charCodeAt(0) + , a = "a".charCodeAt(0) + , z = "z".charCodeAt(0) + , space = " ".charCodeAt(0) + , eq = "=".charCodeAt(0) + , cr = "\n".charCodeAt(0) + +function parse (c) { + if (this._state === ERR) return + + for ( var i = 0, l = c.length + ; i < l + ; this._position++, this._fieldPos++, i++) { + // console.error("top of loop, size="+this._size) + + var b = c[i] + + if (this._size >= 0 && this._fieldPos > this._size) { + error(this, "field exceeds length="+this._size) + return + } + + switch (this._state) { + case ERR: return + + case SIZE: + // console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString()) + if (b === space) { + this._state = KEY + // this._fieldPos = this._sizeBuf.length + this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10) + this._sizeBuf.length = 0 + continue + } + if (b < _0 || b > _9) { + error(this, "expected [" + _0 + ".." + _9 + "], got " + b) + return + } + this._sizeBuf.push(b) + continue + + case KEY: + // can be any char except =, not > size. + if (b === eq) { + this._state = VAL + this._key = new Buffer(this._keyBuf).toString() + if (keyTrans[this._key]) this._key = keyTrans[this._key] + this._keyBuf.length = 0 + continue + } + this._keyBuf.push(b) + continue + + case VAL: + // field must end with cr + if (this._fieldPos === this._size - 1) { + // console.error("finished with "+this._key) + if (b !== cr) { + error(this, "expected \\n at end of field") + return + } + var val = new Buffer(this._valBuf).toString() + if (numeric[this._key]) { + val = parseFloat(val) + } + this.fields[this._key] = val + + this._valBuf.length = 0 + this._state = SIZE + this._size = -1 + this._fieldPos = -1 + continue + } + this._valBuf.push(b) + continue + } + } +} + +function error (me, msg) { + msg = "invalid header: " + msg + + "\nposition=" + me._position + + "\nfield position=" + me._fieldPos + + me.error(msg) + me.state = ERR +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extract.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extract.js new file mode 100644 index 0000000..c34a81e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extract.js @@ -0,0 +1,78 @@ +// give it a tarball and a path, and it'll dump the contents + +module.exports = Extract + +var tar = require("../tar.js") + , fstream = require("fstream") + , inherits = require("inherits") + , path = require("path") + +function Extract (opts) { + if (!(this instanceof Extract)) return new Extract(opts) + tar.Parse.apply(this) + + // have to dump into a directory + opts.type = "Directory" + opts.Directory = true + + if (typeof opts !== "object") { + opts = { path: opts } + } + + // better to drop in cwd? seems more standard. + opts.path = opts.path || path.resolve("node-tar-extract") + opts.type = "Directory" + opts.Directory = true + + // similar to --strip or --strip-components + opts.strip = +opts.strip + if (!opts.strip || opts.strip <= 0) opts.strip = 0 + + this._fst = fstream.Writer(opts) + + this.pause() + var me = this + + // Hardlinks in tarballs are relative to the root + // of the tarball. So, they need to be resolved against + // the target directory in order to be created properly. + me.on("entry", function (entry) { + // if there's a "strip" argument, then strip off that many + // path components. + if (opts.strip) { + var p = entry.path.split("/").slice(opts.strip).join("/") + entry.path = entry.props.path = p + if (entry.linkpath) { + var lp = entry.linkpath.split("/").slice(opts.strip).join("/") + entry.linkpath = entry.props.linkpath = lp + } + } + if (entry.type !== "Link") return + entry.linkpath = entry.props.linkpath = + path.join(opts.path, path.join("/", entry.props.linkpath)) + }) + + this._fst.on("ready", function () { + me.pipe(me._fst, { end: false }) + me.resume() + }) + + // this._fst.on("end", function () { + // console.error("\nEEEE Extract End", me._fst.path) + // }) + + this._fst.on("close", function () { + // console.error("\nEEEE Extract End", me._fst.path) + me.emit("end") + me.emit("close") + }) +} + +inherits(Extract, tar.Parse) + +Extract.prototype._streamEnd = function () { + var me = this + if (!me._ended) me.error("unexpected eof") + me._fst.end() + // my .end() is coming later. +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/global-header-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/global-header-writer.js new file mode 100644 index 0000000..0bfc7b8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/global-header-writer.js @@ -0,0 +1,14 @@ +module.exports = GlobalHeaderWriter + +var ExtendedHeaderWriter = require("./extended-header-writer.js") + , inherits = require("inherits") + +inherits(GlobalHeaderWriter, ExtendedHeaderWriter) + +function GlobalHeaderWriter (props) { + if (!(this instanceof GlobalHeaderWriter)) { + return new GlobalHeaderWriter(props) + } + ExtendedHeaderWriter.call(this, props) + this.props.type = "g" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/header.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/header.js new file mode 100644 index 0000000..05b237c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/header.js @@ -0,0 +1,385 @@ +// parse a 512-byte header block to a data object, or vice-versa +// If the data won't fit nicely in a simple header, then generate +// the appropriate extended header file, and return that. + +module.exports = TarHeader + +var tar = require("../tar.js") + , fields = tar.fields + , fieldOffs = tar.fieldOffs + , fieldEnds = tar.fieldEnds + , fieldSize = tar.fieldSize + , numeric = tar.numeric + , assert = require("assert").ok + , space = " ".charCodeAt(0) + , slash = "/".charCodeAt(0) + , bslash = process.platform === "win32" ? "\\".charCodeAt(0) : null + +function TarHeader (block) { + if (!(this instanceof TarHeader)) return new TarHeader(block) + if (block) this.decode(block) +} + +TarHeader.prototype = + { decode : decode + , encode: encode + , calcSum: calcSum + , checkSum: checkSum + } + +TarHeader.parseNumeric = parseNumeric +TarHeader.encode = encode +TarHeader.decode = decode + +// note that this will only do the normal ustar header, not any kind +// of extended posix header file. If something doesn't fit comfortably, +// then it will set obj.needExtended = true, and set the block to +// the closest approximation. +function encode (obj) { + if (!obj && !(this instanceof TarHeader)) throw new Error( + "encode must be called on a TarHeader, or supplied an object") + + obj = obj || this + var block = obj.block = new Buffer(512) + + // if the object has a "prefix", then that's actually an extension of + // the path field. + if (obj.prefix) { + // console.error("%% header encoding, got a prefix", obj.prefix) + obj.path = obj.prefix + "/" + obj.path + // console.error("%% header encoding, prefixed path", obj.path) + obj.prefix = "" + } + + obj.needExtended = false + + if (obj.mode) { + if (typeof obj.mode === "string") obj.mode = parseInt(obj.mode, 8) + obj.mode = obj.mode & 0777 + } + + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , off = fieldOffs[f] + , end = fieldEnds[f] + , ret + + switch (field) { + case "cksum": + // special, done below, after all the others + break + + case "prefix": + // special, this is an extension of the "path" field. + // console.error("%% header encoding, skip prefix later") + break + + case "type": + // convert from long name to a single char. + var type = obj.type || "0" + if (type.length > 1) { + type = tar.types[obj.type] + if (!type) type = "0" + } + writeText(block, off, end, type) + break + + case "path": + // uses the "prefix" field if > 100 bytes, but <= 255 + var pathLen = Buffer.byteLength(obj.path) + , pathFSize = fieldSize[fields.path] + , prefFSize = fieldSize[fields.prefix] + + // paths between 100 and 255 should use the prefix field. + // longer than 255 + if (pathLen > pathFSize && + pathLen <= pathFSize + prefFSize) { + // need to find a slash somewhere in the middle so that + // path and prefix both fit in their respective fields + var searchStart = pathLen - 1 - pathFSize + , searchEnd = prefFSize + , found = false + , pathBuf = new Buffer(obj.path) + + for ( var s = searchStart + ; (s <= searchEnd) + ; s ++ ) { + if (pathBuf[s] === slash || pathBuf[s] === bslash) { + found = s + break + } + } + + if (found !== false) { + prefix = pathBuf.slice(0, found).toString("utf8") + path = pathBuf.slice(found + 1).toString("utf8") + + ret = writeText(block, off, end, path) + off = fieldOffs[fields.prefix] + end = fieldEnds[fields.prefix] + // console.error("%% header writing prefix", off, end, prefix) + ret = writeText(block, off, end, prefix) || ret + break + } + } + + // paths less than 100 chars don't need a prefix + // and paths longer than 255 need an extended header and will fail + // on old implementations no matter what we do here. + // Null out the prefix, and fallthrough to default. + // console.error("%% header writing no prefix") + var poff = fieldOffs[fields.prefix] + , pend = fieldEnds[fields.prefix] + writeText(block, poff, pend, "") + // fallthrough + + // all other fields are numeric or text + default: + ret = numeric[field] + ? writeNumeric(block, off, end, obj[field]) + : writeText(block, off, end, obj[field] || "") + break + } + obj.needExtended = obj.needExtended || ret + } + + var off = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + writeNumeric(block, off, end, calcSum.call(this, block)) + + return block +} + +// if it's a negative number, or greater than will fit, +// then use write256. +var MAXNUM = { 12: 077777777777 + , 11: 07777777777 + , 8 : 07777777 + , 7 : 0777777 } +function writeNumeric (block, off, end, num) { + var writeLen = end - off + , maxNum = MAXNUM[writeLen] || 0 + + num = num || 0 + // console.error(" numeric", num) + + if (num instanceof Date || + Object.prototype.toString.call(num) === "[object Date]") { + num = num.getTime() / 1000 + } + + if (num > maxNum || num < 0) { + write256(block, off, end, num) + // need an extended header if negative or too big. + return true + } + + // god, tar is so annoying + // if the string is small enough, you should put a space + // between the octal string and the \0, but if it doesn't + // fit, then don't. + var numStr = Math.floor(num).toString(8) + if (num < MAXNUM[writeLen - 1]) numStr += " " + + // pad with "0" chars + if (numStr.length < writeLen) { + numStr = (new Array(writeLen - numStr.length).join("0")) + numStr + } + + if (numStr.length !== writeLen - 1) { + throw new Error("invalid length: " + JSON.stringify(numStr) + "\n" + + "expected: "+writeLen) + } + block.write(numStr, off, writeLen, "utf8") + block[end - 1] = 0 +} + +function write256 (block, off, end, num) { + var buf = block.slice(off, end) + var positive = num >= 0 + buf[0] = positive ? 0x80 : 0xFF + + // get the number as a base-256 tuple + if (!positive) num *= -1 + var tuple = [] + do { + var n = num % 256 + tuple.push(n) + num = (num - n) / 256 + } while (num) + + var bytes = tuple.length + + var fill = buf.length - bytes + for (var i = 1; i < fill; i ++) { + buf[i] = positive ? 0 : 0xFF + } + + // tuple is a base256 number, with [0] as the *least* significant byte + // if it's negative, then we need to flip all the bits once we hit the + // first non-zero bit. The 2's-complement is (0x100 - n), and the 1's- + // complement is (0xFF - n). + var zero = true + for (i = bytes; i > 0; i --) { + var byte = tuple[bytes - i] + if (positive) buf[fill + i] = byte + else if (zero && byte === 0) buf[fill + i] = 0 + else if (zero) { + zero = false + buf[fill + i] = 0x100 - byte + } else buf[fill + i] = 0xFF - byte + } +} + +function writeText (block, off, end, str) { + // strings are written as utf8, then padded with \0 + var strLen = Buffer.byteLength(str) + , writeLen = Math.min(strLen, end - off) + // non-ascii fields need extended headers + // long fields get truncated + , needExtended = strLen !== str.length || strLen > writeLen + + // write the string, and null-pad + if (writeLen > 0) block.write(str, off, writeLen, "utf8") + for (var i = off + writeLen; i < end; i ++) block[i] = 0 + + return needExtended +} + +function calcSum (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + if (!block) throw new Error("Need block to checksum") + + // now figure out what it would be if the cksum was " " + var sum = 0 + , start = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + for (var i = 0; i < fieldOffs[fields.cksum]; i ++) { + sum += block[i] + } + + for (var i = start; i < end; i ++) { + sum += space + } + + for (var i = end; i < 512; i ++) { + sum += block[i] + } + + return sum +} + + +function checkSum (block) { + var sum = calcSum.call(this, block) + block = block || this.block + + var cksum = block.slice(fieldOffs[fields.cksum], fieldEnds[fields.cksum]) + cksum = parseNumeric(cksum) + + return cksum === sum +} + +function decode (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + this.block = block + this.cksumValid = this.checkSum() + + var prefix = null + + // slice off each field. + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = block.slice(fieldOffs[f], fieldEnds[f]) + + switch (field) { + case "ustar": + // if not ustar, then everything after that is just padding. + if (val.toString() !== "ustar\0") { + this.ustar = false + return + } else { + // console.error("ustar:", val, val.toString()) + this.ustar = val.toString() + } + break + + // prefix is special, since it might signal the xstar header + case "prefix": + var atime = parseNumeric(val.slice(131, 131 + 12)) + , ctime = parseNumeric(val.slice(131 + 12, 131 + 12 + 12)) + if ((val[130] === 0 || val[130] === space) && + typeof atime === "number" && + typeof ctime === "number" && + val[131 + 12] === space && + val[131 + 12 + 12] === space) { + this.atime = atime + this.ctime = ctime + val = val.slice(0, 130) + } + prefix = val.toString("utf8").replace(/\0+$/, "") + // console.error("%% header reading prefix", prefix) + break + + // all other fields are null-padding text + // or a number. + default: + if (numeric[field]) { + this[field] = parseNumeric(val) + } else { + this[field] = val.toString("utf8").replace(/\0+$/, "") + } + break + } + } + + // if we got a prefix, then prepend it to the path. + if (prefix) { + this.path = prefix + "/" + this.path + // console.error("%% header got a prefix", this.path) + } +} + +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null + + // build up a base-256 tuple from the least sig to the highest + var zero = false + , tuple = [] + for (var i = buf.length - 1; i > 0; i --) { + var byte = buf[i] + if (positive) tuple.push(byte) + else if (zero && byte === 0) tuple.push(0) + else if (zero) { + zero = false + tuple.push(0x100 - byte) + } else tuple.push(0xFF - byte) + } + + for (var sum = 0, i = 0, l = tuple.length; i < l; i ++) { + sum += tuple[i] * Math.pow(256, i) + } + + return positive ? sum : -1 * sum +} + +function parseNumeric (f) { + if (f[0] & 0x80) return parse256(f) + + var str = f.toString("utf8").split("\0")[0].trim() + , res = parseInt(str, 8) + + return isNaN(res) ? null : res +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/pack.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/pack.js new file mode 100644 index 0000000..3ff14dd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/pack.js @@ -0,0 +1,231 @@ +// pipe in an fstream, and it'll make a tarball. +// key-value pair argument is global extended header props. + +module.exports = Pack + +var EntryWriter = require("./entry-writer.js") + , Stream = require("stream").Stream + , path = require("path") + , inherits = require("inherits") + , GlobalHeaderWriter = require("./global-header-writer.js") + , collect = require("fstream").collect + , eof = new Buffer(512) + +for (var i = 0; i < 512; i ++) eof[i] = 0 + +inherits(Pack, Stream) + +function Pack (props) { + // console.error("-- p ctor") + var me = this + if (!(me instanceof Pack)) return new Pack(props) + + if (props) me._noProprietary = props.noProprietary + else me._noProprietary = false + + me._global = props + + me.readable = true + me.writable = true + me._buffer = [] + // console.error("-- -- set current to null in ctor") + me._currentEntry = null + me._processing = false + + me._pipeRoot = null + me.on("pipe", function (src) { + if (src.root === me._pipeRoot) return + me._pipeRoot = src + src.on("end", function () { + me._pipeRoot = null + }) + me.add(src) + }) +} + +Pack.prototype.addGlobal = function (props) { + // console.error("-- p addGlobal") + if (this._didGlobal) return + this._didGlobal = true + + var me = this + GlobalHeaderWriter(props) + .on("data", function (c) { + me.emit("data", c) + }) + .end() +} + +Pack.prototype.add = function (stream) { + if (this._global && !this._didGlobal) this.addGlobal(this._global) + + if (this._ended) return this.emit("error", new Error("add after end")) + + collect(stream) + this._buffer.push(stream) + this._process() + this._needDrain = this._buffer.length > 0 + return !this._needDrain +} + +Pack.prototype.pause = function () { + this._paused = true + if (this._currentEntry) this._currentEntry.pause() + this.emit("pause") +} + +Pack.prototype.resume = function () { + this._paused = false + if (this._currentEntry) this._currentEntry.resume() + this.emit("resume") + this._process() +} + +Pack.prototype.end = function () { + this._ended = true + this._buffer.push(eof) + this._process() +} + +Pack.prototype._process = function () { + var me = this + if (me._paused || me._processing) { + return + } + + var entry = me._buffer.shift() + + if (!entry) { + if (me._needDrain) { + me.emit("drain") + } + return + } + + if (entry.ready === false) { + // console.error("-- entry is not ready", entry) + me._buffer.unshift(entry) + entry.on("ready", function () { + // console.error("-- -- ready!", entry) + me._process() + }) + return + } + + me._processing = true + + if (entry === eof) { + // need 2 ending null blocks. + me.emit("data", eof) + me.emit("data", eof) + me.emit("end") + me.emit("close") + return + } + + // Change the path to be relative to the root dir that was + // added to the tarball. + // + // XXX This should be more like how -C works, so you can + // explicitly set a root dir, and also explicitly set a pathname + // in the tarball to use. That way we can skip a lot of extra + // work when resolving symlinks for bundled dependencies in npm. + + var root = path.dirname((entry.root || entry).path) + var wprops = {} + + Object.keys(entry.props || {}).forEach(function (k) { + wprops[k] = entry.props[k] + }) + + if (me._noProprietary) wprops.noProprietary = true + + wprops.path = path.relative(root, entry.path || '') + + // actually not a matter of opinion or taste. + if (process.platform === "win32") { + wprops.path = wprops.path.replace(/\\/g, "/") + } + + if (!wprops.type) + wprops.type = 'Directory' + + switch (wprops.type) { + // sockets not supported + case "Socket": + return + + case "Directory": + wprops.path += "/" + wprops.size = 0 + break + + case "Link": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(root, lp) || "." + wprops.size = 0 + break + + case "SymbolicLink": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(path.dirname(entry.path), lp) || "." + wprops.size = 0 + break + } + + // console.error("-- new writer", wprops) + // if (!wprops.type) { + // // console.error("-- no type?", entry.constructor.name, entry) + // } + + // console.error("-- -- set current to new writer", wprops.path) + var writer = me._currentEntry = EntryWriter(wprops) + + writer.parent = me + + // writer.on("end", function () { + // // console.error("-- -- writer end", writer.path) + // }) + + writer.on("data", function (c) { + me.emit("data", c) + }) + + writer.on("header", function () { + Buffer.prototype.toJSON = function () { + return this.toString().split(/\0/).join(".") + } + // console.error("-- -- writer header %j", writer.props) + if (writer.props.size === 0) nextEntry() + }) + writer.on("close", nextEntry) + + var ended = false + function nextEntry () { + if (ended) return + ended = true + + // console.error("-- -- writer close", writer.path) + // console.error("-- -- set current to null", wprops.path) + me._currentEntry = null + me._processing = false + me._process() + } + + writer.on("error", function (er) { + // console.error("-- -- writer error", writer.path) + me.emit("error", er) + }) + + // if it's the root, then there's no need to add its entries, + // or data, since they'll be added directly. + if (entry === me._pipeRoot) { + // console.error("-- is the root, don't auto-add") + writer.add = null + } + + entry.pipe(writer) +} + +Pack.prototype.destroy = function () {} +Pack.prototype.write = function () {} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/parse.js new file mode 100644 index 0000000..009a85f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/parse.js @@ -0,0 +1,271 @@ + +// A writable stream. +// It emits "entry" events, which provide a readable stream that has +// header info attached. + +module.exports = Parse.create = Parse + +var stream = require("stream") + , Stream = stream.Stream + , BlockStream = require("block-stream") + , tar = require("../tar.js") + , TarHeader = require("./header.js") + , Entry = require("./entry.js") + , BufferEntry = require("./buffer-entry.js") + , ExtendedHeader = require("./extended-header.js") + , assert = require("assert").ok + , inherits = require("inherits") + , fstream = require("fstream") + +// reading a tar is a lot like reading a directory +// However, we're actually not going to run the ctor, +// since it does a stat and various other stuff. +// This inheritance gives us the pause/resume/pipe +// behavior that is desired. +inherits(Parse, fstream.Reader) + +function Parse () { + var me = this + if (!(me instanceof Parse)) return new Parse() + + // doesn't apply fstream.Reader ctor? + // no, becasue we don't want to stat/etc, we just + // want to get the entry/add logic from .pipe() + Stream.apply(me) + + me.writable = true + me.readable = true + me._stream = new BlockStream(512) + me.position = 0 + me._ended = false + + me._stream.on("error", function (e) { + me.emit("error", e) + }) + + me._stream.on("data", function (c) { + me._process(c) + }) + + me._stream.on("end", function () { + me._streamEnd() + }) + + me._stream.on("drain", function () { + me.emit("drain") + }) +} + +// overridden in Extract class, since it needs to +// wait for its DirWriter part to finish before +// emitting "end" +Parse.prototype._streamEnd = function () { + var me = this + if (!me._ended) me.error("unexpected eof") + me.emit("end") +} + +// a tar reader is actually a filter, not just a readable stream. +// So, you should pipe a tarball stream into it, and it needs these +// write/end methods to do that. +Parse.prototype.write = function (c) { + if (this._ended) { + // gnutar puts a LOT of nulls at the end. + // you can keep writing these things forever. + // Just ignore them. + for (var i = 0, l = c.length; i > l; i ++) { + if (c[i] !== 0) return this.error("write() after end()") + } + return + } + return this._stream.write(c) +} + +Parse.prototype.end = function (c) { + this._ended = true + return this._stream.end(c) +} + +// don't need to do anything, since we're just +// proxying the data up from the _stream. +// Just need to override the parent's "Not Implemented" +// error-thrower. +Parse.prototype._read = function () {} + +Parse.prototype._process = function (c) { + assert(c && c.length === 512, "block size should be 512") + + // one of three cases. + // 1. A new header + // 2. A part of a file/extended header + // 3. One of two or more EOF null blocks + + if (this._entry) { + var entry = this._entry + entry.write(c) + if (entry._remaining === 0) { + entry.end() + this._entry = null + } + } else { + // either zeroes or a header + var zero = true + for (var i = 0; i < 512 && zero; i ++) { + zero = c[i] === 0 + } + + // eof is *at least* 2 blocks of nulls, and then the end of the + // file. you can put blocks of nulls between entries anywhere, + // so appending one tarball to another is technically valid. + // ending without the eof null blocks is not allowed, however. + if (zero) { + if (this._eofStarted) + this._ended = true + this._eofStarted = true + } else { + this._eofStarted = false + this._startEntry(c) + } + } + + this.position += 512 +} + +// take a header chunk, start the right kind of entry. +Parse.prototype._startEntry = function (c) { + var header = new TarHeader(c) + , self = this + , entry + , ev + , EntryType + , onend + , meta = false + + if (null === header.size || !header.cksumValid) { + var e = new Error("invalid tar file") + e.header = header + e.tar_file_offset = this.position + e.tar_block = this.position / 512 + this.emit("error", e) + } + + switch (tar.types[header.type]) { + case "File": + case "OldFile": + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + case "ContiguousFile": + case "GNUDumpDir": + // start a file. + // pass in any extended headers + // These ones consumers are typically most interested in. + EntryType = Entry + ev = "entry" + break + + case "GlobalExtendedHeader": + // extended headers that apply to the rest of the tarball + EntryType = ExtendedHeader + onend = function () { + self._global = self._global || {} + Object.keys(entry.fields).forEach(function (k) { + self._global[k] = entry.fields[k] + }) + } + ev = "globalExtendedHeader" + meta = true + break + + case "ExtendedHeader": + case "OldExtendedHeader": + // extended headers that apply to the next entry + EntryType = ExtendedHeader + onend = function () { + self._extended = entry.fields + } + ev = "extendedHeader" + meta = true + break + + case "NextFileHasLongLinkpath": + // set linkpath= in extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.linkpath = entry.body + } + ev = "longLinkpath" + meta = true + break + + case "NextFileHasLongPath": + case "OldGnuLongPath": + // set path= in file-extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.path = entry.body + } + ev = "longPath" + meta = true + break + + default: + // all the rest we skip, but still set the _entry + // member, so that we can skip over their data appropriately. + // emit an event to say that this is an ignored entry type? + EntryType = Entry + ev = "ignoredEntry" + break + } + + var global, extended + if (meta) { + global = extended = null + } else { + var global = this._global + var extended = this._extended + + // extendedHeader only applies to one entry, so once we start + // an entry, it's over. + this._extended = null + } + entry = new EntryType(header, extended, global) + entry.meta = meta + + // only proxy data events of normal files. + if (!meta) { + entry.on("data", function (c) { + me.emit("data", c) + }) + } + + if (onend) entry.on("end", onend) + + this._entry = entry + var me = this + + entry.on("pause", function () { + me.pause() + }) + + entry.on("resume", function () { + me.resume() + }) + + if (this.listeners("*").length) { + this.emit("*", ev, entry) + } + + this.emit(ev, entry) + + // Zero-byte entry. End immediately. + if (entry.props.size === 0) { + entry.end() + this._entry = null + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENCE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENCE new file mode 100644 index 0000000..74489e2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/README.md new file mode 100644 index 0000000..c16e9c4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/README.md @@ -0,0 +1,14 @@ +# block-stream + +A stream of blocks. + +Write data into it, and it'll output data in buffer blocks the size you +specify, padding with zeroes if necessary. + +```javascript +var block = new BlockStream(512) +fs.createReadStream("some-file").pipe(block) +block.pipe(fs.createWriteStream("block-file")) +``` + +When `.end()` or `.flush()` is called, it'll pad the block with zeroes. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js new file mode 100644 index 0000000..9328844 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js @@ -0,0 +1,70 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + f.pause() + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + f.resume() + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream.js new file mode 100644 index 0000000..1141f3a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/block-stream.js @@ -0,0 +1,68 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js new file mode 100644 index 0000000..93e4068 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js @@ -0,0 +1,70 @@ +var BlockStream = require("dropper") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + f.pause() + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + f.resume() + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper.js new file mode 100644 index 0000000..55fa133 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/bench/dropper.js @@ -0,0 +1,68 @@ +var BlockStream = require("dropper") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/block-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/block-stream.js new file mode 100644 index 0000000..008de03 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/block-stream.js @@ -0,0 +1,209 @@ +// write data to it, and it'll emit data in 512 byte blocks. +// if you .end() or .flush(), it'll emit whatever it's got, +// padded with nulls to 512 bytes. + +module.exports = BlockStream + +var Stream = require("stream").Stream + , inherits = require("inherits") + , assert = require("assert").ok + , debug = process.env.DEBUG ? console.error : function () {} + +function BlockStream (size, opt) { + this.writable = this.readable = true + this._opt = opt || {} + this._chunkSize = size || 512 + this._offset = 0 + this._buffer = [] + this._bufferLength = 0 + if (this._opt.nopad) this._zeroes = false + else { + this._zeroes = new Buffer(this._chunkSize) + for (var i = 0; i < this._chunkSize; i ++) { + this._zeroes[i] = 0 + } + } +} + +inherits(BlockStream, Stream) + +BlockStream.prototype.write = function (c) { + // debug(" BS write", c) + if (this._ended) throw new Error("BlockStream: write after end") + if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "") + if (c.length) { + this._buffer.push(c) + this._bufferLength += c.length + } + // debug("pushed onto buffer", this._bufferLength) + if (this._bufferLength >= this._chunkSize) { + if (this._paused) { + // debug(" BS paused, return false, need drain") + this._needDrain = true + return false + } + this._emitChunk() + } + return true +} + +BlockStream.prototype.pause = function () { + // debug(" BS pausing") + this._paused = true +} + +BlockStream.prototype.resume = function () { + // debug(" BS resume") + this._paused = false + return this._emitChunk() +} + +BlockStream.prototype.end = function (chunk) { + // debug("end", chunk) + if (typeof chunk === "function") cb = chunk, chunk = null + if (chunk) this.write(chunk) + this._ended = true + this.flush() +} + +BlockStream.prototype.flush = function () { + this._emitChunk(true) +} + +BlockStream.prototype._emitChunk = function (flush) { + // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused) + + // emit a chunk + if (flush && this._zeroes) { + // debug(" BS push zeroes", this._bufferLength) + // push a chunk of zeroes + var padBytes = (this._bufferLength % this._chunkSize) + if (padBytes !== 0) padBytes = this._chunkSize - padBytes + if (padBytes > 0) { + // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes)) + this._buffer.push(this._zeroes.slice(0, padBytes)) + this._bufferLength += padBytes + // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength) + } + } + + if (this._emitting || this._paused) return + this._emitting = true + + // debug(" BS entering loops") + var bufferIndex = 0 + while (this._bufferLength >= this._chunkSize && + (flush || !this._paused)) { + // debug(" BS data emission loop", this._bufferLength) + + var out + , outOffset = 0 + , outHas = this._chunkSize + + while (outHas > 0 && (flush || !this._paused) ) { + // debug(" BS data inner emit loop", this._bufferLength) + var cur = this._buffer[bufferIndex] + , curHas = cur.length - this._offset + // debug("cur=", cur) + // debug("curHas=%j", curHas) + // If it's not big enough to fill the whole thing, then we'll need + // to copy multiple buffers into one. However, if it is big enough, + // then just slice out the part we want, to save unnecessary copying. + // Also, need to copy if we've already done some copying, since buffers + // can't be joined like cons strings. + if (out || curHas < outHas) { + out = out || new Buffer(this._chunkSize) + cur.copy(out, outOffset, + this._offset, this._offset + Math.min(curHas, outHas)) + } else if (cur.length === outHas && this._offset === 0) { + // shortcut -- cur is exactly long enough, and no offset. + out = cur + } else { + // slice out the piece of cur that we need. + out = cur.slice(this._offset, this._offset + outHas) + } + + if (curHas > outHas) { + // means that the current buffer couldn't be completely output + // update this._offset to reflect how much WAS written + this._offset += outHas + outHas = 0 + } else { + // output the entire current chunk. + // toss it away + outHas -= curHas + outOffset += curHas + bufferIndex ++ + this._offset = 0 + } + } + + this._bufferLength -= this._chunkSize + assert(out.length === this._chunkSize) + // debug("emitting data", out) + // debug(" BS emitting, paused=%j", this._paused, this._bufferLength) + this.emit("data", out) + out = null + } + // debug(" BS out of loops", this._bufferLength) + + // whatever is left, it's not enough to fill up a block, or we're paused + this._buffer = this._buffer.slice(bufferIndex) + if (this._paused) { + // debug(" BS paused, leaving", this._bufferLength) + this._needsDrain = true + this._emitting = false + return + } + + // if flushing, and not using null-padding, then need to emit the last + // chunk(s) sitting in the queue. We know that it's not enough to + // fill up a whole block, because otherwise it would have been emitted + // above, but there may be some offset. + var l = this._buffer.length + if (flush && !this._zeroes && l) { + if (l === 1) { + if (this._offset) { + this.emit("data", this._buffer[0].slice(this._offset)) + } else { + this.emit("data", this._buffer[0]) + } + } else { + var outHas = this._bufferLength + , out = new Buffer(outHas) + , outOffset = 0 + for (var i = 0; i < l; i ++) { + var cur = this._buffer[i] + , curHas = cur.length - this._offset + cur.copy(out, outOffset, this._offset) + this._offset = 0 + outOffset += curHas + this._bufferLength -= curHas + } + this.emit("data", out) + } + // truncate + this._buffer.length = 0 + this._bufferLength = 0 + this._offset = 0 + } + + // now either drained or ended + // debug("either draining, or ended", this._bufferLength, this._ended) + // means that we've flushed out all that we can so far. + if (this._needDrain) { + // debug("emitting drain", this._bufferLength) + this._needDrain = false + this.emit("drain") + } + + if ((this._bufferLength === 0) && this._ended && !this._endEmitted) { + // debug("emitting end", this._bufferLength) + this._endEmitted = true + this.emit("end") + } + + this._emitting = false + + // debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/package.json new file mode 100644 index 0000000..97d9d42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/package.json @@ -0,0 +1,55 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "block-stream", + "description": "a stream of blocks", + "version": "0.0.8", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/block-stream.git" + }, + "engines": { + "node": "0.4 || >=0.5.8" + }, + "main": "block-stream.js", + "dependencies": { + "inherits": "~2.0.0" + }, + "devDependencies": { + "tap": "0.x" + }, + "scripts": { + "test": "tap test/" + }, + "license": "ISC", + "gitHead": "b35520314f4763af0788d65a846bb43d9c0a8f02", + "bugs": { + "url": "https://github.com/isaacs/block-stream/issues" + }, + "homepage": "https://github.com/isaacs/block-stream#readme", + "_id": "block-stream@0.0.8", + "_shasum": "0688f46da2bbf9cff0c4f68225a0cb95cbe8a46b", + "_from": "block-stream@*", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "0688f46da2bbf9cff0c4f68225a0cb95cbe8a46b", + "tarball": "http://registry.npmjs.org/block-stream/-/block-stream-0.0.8.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.8.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/basic.js new file mode 100644 index 0000000..b4b9305 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/basic.js @@ -0,0 +1,27 @@ +var tap = require("tap") + , BlockStream = require("../block-stream.js") + +tap.test("basic test", function (t) { + var b = new BlockStream(16) + var fs = require("fs") + var fstr = fs.createReadStream(__filename, {encoding: "utf8"}) + fstr.pipe(b) + + var stat + t.doesNotThrow(function () { + stat = fs.statSync(__filename) + }, "stat should not throw") + + var totalBytes = 0 + b.on("data", function (c) { + t.equal(c.length, 16, "chunks should be 16 bytes long") + t.type(c, Buffer, "chunks should be buffer objects") + totalBytes += c.length + }) + b.on("end", function () { + var expectedBytes = stat.size + (16 - stat.size % 16) + t.equal(totalBytes, expectedBytes, "Should be multiple of 16") + t.end() + }) + +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js new file mode 100644 index 0000000..7a8de88 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js @@ -0,0 +1,68 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16]//, 25]//, 1024] + , writeSizes = [4, 15, 16, 17, 64 ]//, 64, 100] + , writeCounts = [1, 10]//, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad.js new file mode 100644 index 0000000..6d38429 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/nopad.js @@ -0,0 +1,57 @@ +var BlockStream = require("../") +var tap = require("tap") + + +tap.test("don't pad, small writes", function (t) { + var f = new BlockStream(16, { nopad: true }) + t.plan(1) + + f.on("data", function (c) { + t.equal(c.toString(), "abc", "should get 'abc'") + }) + + f.on("end", function () { t.end() }) + + f.write(new Buffer("a")) + f.write(new Buffer("b")) + f.write(new Buffer("c")) + f.end() +}) + +tap.test("don't pad, exact write", function (t) { + var f = new BlockStream(16, { nopad: true }) + t.plan(1) + + var first = true + f.on("data", function (c) { + if (first) { + first = false + t.equal(c.toString(), "abcdefghijklmnop", "first chunk") + } else { + t.fail("should only get one") + } + }) + + f.on("end", function () { t.end() }) + + f.end(new Buffer("abcdefghijklmnop")) +}) + +tap.test("don't pad, big write", function (t) { + var f = new BlockStream(16, { nopad: true }) + t.plan(2) + + var first = true + f.on("data", function (c) { + if (first) { + first = false + t.equal(c.toString(), "abcdefghijklmnop", "first chunk") + } else { + t.equal(c.toString(), "q") + } + }) + + f.on("end", function () { t.end() }) + + f.end(new Buffer("abcdefghijklmnopq")) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/pause-resume.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/pause-resume.js new file mode 100644 index 0000000..64d0d09 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/pause-resume.js @@ -0,0 +1,73 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16] + , writeSizes = [15, 16, 17] + , writeCounts = [1, 10]//, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + var paused = false + + f.on("data", function (c) { + timeouts ++ + t.notOk(paused, "should not be paused when emitting data") + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + paused = true + f.pause() + process.nextTick(function () { + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + paused = false + f.resume() + timeouts -- + }) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = expectChunks * blockSize + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 200) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/thorough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/thorough.js new file mode 100644 index 0000000..1cc9ea0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/thorough.js @@ -0,0 +1,68 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16]//, 25]//, 1024] + , writeSizes = [4, 15, 16, 17, 64 ]//, 64, 100] + , writeCounts = [1, 10]//, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = expectChunks * blockSize + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/two-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/two-stream.js new file mode 100644 index 0000000..c6db79a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/block-stream/test/two-stream.js @@ -0,0 +1,59 @@ +var log = console.log, + assert = require( 'assert' ), + BlockStream = require("../block-stream.js"), + isize = 0, tsize = 0, fsize = 0, psize = 0, i = 0, + filter = null, paper = null, stack = null, + +// a source data buffer +tsize = 1 * 1024; // <- 1K +stack = new Buffer( tsize ); +for ( ; i < tsize; i++) stack[i] = "x".charCodeAt(0); + +isize = 1 * 1024; // <- initial packet size with 4K no bug! +fsize = 2 * 1024 ; // <- first block-stream size +psize = Math.ceil( isize / 6 ); // <- second block-stream size + +fexpected = Math.ceil( tsize / fsize ); // <- packets expected for first +pexpected = Math.ceil( tsize / psize ); // <- packets expected for second + + +filter = new BlockStream( fsize, { nopad : true } ); +paper = new BlockStream( psize, { nopad : true } ); + + +var fcounter = 0; +filter.on( 'data', function (c) { + // verify that they're not null-padded + for (var i = 0; i < c.length; i ++) { + assert.strictEqual(c[i], "x".charCodeAt(0)) + } + ++fcounter; +} ); + +var pcounter = 0; +paper.on( 'data', function (c) { + // verify that they're not null-padded + for (var i = 0; i < c.length; i ++) { + assert.strictEqual(c[i], "x".charCodeAt(0)) + } + ++pcounter; +} ); + +filter.pipe( paper ); + +filter.on( 'end', function () { + log("fcounter: %s === %s", fcounter, fexpected) + assert.strictEqual( fcounter, fexpected ); +} ); + +paper.on( 'end', function () { + log("pcounter: %s === %s", pcounter, pexpected); + assert.strictEqual( pcounter, pexpected ); +} ); + + +for ( i = 0, j = isize; j <= tsize; j += isize ) { + filter.write( stack.slice( j - isize, j ) ); +} + +filter.end(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/package.json new file mode 100644 index 0000000..8c08a43 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.0 <3.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/package.json new file mode 100644 index 0000000..7799429 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/package.json @@ -0,0 +1,54 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "tar", + "description": "tar for node", + "version": "0.1.20", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-tar.git" + }, + "main": "tar.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "block-stream": "*", + "fstream": "~0.1.28", + "inherits": "2" + }, + "devDependencies": { + "tap": "0.x", + "rimraf": "1.x" + }, + "license": "BSD", + "gitHead": "b5931010907cd1ef5a186bc947954391050cbcce", + "bugs": { + "url": "https://github.com/isaacs/node-tar/issues" + }, + "homepage": "https://github.com/isaacs/node-tar", + "_id": "tar@0.1.20", + "_shasum": "42940bae5b5f22c74483699126f9f3f27449cb13", + "_from": "tar@>=0.1.17 <0.2.0", + "_npmVersion": "1.4.16", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "dist": { + "shasum": "42940bae5b5f22c74483699126f9f3f27449cb13", + "tarball": "http://registry.npmjs.org/tar/-/tar-0.1.20.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/tar/-/tar-0.1.20.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/tar.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/tar.js new file mode 100644 index 0000000..a81298b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/tar.js @@ -0,0 +1,173 @@ +// field paths that every tar file must have. +// header is padded to 512 bytes. +var f = 0 + , fields = {} + , path = fields.path = f++ + , mode = fields.mode = f++ + , uid = fields.uid = f++ + , gid = fields.gid = f++ + , size = fields.size = f++ + , mtime = fields.mtime = f++ + , cksum = fields.cksum = f++ + , type = fields.type = f++ + , linkpath = fields.linkpath = f++ + , headerSize = 512 + , blockSize = 512 + , fieldSize = [] + +fieldSize[path] = 100 +fieldSize[mode] = 8 +fieldSize[uid] = 8 +fieldSize[gid] = 8 +fieldSize[size] = 12 +fieldSize[mtime] = 12 +fieldSize[cksum] = 8 +fieldSize[type] = 1 +fieldSize[linkpath] = 100 + +// "ustar\0" may introduce another bunch of headers. +// these are optional, and will be nulled out if not present. + +var ustar = fields.ustar = f++ + , ustarver = fields.ustarver = f++ + , uname = fields.uname = f++ + , gname = fields.gname = f++ + , devmaj = fields.devmaj = f++ + , devmin = fields.devmin = f++ + , prefix = fields.prefix = f++ + , fill = fields.fill = f++ + +// terminate fields. +fields[f] = null + +fieldSize[ustar] = 6 +fieldSize[ustarver] = 2 +fieldSize[uname] = 32 +fieldSize[gname] = 32 +fieldSize[devmaj] = 8 +fieldSize[devmin] = 8 +fieldSize[prefix] = 155 +fieldSize[fill] = 12 + +// nb: prefix field may in fact be 130 bytes of prefix, +// a null char, 12 bytes for atime, 12 bytes for ctime. +// +// To recognize this format: +// 1. prefix[130] === ' ' or '\0' +// 2. atime and ctime are octal numeric values +// 3. atime and ctime have ' ' in their last byte + +var fieldEnds = {} + , fieldOffs = {} + , fe = 0 +for (var i = 0; i < f; i ++) { + fieldOffs[i] = fe + fieldEnds[i] = (fe += fieldSize[i]) +} + +// build a translation table of field paths. +Object.keys(fields).forEach(function (f) { + if (fields[f] !== null) fields[fields[f]] = f +}) + +// different values of the 'type' field +// paths match the values of Stats.isX() functions, where appropriate +var types = + { 0: "File" + , "\0": "OldFile" // like 0 + , "": "OldFile" + , 1: "Link" + , 2: "SymbolicLink" + , 3: "CharacterDevice" + , 4: "BlockDevice" + , 5: "Directory" + , 6: "FIFO" + , 7: "ContiguousFile" // like 0 + // posix headers + , g: "GlobalExtendedHeader" // k=v for the rest of the archive + , x: "ExtendedHeader" // k=v for the next file + // vendor-specific stuff + , A: "SolarisACL" // skip + , D: "GNUDumpDir" // like 5, but with data, which should be skipped + , I: "Inode" // metadata only, skip + , K: "NextFileHasLongLinkpath" // data = link path of next file + , L: "NextFileHasLongPath" // data = path of next file + , M: "ContinuationFile" // skip + , N: "OldGnuLongPath" // like L + , S: "SparseFile" // skip + , V: "TapeVolumeHeader" // skip + , X: "OldExtendedHeader" // like x + } + +Object.keys(types).forEach(function (t) { + types[types[t]] = types[types[t]] || t +}) + +// values for the mode field +var modes = + { suid: 04000 // set uid on extraction + , sgid: 02000 // set gid on extraction + , svtx: 01000 // set restricted deletion flag on dirs on extraction + , uread: 0400 + , uwrite: 0200 + , uexec: 0100 + , gread: 040 + , gwrite: 020 + , gexec: 010 + , oread: 4 + , owrite: 2 + , oexec: 1 + , all: 07777 + } + +var numeric = + { mode: true + , uid: true + , gid: true + , size: true + , mtime: true + , devmaj: true + , devmin: true + , cksum: true + , atime: true + , ctime: true + , dev: true + , ino: true + , nlink: true + } + +Object.keys(modes).forEach(function (t) { + modes[modes[t]] = modes[modes[t]] || t +}) + +var knownExtended = + { atime: true + , charset: true + , comment: true + , ctime: true + , gid: true + , gname: true + , linkpath: true + , mtime: true + , path: true + , realtime: true + , security: true + , size: true + , uid: true + , uname: true } + + +exports.fields = fields +exports.fieldSize = fieldSize +exports.fieldOffs = fieldOffs +exports.fieldEnds = fieldEnds +exports.types = types +exports.modes = modes +exports.numeric = numeric +exports.headerSize = headerSize +exports.blockSize = blockSize +exports.knownExtended = knownExtended + +exports.Pack = require("./lib/pack.js") +exports.Parse = require("./lib/parse.js") +exports.Extract = require("./lib/extract.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/00-setup-fixtures.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/00-setup-fixtures.js new file mode 100644 index 0000000..1524ff7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/00-setup-fixtures.js @@ -0,0 +1,53 @@ +// the fixtures have some weird stuff that is painful +// to include directly in the repo for various reasons. +// +// So, unpack the fixtures with the system tar first. +// +// This means, of course, that it'll only work if you +// already have a tar implementation, and some of them +// will not properly unpack the fixtures anyway. +// +// But, since usually those tests will fail on Windows +// and other systems with less capable filesystems anyway, +// at least this way we don't cause inconveniences by +// merely cloning the repo or installing the package. + +var tap = require("tap") +, child_process = require("child_process") +, rimraf = require("rimraf") +, test = tap.test +, path = require("path") + +test("clean fixtures", function (t) { + rimraf(path.resolve(__dirname, "fixtures"), function (er) { + t.ifError(er, "rimraf ./fixtures/") + t.end() + }) +}) + +test("clean tmp", function (t) { + rimraf(path.resolve(__dirname, "tmp"), function (er) { + t.ifError(er, "rimraf ./tmp/") + t.end() + }) +}) + +test("extract fixtures", function (t) { + var c = child_process.spawn("tar" + ,["xzvf", "fixtures.tgz"] + ,{ cwd: __dirname }) + + c.stdout.on("data", errwrite) + c.stderr.on("data", errwrite) + function errwrite (chunk) { + process.stderr.write(chunk) + } + + c.on("exit", function (code) { + t.equal(code, 0, "extract fixtures should exit with 0") + if (code) { + t.comment("Note, all tests from here on out will fail because of this.") + } + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/extract.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/extract.js new file mode 100644 index 0000000..a68144b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/extract.js @@ -0,0 +1,367 @@ +// Set the umask, so that it works the same everywhere. +process.umask(parseInt('22', 8)) + +var tap = require("tap") + , tar = require("../tar.js") + , fs = require("fs") + , path = require("path") + , file = path.resolve(__dirname, "fixtures/c.tar") + , target = path.resolve(__dirname, "tmp/extract-test") + , index = 0 + , fstream = require("fstream") + + , ee = 0 + , expectEntries = +[ { path: 'c.txt', + mode: '644', + type: '0', + depth: undefined, + size: 513, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'cc.txt', + mode: '644', + type: '0', + depth: undefined, + size: 513, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '0', + depth: undefined, + size: 100, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'Ω.txt', + mode: '644', + type: '0', + depth: undefined, + size: 2, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'Ω.txt', + mode: '644', + type: '0', + depth: undefined, + size: 2, + linkpath: '', + nlink: 1, + dev: 234881026, + ino: 51693379 }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '0', + depth: undefined, + size: 200, + linkpath: '', + nlink: 1, + dev: 234881026, + ino: 51681874 }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '0', + depth: undefined, + size: 201, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', + mode: '777', + type: '2', + depth: undefined, + size: 0, + linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: '200-hard', + mode: '644', + type: '0', + depth: undefined, + size: 200, + linkpath: '', + nlink: 2, + dev: 234881026, + ino: 51681874 }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '1', + depth: undefined, + size: 0, + linkpath: path.resolve(target, '200-hard'), + nlink: 2, + dev: 234881026, + ino: 51681874 } ] + + , ef = 0 + , expectFiles = +[ { path: '', + mode: '40755', + type: 'Directory', + depth: 0, + linkpath: undefined }, + { path: '/200-hard', + mode: '100644', + type: 'File', + depth: 1, + size: 200, + linkpath: undefined, + nlink: 2 }, + { path: '/200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', + mode: '120755', + type: 'SymbolicLink', + depth: 1, + size: 200, + linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + nlink: 1 }, + { path: '/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '100644', + type: 'Link', + depth: 1, + size: 200, + linkpath: path.join(target, '200-hard'), + nlink: 2 }, + { path: '/c.txt', + mode: '100644', + type: 'File', + depth: 1, + size: 513, + linkpath: undefined, + nlink: 1 }, + { path: '/cc.txt', + mode: '100644', + type: 'File', + depth: 1, + size: 513, + linkpath: undefined, + nlink: 1 }, + { path: '/r', + mode: '40755', + type: 'Directory', + depth: 1, + linkpath: undefined }, + { path: '/r/e', + mode: '40755', + type: 'Directory', + depth: 2, + linkpath: undefined }, + { path: '/r/e/a', + mode: '40755', + type: 'Directory', + depth: 3, + linkpath: undefined }, + { path: '/r/e/a/l', + mode: '40755', + type: 'Directory', + depth: 4, + linkpath: undefined }, + { path: '/r/e/a/l/l', + mode: '40755', + type: 'Directory', + depth: 5, + linkpath: undefined }, + { path: '/r/e/a/l/l/y', + mode: '40755', + type: 'Directory', + depth: 6, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-', + mode: '40755', + type: 'Directory', + depth: 7, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d', + mode: '40755', + type: 'Directory', + depth: 8, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e', + mode: '40755', + type: 'Directory', + depth: 9, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e', + mode: '40755', + type: 'Directory', + depth: 10, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p', + mode: '40755', + type: 'Directory', + depth: 11, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-', + mode: '40755', + type: 'Directory', + depth: 12, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f', + mode: '40755', + type: 'Directory', + depth: 13, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o', + mode: '40755', + type: 'Directory', + depth: 14, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l', + mode: '40755', + type: 'Directory', + depth: 15, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d', + mode: '40755', + type: 'Directory', + depth: 16, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e', + mode: '40755', + type: 'Directory', + depth: 17, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r', + mode: '40755', + type: 'Directory', + depth: 18, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-', + mode: '40755', + type: 'Directory', + depth: 19, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p', + mode: '40755', + type: 'Directory', + depth: 20, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a', + mode: '40755', + type: 'Directory', + depth: 21, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t', + mode: '40755', + type: 'Directory', + depth: 22, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h', + mode: '40755', + type: 'Directory', + depth: 23, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '100644', + type: 'File', + depth: 24, + size: 100, + linkpath: undefined, + nlink: 1 }, + { path: '/Ω.txt', + mode: '100644', + type: 'File', + depth: 1, + size: 2, + linkpath: undefined, + nlink: 1 } ] + + + +// The extract class basically just pipes the input +// to a Reader, and then to a fstream.DirWriter + +// So, this is as much a test of fstream.Reader and fstream.Writer +// as it is of tar.Extract, but it sort of makes sense. + +tap.test("preclean", function (t) { + require("rimraf").sync(__dirname + "/tmp/extract-test") + t.pass("cleaned!") + t.end() +}) + +tap.test("extract test", function (t) { + var extract = tar.Extract(target) + var inp = fs.createReadStream(file) + + // give it a weird buffer size to try to break in odd places + inp.bufferSize = 1234 + + inp.pipe(extract) + + extract.on("end", function () { + t.equal(ee, expectEntries.length, "should see "+ee+" entries") + + // should get no more entries after end + extract.removeAllListeners("entry") + extract.on("entry", function (e) { + t.fail("Should not get entries after end!") + }) + + next() + }) + + extract.on("entry", function (entry) { + var found = + { path: entry.path + , mode: entry.props.mode.toString(8) + , type: entry.props.type + , depth: entry.props.depth + , size: entry.props.size + , linkpath: entry.props.linkpath + , nlink: entry.props.nlink + , dev: entry.props.dev + , ino: entry.props.ino + } + + var wanted = expectEntries[ee ++] + + t.equivalent(found, wanted, "tar entry " + ee + " " + wanted.path) + }) + + function next () { + var r = fstream.Reader({ path: target + , type: "Directory" + // this is just to encourage consistency + , sort: "alpha" }) + + r.on("ready", function () { + foundEntry(r) + }) + + r.on("end", finish) + + function foundEntry (entry) { + var p = entry.path.substr(target.length) + var found = + { path: p + , mode: entry.props.mode.toString(8) + , type: entry.props.type + , depth: entry.props.depth + , size: entry.props.size + , linkpath: entry.props.linkpath + , nlink: entry.props.nlink + } + + var wanted = expectFiles[ef ++] + + t.has(found, wanted, "unpacked file " + ef + " " + wanted.path) + + entry.on("entry", foundEntry) + } + + function finish () { + t.equal(ef, expectFiles.length, "should have "+ef+" items") + t.end() + } + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/fixtures.tgz b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/fixtures.tgz new file mode 100644 index 0000000000000000000000000000000000000000..4501bcf22695435b84edb3d4076cd9a70687b035 GIT binary patch literal 19205 zcmdS9Wm8^F&@GI+1$UC5!6CR4+}#Q8?(Xgo+@0X=mJ8S5F2UX1x%SKbJYU{Zb^gHl zva4qI-ZR}(-D|C$8nS2v2z6Tw1qkSK-!(TZsZ^RNa1__yOh~V~Z1>TH9ztlwtK>lK zWmOG@dzb2_ zxNwX{Rl|=%Pu;FM(vx~PcIG@m0S`eDK+0zy(D}3DRx_4@habN94D=@^M_EF%LAIP8 zML4lcx9I1oUgLK#?D>f2k^d#)-2xascd0K$6RO9HLW#{Cz}f&P(E2{3^y5DWBJDl} zUZt|6(^fr$f$ZGwiCH}kVVEOEXxs}Bo`k?9i0t)?&vvL1h8Oz43N5a|#G~L9KZ|@R z^;BB(du3Q`57xiqEjI6qaIo8KFWDRYLS8fZCVFCQ9r?qf-i43Pz1wBlKXv!SUaaR4 zukUCa5G3eZk?(@7UMp#b!uYN{f8g!m3toJf$MS~#X0LhAE&4CZ;wAcfk8Yj)cWXF3 zAgc`4@MiswywzUNcYCe@wVuZx5ANM@XvAC&4x3w9(?ECrR{(3ue$)9~pJ1_7U~4V3 zXVdI`(*=ee7F`|n_ZJM9UN>qKzBvqp9eI4pnFk-7O-{A9f$(_VM}=N}h|S;Nyr(0e zbLj=}EdVY5UZfNub`c_{Uj1?KC9(M<LyT_s$<0iz>o=H*4AP32x*ear)hd zNU*Xr@^VnMjYF==Ym~%C2g1m3q8AhSy_Xp)%P3jlJ4?=A@qaFv_ahlk{}7O?FR8z1 zmapPo^>ZA(Z>)n(IbgJr5cxzP42>xCL#- z@!#r0HGSc#p^w{fn++O_>w>X~S5uV!7be+aIOY2k*bSO2+_>|FuY~CjGgzAS`Co54 z>W&VIEIBf9H)DOC^!&P976!Is5aF#+C)0(VA)u5^JU5m4y@JW%Bp|KP;$VmotGKx^ z9VqG!wj_Ig^<)NdMk!fS@w}0uBuVCC7`hbEAVLWUT@Pn@>+K0)@Zsze3 z`%jv8`o({l>Qi}_=Yc)|P8>20ECSvyA^+!Xl@TB{YTf#4=-N;HR$uP63J4X(9?qwR z^TQUv=%o!wDg?w{HVZFFxE!{&a)lSbWF@65QRl!w6Cli-@QzMf&A(=G*i5F@x*^tt@JgJ8vzUL_IGw^Z(Y$CsRVv)js6lNQt#VeC- zj*0pB@vhP9RJ@Pi=hrE8tm#*gI-n5aFN8Tz4Z*=VD3$uq5V^d*F8TJ^TH;)u_vV5< z&ow#M28u2~8Jz&Qeb1pq5xFomogFB)l<6<2@elo5iSM<7+#TPjNjVVDuN0v80OZv`UO)$S zI&doSRkIH8*dmXCChLV4umdz8-Ots!o!d@P9kzM`gL$D;0G-sY4zAB+p@DONI+Qzu z-zD*d7xV=_+dJ7m!#8tY#$Ca+L~srmgt@$qUF74Gi8jGJ-4hz998nrmUl|%`L}Rdq z04?{Ym3g|T6CHZcfQSSxvuO<*F0+kU5f82d$-yvR&M^NguT1CMc6-FT5OIz|!PKcrB zP0mli%EQ+<0OjBFChgYI#jc>QGmzw_b0rnO_JQy}J0pqL8P?gs+#kt#(K8QR(106- z!4if?JAxV?!TNt#EnY4+)II`z@bv^lmg9Qx_g?ZQ!8(XGc2SH@egxq5Um=VSD#L!O zltNfmkkP?#>WI^OuTk%3epvN+4KNm%t=%+RnE8>>?=JOubP#y2QuVy_xL(I>umxLw zi_h>OeIFnb$PPGC)NPlzQzwzE^S4F7;x#pXAW(o@aMbwGs{tN92inb9McsSAS&@-|y6Z|B3+29|#({`s;FPf@}i+$Fd{+Pk0`YzUp02F3uI%~eqkf}%EHd!v zjsN+1KH1&Yqof}^(9Hj=1qIyiH{N*LK!f_t>vA~!Hrh8lE;;FE23;r@eNNMTE!zU| zl_<~t5D7cEdw75h*@N~jEKFFqyiF#0SI8+OZ|2UpQXXK{SV&6EiT=_5bCXy(;T@ku z7#-{3F!oH2T|{Ym_FW+W-iC9?On3Ed%tQRnC>_UdMQZ=KxrOnL=|Q#?*@*C2bV9=R z|2vNi?u5fc`M`g>k0Nn{MucO=+LPmc_vte-f^K31{fp$0Lh+JM9yn_5ivK;pK&;SI zjqIHHH!NMdr1<#3eP=2~>EG99%(Tx!mI9A6eTd*y>U{)R=l zB>e7&bK=`_q4`o+jP*d@o&XgNVr;*W?j1LEj)|#l^QkQ+eKj(@#iR? zv_j*M2)qkcAd>6hcDV+kad-WF0GI~!h5G9r=N6)icY)ltZ*4eQ1o1ec$vv(ny5rty zb_B+sD}zyyDH0y8Q$yITs&LP6v=M0j+vV*)Qel_xhkZqP6lY}sF7dmlsxlJAXFj~0 zZQ1$QmLj2up2w$oL#;x?1%tdS3X-?->?~0~42kNxxz$bY_D|1_J%_4}n1jM_$Rzm{ zqT|a74alh^su3mG#oKcv>um0cEj}1Vhr5-n-k`IVjwF->7_Op7K1YXV=$5!mONq@Z z$Ti|JQXW+XglmugpR9qoiKZsn3@>hj?fhy&(9u(a5c$(bqZE@4g8=y)$sjfwQoe|<)QgK+x0(9%%ze@HKz7pd*t=9=G8>n_JX-~#>v z{HO-;Z@FPlfN{gWqeBY6)ff5C`Pw<~!LB*=AAFI$rDuOsBLtxv3s48uUO2z`<2Wq6 z4fp;F+67KgD|_l;-^eZ(FowDbgDw}^4&MN2Je>8HDn``GWuP-FCs?cphbDDx`0GnJ zC`2jnhXZVsw>U&g}(dunsDh8$>EAGgK z7{SJrSKSHkKWle=Ll@PpPX!-tXRZb6Dk<;3jQVVVgn&PW$UTRD$f!R9j~`kXIRYH& z!9044JdrQ9xvAoC2imBMdVkb}^bo4~v-}-cxSM+LCmuZC3&aci)jInmm=B2E`2UYk z!g~Q0@6YUU{-`~ZwUR~TrGCto{RXn0?Z#<4b?vIXs-6YS0UFRk!0RUT`aREvhUOrc zT&Z>Ky!}ORmhTvl!WVUX>xqUIL?VkY!0EG`xc5JOGry(Cxw8YI+Xn)iS8FZ6QamP; z+o513#BNha6w0fTNp9-2xiEg!K@)|8`g(<-r>cJ6*O%HHzyKUS4(K9sz1ny84*FMd zzxz*JlR2|zj>u$-i(D}b_<=@q!Zxzr~#TNkk1}Xq6V8bzj z{VD5gwlBBV!t8$vy4LB^JOei{Jqu5Qi$G*y%Pmk1bCC&fwdpv#`F9K70)Dxz@(m?z zx=aUv-yVD-5RS-)IrnV8_XJ2AIIG0mj9T)ja*Em6*-=Q%D!d4%7B6+4UFZZ7Z9+r} z{_28c{oP4=3>N(3o@N&?u;yOST=(w#4Kv(c%>;7J=7xFIX8H~;(J3XgxO(u0T38+I#91r|D zBMcS;WI7<-Am2}4^-*6Gez*f`(gu+>`u+P)Ac12XpV`v~f1Ir+5cG#ct)jMgN58dU zG4-4S-3#E3`fCB?*L_?!P|1MfR_DtlUEn3*10sU2kRFAJ=Wnf(A%{^ z+|}Igr<9Wljk_+~1Q2+a{tyNOz_2Fp?ZJ5JzYg`_H-4$P_?3Umy%LWSbtINxWMUf$ z%)4Ex9lRE=mHX;Uc2T@NnjP`mrEz{M&f8|#CLhwHMlZn9d}4g%-|0Mz^@kFp(2Mej zbuzLGwiobQ+uZ_M(4QiDfqJ}t=l@|e-76q77#UoOpdiAS{taT}A>f}9LG^!}ww(aQ z3mYSgvH8E8<{>~~MgUp49(K8AC?R;rDR78YdC`;it>bdUW%`K7A_n9v$0AlFZ^qk*vIe!l2Pp@5s;XP%Niq9crtueg8I)O{d zuuFV`L6kP`SB*_?f8*D3>R{ix%agU~5Ol=9vG>Hg)#XqyfaV%%XFIJ6r?+-|7KwGU z(GerGcdmS!urjyQF~fslTSO!y2YMeB~9a^^#`u{JT;d4J-nDpDGGAl%P z^seAc?axsl`klt<+P^Zus&0w(yw8Q&B5UskQds-A;PkD$_$ zfR^{AhnzQkSgvQ#hQS=b#jg{Dd}Q=e8ln9M;Du?hR{@)2cE0ARLzMvLo=^q_0QE!V zn_$l?Sq@T|4J1+8bcM)V_!AqfnX<|e??2={oFtHuo5!NIhj331`3;vc$GayF{_}44{uqz^yo&VXie(b{@IY3Bo!x1?YF<*cs=U-Mul0T5=}4p@Jj+~xlL z5fbvhkZZbtrHD@*A3@0jI;gtFKyCI{m)Q4s@x?RI09?`ec_@3 zu~GO&_B6W+(1d|5Jl}wOgww^+Rs{8WfG#gNSVn{&czmD>Vkq>_0Fpck@P>tWJ;1x| zZ+R&JoUnjb8Kbv9 z*g?V|X-9_R+ZOV#$H6-atkPyGvej7M$w|;blAd9csz57cxO?*B_4P2(C7w$eCDOs2^2F zZyYZxi;05+t%Evv`?=_c56|*Djh?T^qut^ADRe!4Znw|1jYQXb+w1OaID9xS86^(C zPoO_v+(RDU+N$TZ%_-#_q{_~(ZdARlP0!X>8)U!jUS$<7*Fbm5`0u~u4TSU!j^RYK zL31uvoL63tTMNV8dFYP!lEzraWz=4t?rum~2=*xA>rj8- z`aRp7>mH-vLX6j*%lv#hJ8!)-08=?c0on$}!VIpluxAZ!O-HEC9J#i8!v{(tb#c8o z!f@MIUWg&`hVMO%dW*Zb@?|f=N@N0{$fDKvdxyvO(|=2B6wYr?ue*8fe!hhOZD|qb z&eqj#sYZC7z{QQo!Z&ubYT^Zo-LN4sj??`R6j&6LMWSQMP{ZHkEJUdArO?DJ_!IK+ z4Us}G*4bqkQ9Cel+ze4&yh6&D`m@_8N>F%O0#&*DxER4_l!;m1)v$$v{;Th|c>+E@ zzKS*J-2xm#SeS?wx(?rWpfI1F_lOgCNYJM8qUObQkKAd?MYfsg%~)uD!`A3T1*fC1 za$D<4VWhRS4Q^dZBKLQ_X5{kuv;*4<3OkNx@Cu@j6gkEJzMT=CosgbS{ic9irdpO> zsj$I_(C*=xrH0zzA&IfTLohc)=zqfxpJM3Yuse8{W7qbKd{O!GCl{rIdhw`K-`O~X znbmIl$Y<;)nXq7z^Yx=mBG&um?`a5BcnRmYyYHhz`Gi+g{T9l|{$;j9LbxyzAqklZ zsD^7#-9E{P2Ct>B;qVX7;iEYk@SDR^8776%&@hk2qgsHSf74S zr&!v!?ZO;ZIsQlZ)Pr73uI+hu9TocbCmsS>!;LPq0G!~NYv#sc z1c6`8P~XIlYKH@H$xZX>e96QEP=+yQ#82N3>%cu(V(48P?}K`cz~9Ev z`p+eH5k=<93en$c#*VmNg*~oQFKwUK3K8F87s^7My0Z{1y#yv-`tLLoXLMJe+g=Z@ zrUWl5F35Vtw@Ll}#+i!Pf{@}N?FaX{a)B%A0GT%lfM74E2?zl|c)iEb$<0%a_Va8z2_do%|12>Qs;VysLw@W;yw(;~1vqvGpU0cVbQcC{D0Ih6#D-doM<+ZgxGHd$X zQw*w+9n|4zs-O|y9N83vJuq2Fa+in%P!xfQCq;r%BE4G(f z2t(A;3ZM^JXtTA1i70mr6g{r5hQBX0MMnJQ%KY)Rc6}FLc1(C+YHSTJc(do;tej-idBqkr>76C4G3P7?1_{Pqcx84cxdbA78c zv77&;Ik5E`v3CspcACOi=u@$hZnxQX;9Jmv*ctdyWq`GT=O7CYK7V=6TrVV7+YayP zP<0EB?N=3Vktf?9uy{AAs-C}d`I0~PTZ;Z;>{74SsT99q00+^|q{+0HG*{gw|*kq58$#2RD&i%$^EAzvNBRFm5sx zXD;4>FKRn$+q^+O{%LM>YqYE`70IaVY*)XD1!ePj{G7;i*}$CpPliy<*E*M+-Fj$b zLxTQK>+&MdWHH;`O194{yDT68edww?|IgdOt6VKnKfHDx=w)6$_%Gl3$|iggiDtAkxXJTMJYe9{fyuIb1mP_PNbZYGER}m)-hc^ z?)!~b;ZL2Up+&EJvO~_}-vx-mM37BNFFv@FVo`IO$yj0Vm=pz1Vz~?T?nJ7%M)9#+ z;#j}z2>IhE%>H`mi#&)E?{aJ`+uF2Jnk^7oS{0@Fa?1g!3S<95Ir<3fz&I~<@!@XhnQyW$PW&)8jVM((wZ%2%&7Hp(xBLmroZG73ZNT zc3TsOX$7v*fh5b$nl`&YV!}FN@ZMfY4DSpd zNo&`jiIIk&_70n)ZoO+0{ygAdttVa>#qcQfy4h|;@p(ipQs8iNlp6nu2vt{*H;cp3 z&pV*!W(Wl9H>U{~%EMG12g8kwBK}ug(vzC_Ofk#K-p$JkOaxD%dEN+GdGkWnqPt2Q zepJzti^a5G`RIe(hT=m(Tr8 zJm=C_p_-Mcppm4K7Y7%t6ze4Q+#SOF{x>+!z$jTp15d9a=soGBc5(J}Q^T@qS}!yN z+pu&>Um06BhM8mB)&i)Gu_A^j$pJ|+0}lMN+hnkEAH3i;7w=p03ammImgPfnV2v*m~IV8*x zMrJ+Kb*Gt!Cp`4a?Qfol()B7d0~s+E+32JOce>h+Cf%j1CTN^cnQwVo>eH5x+FuCSwS&;v+e2&f z1IBwq1auM`C?l|(u}X3ojZwX0g5<0Pw)nGfn&w&E z@d`WnzC=IeGLw?gx)YX-XM;gz9U_sK!<0tWM!VhLmLjtl9;KD?W;XGvtG1)YQ;}TJ z;_zW(P>l1AAV@SI<3}OGOR?$>DK|eKL=APsV8}_d1$Zc?&-^m9w5h0T|3Q}Gh>VRh zPjr{AJtEV;UD(u)-->|J8Lp$-QZlqLpk)x4++eHNlA9YxFmGK%PUi?KVUvr{Otg%hm+-iLC0L8Dj(B2l-Q@wn*(NtO%x`~P!@PGwOw#d-qXsvlp)nZbRvdat-qg& zvWchK2Y*}%g;6+*9Aj`a_4H0tO|K2%OMjiZ_O+xMvrU+f3t2A5e2@}QEoeL+`-*(s zHgP4|B2+)f6NC+4_*>*C@)o`8yoKx)FBUT1;;-Q}m&a!=%pclh3SoN|dk$@|>=cBl zq)F37J0AWN5bSK+9Qeeo(~-PuYX(F%uSl+tWS;fE!oTs+l>K6=tEK@r0V;e{+x+|) zz0gHIO;UR_c#`2YR}@1+SNSZ&WJP@?SDws4wIiIC)e16>xNdq67`sh2(x1qfF{Q<> zA;N#_cXB7jQ~a|O5PugHSCBboPp_M$`Xu(UE%YFJa}Cq~CYSsfk#t^_h*Aw{F!cz= zE151li4+!rmzWYcq05|=dmU#FI-p0{D#?#yR9*$CoaGZ#q&CtgDKU>srllB!y*kV> zlrk9-l_^5sdXRidiuGd1YlNO2h`7<`lOSpZQu;cT8PN-Bb0yc_@zR@8ue^HS=k7x% zd-sZ3M~s$saMyGu6lx%DjELA9JSn3Ie<4G!-^nevY$y7pF*ru`J2*y^7A)?w@ zj)IgQ>jB*Szf5>~*PG_Lq*EghoJVSnh_JIGU>dMiX?n6nheAr>aqbdyz`rPo#Xl8H z35|gZ_gtzP^MgvB({^I~d4$gusb!BNczg1v()pe4OanfZ@O+(8>6h#4eL3~not;T((iR+=RF|qeNdo0 zQ(*uXz}eDIY0o7jLVYRaUt!fR8`(nE)WjIg_jxx*QZ7uVW#~FboO*?T`~#ki$f zNhZ$#p(sb&LLkbyQlWzlscz~RG-Vx`L0ROLF>S>ORInt7L=PffOOQ)cK_LvKKaLlQ zk4H7}EVwo3r1G#XP06CZWDw-E!5&L}9bFP~%s(_4rj1YhPCXu$Y?RMZ%uyiS2;JA> ze2r7isfLCUYUQu|)c1XBS;mQkc`z-y_iJd%r~GzRA|wAa(#NqMoXbCyagwF%o&pMC zEoB-TE%Tiznpa}}1Slu5C8F8x7Tx(>S+?q48gYm}rt&Q=Oe_<8Db|^}tD;JIh?V@@ z|9wCAZ_n2$(3qr}O=TIwqepth`p+ob1*_X}y!b8&Y04A=@{++Hb&L90N;pqqF+Q!#qp_xK6tP-IG4Ryh|fWdul`kb!`mN^ee$fTWZ#+0VtIt3gUgw&>z?2dc_3pHF}3 z81c3tSTv6_6Ev$R9DZ)qRr}({D{(X%+t(8tmTxL27~sdRSi>b9)`TS|L~j`p z{TRX+nD40bV2P=gA1O`M`%_XibSy$gR8t&T`c6NihJ#Mjw4<5`u}UkA&3$+^`?0;= z2{)I`F;9^xS@y9qlCnn$yU<+a*UAPJF2T-m*>hccq9d{Ncc#iy z!2A<^ErB3R#g{|Opr%CG^dNTX`(N>kKH@RNRg^M?nNd5r140sC{BkEGTqvicGNJ_N z!0=fj?7Vy8k#o9c4yR2cJCiw+5ryvxV+lP5O7Vy2(my#v3+V40*k$F}s4Cxf2x*<| zSSazvZ&MOAEDL(a)oVIu`iyw8sXxh^56-7nTOn4tG$2#`?A?BOTPtZwK%8}TRQfGx zt;d#dNL*5dJzPaDyw{o}nx|lO&9zm7wpmxH4dfkMvu;r`Z=NIHlA2$-MR@ zlS|U6?@u4M*K$M}wKE1++agl>f+Wl{6Dzv^5i+nR&6XiD(XyG0Yukt=DwU%oZ|@)= z@k{+FysT%6r$zWq7vcGdie`S#P&XtyCK0Fe1ZuCz(HYGuisyiCJ-MjXfLaVm5}Wel z_#sN2xrrTqrAA#v{)-C9?a5P1(Y3A0`^^!ERBiPo9cLwE%wZ496{dzHPK{Hg+cBY} zBdE91S4*6p;Yn7*3J#Cv&q1OgIGQUxmQXdEN2Qgkc;b01ps-w==GzpG^ff0XYGT&!%|F51IgVFu}wY&CoMYt zv_C`pXhej$AtqwRtDqJ4mDBKbDakaK+Z@SbmgiK0L2%?e-%SfuVOfvt3-hT^zU0c9 zz-F1mE9}B~h87DIGcr4V!|8Z|%X=@Q9wTIeS->-}6*tPp8-$?#hP+sRwQ{F}$2IOb zuj#22m$wV$h&l8lpM5G<*`?F1F;~q&ktqv1GgE!#r~IkV1e&-I>%fN!JIRYx8(1E6 zV3GR8kY!`lU+P7EM4S5FO<+(^@4n0VA#U)6qvSM6Q(?#Pew{P?{hX(D_m(!zI;HJr(`5bFuQs(oO2I;aE>8nuasHprIPD3 zb6CMj#?^vA3FYutwtNNOX5E=6ezG68Fy{^~P+A}vGcLJ%3j_A*(UX3jRN>zw!{{Sz zvBtAGRP=2(O6oe8s)M2#xz(v6zt6|y)ruYnZ^LP{1!NWIjfJ&&oWkp)pLt7gshVNz zD}HEaEN>~`^n^kRC-*1Bwu1?$Gth`R|2c*t@n{~w(_Yt&+SS`KsP&DhBbg2aWPUDJ zBn~iS8)(Q-&)f0hY6^y>4}-ZG$KfCDLo4|;d0yQfKc*yV3N1J5RV!(&x`-$mDQu%q zfC8sZ+w{p)=w}9gJafG7x9lZaunomOzj=@E)@TQ>!TG-5!^M zmZuG>w*|-x672wXpa4FON-`Gq)y7`%JoG4z2qkf9wN@Z&;!?&5d)nB5!*r8iN_|lY zlGI>bIX0i{UwW!Z4a~iyLbfZHCN0lm@oh3yy>S}a2?j}c7%9%Uu|y>s>8ObU zI`ywAPRTl|$@1erR@w0)Sx~L-e*1fJ&BY1so)u;Xsmq%Nu-z)ptrit+w+BiLxLwo2 z>iHDA_-e!Wv^~#{-IUVU3f)wcvNnEh_)TqYPGUJNfXZxR#Wt}(LD`T@^($U%)x-6^3m6L@JbN$tvA-jz?fn8PMQ&O!bwXo}qN?%PbhLba_MZ+)1NeI@cq^Qy>Jtci-OXWr~bMFcDVIKxt#TH#2H!W8sf8__aE2^8okxc$WN8`&Inl-u0%8p2|5A z?V!a+*?MI+wcyhoYz3SWdDoeZULzVkT{aNyp8+Q9fL^%H8z&vKrI{r;%s?tqkRnwyi6R^Wil+M;+II+x8##VsD3?7ZT2 zT$!$}ozQ2eZPG75?UiFv0uPN`*2}bThGCqD9clgGi?7nJ!I{C!~i^hv)Zo$3mWN>A^4SU=Nal_KyNWezh1s+=W zLLpqx&drZzfw{bWvCq0(5&ays+#Ym#cyyAr^6M`Q=5Ufrh+a+a-TERf;S_R7O8oC_ z8j^if+hp=0YwZTh{$+&S+*jhC=Nfo42R;?9+vkpk6 z^(q^bMy{UTgx~8bBszyaC_Qap?PBaYRT<;gjw9D_#g80O4Xx!&JXWCMMl%JdaNOMCdVn$(u{qG4Y!<@IOz#NFk>iL|a4d>W4Wf=lU7Qmg=sur?EhY$zUQ z@k1PYTzQ#Ij8XnnbE(BsZHMu#0@l3D(!q|*9rIw&ZLI6Qra^{zQ`-_z^!-ch@Q**A z+bi$SstWsJ>G6yQucOaoScs(vOc5~$T|%@Li`8OPnTLu78fQC>2UI;R9eKxCB8pb# z1q3ooL~u1r;!}+7&Q&k8eKKA7H1he3=g^0{y0xghGKY z$%xN_hdmM8&@*spJrWvalk#5K$Sx3Xv0N@Q8kR*XLD#K?=57>+QnU(@_Q?=$oY~53 zl-1^PkjbFL=Si~tI+2Q2JG(G>_1K^yyT+zl=^E+}`j~}qMt%r(QuNN3@z;v8UET)p z*k5=Rf@HPquy*MTx(2I8aS>BBG$#XPNptdg92}Ln$YeV`^2#_y(`@s>g`se*?c2k# z#oq@ovMX;~t>z$=dIY*wMDj+CGuBbv*$WJCKT#c_0}iwdH`WHdp0I<^J%KoP6~mq2 zG>bt6qr3io0Mzj3q>JD9&Xoe)aCwvNo<8$|LjGlrIE~5=wtbFC zRe_)UMeMnuW^*eJ6-B4Vby|2VKF?6N!+a2)wtRYi*15>E`{|6tgvMuAX))x`O1M{F zUH2JGoV3myV0q3j2;iuerLd}40(w6;UCl-;E!?Yxc=N|(MBklCj%-kzpVrd_Df_?L z&Q%znjkJd#m45&9oi$Yyj=Vp?49kVr_4bRI7S0M+j%tvNR*2?3d(4kt%XLl(XkOFw zR07x3nxT7h8`d?v%Dn5}8J7=?=wVZWL@_PZB&LFX4cWAOK0wp|OTxsireJA{|3c(_ zbP!O2D3PcUyJB%!PeIon900Vr?+Yhxa_o4|>P=Ok4kxFbCR_`vH|1&)jfXPOcnW{k zku9G_M0OnF5!<1qX(@b|C~X_A_^s#Z!x1#`MNm0UPK@qX*jv`oMslm9kvyzbwnWm~ z_pUc0HMfMBvUu=~dIiH&^Y}4vA;b2T|atKt+~Q6Xa2-p z_~^k3I`iBzvV)z%pneP$VZg&3ywB-3fM??N3%x+g3-qtu{Z($c=qWyIr0+eroKqaM zHl4~5G$h}$X|EITl=Gj+uBrAyNrG}sb5%ZFVk@p3Tujs-mDH;l_p2!8PvLNx zQBL6UtBqrIPTzbdJE`?jgQ&$=;$X(iow>2Ift-z(qB@t-^{NW5p!kEu4gbljC4mw3 zExHG@rbbgVj7M^Lb;9-`=VGvi7g>&1IreT_({a}c#(tF2=eCYDBfe3&LC7LXWCAl0 zxR4b{F@XlM1P(}opN-}7^e1%16rggeA3OyXXr+xS(|q1?4^EvZOR72-MExnoAe=bs z2HjD1PShGtb&(J~rq|gBNDl_6y2-vavgGrh`#S8a_>yeHUF0fa47DW(`8<>DM(&ws zOI(i?PlB>7>Z_Yt{mT=b#$-^40$jH|}Yv}C`D)hXdf z5mZjV=Pi>S$&;4^tw#4p&b9njQ};_Trh)HWXdNCPW@&_de<}BPo3FZ5#Pws0wG{W! zQqTI@>x4s5K2|^fFVXqMd}d)k+QT90gt^|+{0ur*tH9N90BMzq-nNW%&|L1}_l5|f zTdv#$Mv=PO?8l7|)nuG)ZEP)_Z|>^fHb;>CMIj4KpHEz9k@cL)XIXU~-?L5U-p4o8 z=5th)ns?Qb)f(yA6$W~a*@#8FVtA{?*;05?^kj?E3hAX!KnX33?ZI}uV=rvC4GMiu|<}(gYGB#OY zVd&$*y`;QvoO4MlO%|^|`Rh*LrK#pwZ6eotTvO|hUlW83B@{lxXWHeAT{Vh@SZNzu zp$yu?!jIOXtUc6CGr-A>h-@f6*da{8))^-7Ifi1nvd=9lM_V}Hh0O)3mVCV0Jnx~aPrza$K~M7FDY zFHB};UjCftgU50%)~ybou)00KwyU_WzT4ml>Q7Wr_3YR98<_X&P=2GRK&DNDo2YaO zO|{ocO5i0d@C#!=#*2M;+Q`-K8~*u*wwM_%rY9?y8m|$b^yh^3Pl?pNYP520VdfD> z*u7V4jBv{LM^sGFB&z0L$p4idJ9^sd2ERr%)Qz=07U_yLU>#{;<4!6ayH>P`XmDDT z8vjE5E)SR}mx$*6I1J6~(ja9{SG8OCZu%%gu%svWWbEJ3RfdW;yLafZnjbw@A$hcs zZ(q~c1&U5?23@F<%hI)HXM24kna=W~GZSO3m88IFnNsVccqO+C7@b%U7b{VO#37;` z7cawt*8ZzC>Oq%9lS0>sCaP879AwUwo;_i0z%{2d6fx}o9#3sE)|2E z97YhwSQV&ZRrdt9cL|RP{Gqv7DUL2xruW+7%@wcI8A6;Nf7Nw(3pg*cX&kQ-A@Ehl zMf?WsQ%NsVNl+zU!JAj%HE2^TJz$lg6lbCe`XltI;b*lsDY27Tk_ zfUV}NO_aK0DAld9;`5Et!(dca4m`EXvK~%h!;rW!tHJ(8=vbC%$=u60s;lB*@<0xJ zhpL@`(ujpRf43;ID&9g(SOqri@=j@*h2iG~Mm20XHL;{hr%2q)#cD3W!SlSvoetbi z`jn6hxH0mIx(4s*1q&zBK^@kCuz!(%3-e?5V^K{j=j%7~`t5VVmMRIH0ELDatqZ$uG zC+gxx2h2kPLJDRwjD;9qD$-vg_=*gkLfuq4!2}|P2VBN}EiUE4DzmtttFLEGlX!na zne8j8=PzG=r+!6YY{m8jZD!j>P9^J~RGPdJ)4C`*G8Yv{Z)0|gx=oB(1u}Q;fPT`W z#74Lu+`4Je-6xxRo6(Af&tqz_<&B*gX0SJGK2>Nre|9}pi*Yn8rB2EGxk>DnmGLd5 z{#TCC!JRHtuYFZ=6?l;nYhrH^9Yv%%b$;M6SjRoGjN*X_y5@1!<+><`LDi8#NkLpZ z@vL7mKFvKOy*|E~Vsf@ExO};Rp;e{UL^`1`?4+8&s`R>*=Q*`;neN|Ei;1ScMpFz{GKHv)E=FVi%k`(}l@q^9a6r%yP?3$?2Ar%Y9IWXT)^lPjpAL?_uPR$W6x?WbQj zyv9V>>12jA(_zaw)TKHic8cn}b~Q&6JwU!R=MO%5^N23_xnv@t?cFuE$*y&0`qTDpGsKro*G-N3tLpW^c{SB`g~92SJ|C5l9UlY{m#(b&7q-#>x22RlwEX7^J4D z&y&g|lICUNYnM;VvPA^!qbDR%j(X!BAicp904>AwMLt$FMXj^ODIQE2_ZO=buL(6! z!a()mxbT= zS({U%=}Y!fVCprO57KuPTRM5OPB6*nfa-DtRz()|6&G~Ut7*@AqqSZ*T|k z$y=kb!FRQpXCg+4V3lLT9tgq71Uk0kE7uCH=Wkib^9s3;>rRVH8xA^CJ{=BvVuIWa z)_D3gv&y~uk{AY~J|@?Z` zR32^RzTR(k8AJa{%h>(ey9^$~!s!qST}Pkfw(=~Q%A$&8AY^4nfXu_E>_?KIM!?jd zei7-*7kxUQ+(bt{knnRh`MK;p7yqUT?4^SP`K!9*Et{`%$!U}7d2XM9%2Ij~KFGH0 zgU<^a(ry689(nx?*Dsvm6$GY(g&ZTCz*>ybF>Enl<0LIZ9`aG;XdRxmAbnIlQ!Y8wZ)I zzAdJLKIjDjd+*i}h-!A3(S7nJG+6_6K0eQoA%4k*w>~0j)v&?Klsk+oga=+@Q~Vf{ za&Zc}L+w0B-U)z##Kp9{CacWW^IEbk?$Mhg_p!hONBa@?uwU}cM@<`0a#tcoUHLZU zz+gZ&b>}Q*qUBwfBI>@QuAQQQ!Sdv>luP0@u7L=aI|dqpnyu{L40Y3Gg;cIZ+Hn1J zDg(NE<ZMCzCA7`vQE=yJgw$@eSQda2p*o;(wz(dkOSc z_a4$74k}ma8ljE!J%>RVtl79)+ej0tY#Qm;D6;``ISm?!C9A$kGblP!mkHaVG(C3+~Vn&g87humYJ!+5_hJDKB7(J${%_$R& zK9rdjwj;D$Z)uUGFV$8pzGDX4hk7NZ%Fh3 zB_&SOJtx4q218VzNa$7$#`^HH2O2D{i_`3U>-%dU6}ym5c;{hQiJ z87Xf@33zoZK*ycc!?;~&aR1Ivs9db((wG@$#gpYVQcH_*RQQS z?Y3s!K`ZOcwg#i#;LBEalIOiGpy&W)h7=s?&u3dHbhoAZdp3UY>}2wyvFZNFajTbY zJ$&(O@7)`5@bT62hw#xbKc2LX2mObz(1*_-{&@06JQOcKe0;t8@wxYc+iz+t|2!*N z{Yg3-o#g!t9dBDF`DwLzXg#mA{^N(AJ{?@D51^mnATO$erjI`y{7!BEZG0@-e#svj zEsHf`#+ugl4Zx5eGesgc#9$y(_c9{=*TjR;#3+NKK6WN(u`i*iVg+dr( zimW8mM-lmI5OH+#L1FfgojgulnAvSmGE_`mGF7V=Yb z4m@JOw4=Otju?l-c(L)|enWq7MiCoZV-Wq*te9^7oSyMzRa^i3M{9aEy?Gy==Os}j z9(ZxPo%jO(#)DP*mwxv>;rmJAg`p~ynVmTJ{HkG{AJU>pTvp(KzO$~ zh b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + + +function runTest (t, doGH) { + var reader = Reader({ path: input + , filter: function () { + return !this.path.match(/\.(tar|hex)$/) + } + , sort: alphasort + }) + + var props = doGH ? pkg : {} + props.noProprietary = true + var pack = Pack(props) + var writer = Writer(target) + + // global header should be skipped regardless, since it has no content. + var entry = 0 + + t.ok(reader, "reader ok") + t.ok(pack, "pack ok") + t.ok(writer, "writer ok") + + pack.pipe(writer) + + var parse = tar.Parse() + t.ok(parse, "parser should be ok") + + pack.on("data", function (c) { + // console.error("PACK DATA") + if (c.length !== 512) { + // this one is too noisy, only assert if it'll be relevant + t.equal(c.length, 512, "parser should emit data in 512byte blocks") + } + parse.write(c) + }) + + pack.on("end", function () { + // console.error("PACK END") + t.pass("parser ends") + parse.end() + }) + + pack.on("error", function (er) { + t.fail("pack error", er) + }) + + parse.on("error", function (er) { + t.fail("parse error", er) + }) + + writer.on("error", function (er) { + t.fail("writer error", er) + }) + + reader.on("error", function (er) { + t.fail("reader error", er) + }) + + parse.on("*", function (ev, e) { + var wanted = entries[entry++] + if (!wanted) { + t.fail("unexpected event: "+ev) + return + } + t.equal(ev, wanted[0], "event type should be "+wanted[0]) + + if (ev !== wanted[0] || e.path !== wanted[1].path) { + console.error(wanted) + console.error([ev, e.props]) + e.on("end", function () { + console.error(e.fields) + throw "break" + }) + } + + t.has(e.props, wanted[1], "properties "+wanted[1].path) + if (wanted[2]) { + e.on("end", function () { + if (!e.fields) { + t.ok(e.fields, "should get fields") + } else { + t.has(e.fields, wanted[2], "should get expected fields") + } + }) + } + }) + + reader.pipe(pack) + + writer.on("close", function () { + t.equal(entry, entries.length, "should get all expected entries") + t.pass("it finished") + t.end() + }) + +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/pack.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/pack.js new file mode 100644 index 0000000..0f50994 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/pack.js @@ -0,0 +1,897 @@ + +// the symlink file is excluded from git, because it makes +// windows freak the hell out. +var fs = require("fs") + , path = require("path") + , symlink = path.resolve(__dirname, "fixtures/symlink") +try { fs.unlinkSync(symlink) } catch (e) {} +fs.symlinkSync("./hardlink-1", symlink) +process.on("exit", function () { + fs.unlinkSync(symlink) +}) + + +var tap = require("tap") + , tar = require("../tar.js") + , pkg = require("../package.json") + , Pack = tar.Pack + , fstream = require("fstream") + , Reader = fstream.Reader + , Writer = fstream.Writer + , input = path.resolve(__dirname, "fixtures/") + , target = path.resolve(__dirname, "tmp/pack.tar") + , uid = process.getuid ? process.getuid() : 0 + , gid = process.getgid ? process.getgid() : 0 + + , entries = + + // the global header and root fixtures/ dir are going to get + // a different date each time, so omit that bit. + // Also, dev/ino values differ across machines, so that's not + // included. + [ [ 'globalExtendedHeader', + { path: 'PaxHeader/', + mode: 438, + uid: 0, + gid: 0, + type: 'g', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { "NODETAR.author": pkg.author, + "NODETAR.name": pkg.name, + "NODETAR.description": pkg.description, + "NODETAR.version": pkg.version, + "NODETAR.repository.type": pkg.repository.type, + "NODETAR.repository.url": pkg.repository.url, + "NODETAR.main": pkg.main, + "NODETAR.scripts.test": pkg.scripts.test } ] + + , [ 'entry', + { path: 'fixtures/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/200cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + 'NODETAR.depth': '1', + 'NODETAR.type': 'File', + nlink: 1, + uid: uid, + gid: gid, + size: 200, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + size: 200, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '', + 'NODETAR.depth': '1', + 'NODETAR.type': 'File', + nlink: 1, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/a.txt', + mode: 420, + uid: uid, + gid: gid, + size: 257, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/b.txt', + mode: 420, + uid: uid, + gid: gid, + size: 512, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/c.txt', + mode: 420, + uid: uid, + gid: gid, + size: 513, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/cc.txt', + mode: 420, + uid: uid, + gid: gid, + size: 513, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/foo.js', + mode: 420, + uid: uid, + gid: gid, + size: 4, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/hardlink-1', + mode: 420, + uid: uid, + gid: gid, + size: 200, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/hardlink-2', + mode: 420, + uid: uid, + gid: gid, + size: 0, + type: '1', + linkpath: 'fixtures/hardlink-1', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/omega.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/omega.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/star.4.html', + mode: 420, + uid: uid, + gid: gid, + size: 54081, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/packtest/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'fixtures/packtest/Ω.txt', + 'NODETAR.depth': '2', + 'NODETAR.type': 'File', + nlink: 1, + uid: uid, + gid: gid, + size: 2, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/packtest/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '', + 'NODETAR.depth': '2', + 'NODETAR.type': 'File', + nlink: 1, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/r/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + size: 100, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/symlink', + uid: uid, + gid: gid, + size: 0, + type: '2', + linkpath: 'hardlink-1', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: "fixtures/Ω.txt" + , "NODETAR.depth": "1" + , "NODETAR.type": "File" + , nlink: 1 + , uid: uid + , gid: gid + , size: 2 + , "NODETAR.blksize": "4096" + , "NODETAR.blocks": "8" } ] + + , [ 'entry', + { path: 'fixtures/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '', + 'NODETAR.depth': '1', + 'NODETAR.type': 'File', + nlink: 1, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + ] + + +// first, make sure that the hardlinks are actually hardlinks, or this +// won't work. Git has a way of replacing them with a copy. +var hard1 = path.resolve(__dirname, "fixtures/hardlink-1") + , hard2 = path.resolve(__dirname, "fixtures/hardlink-2") + , fs = require("fs") + +try { fs.unlinkSync(hard2) } catch (e) {} +fs.linkSync(hard1, hard2) + +tap.test("with global header", { timeout: 10000 }, function (t) { + runTest(t, true) +}) + +tap.test("without global header", { timeout: 10000 }, function (t) { + runTest(t, false) +}) + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + + +function runTest (t, doGH) { + var reader = Reader({ path: input + , filter: function () { + return !this.path.match(/\.(tar|hex)$/) + } + , sort: alphasort + }) + + var pack = Pack(doGH ? pkg : null) + var writer = Writer(target) + + // skip the global header if we're not doing that. + var entry = doGH ? 0 : 1 + + t.ok(reader, "reader ok") + t.ok(pack, "pack ok") + t.ok(writer, "writer ok") + + pack.pipe(writer) + + var parse = tar.Parse() + t.ok(parse, "parser should be ok") + + pack.on("data", function (c) { + // console.error("PACK DATA") + if (c.length !== 512) { + // this one is too noisy, only assert if it'll be relevant + t.equal(c.length, 512, "parser should emit data in 512byte blocks") + } + parse.write(c) + }) + + pack.on("end", function () { + // console.error("PACK END") + t.pass("parser ends") + parse.end() + }) + + pack.on("error", function (er) { + t.fail("pack error", er) + }) + + parse.on("error", function (er) { + t.fail("parse error", er) + }) + + writer.on("error", function (er) { + t.fail("writer error", er) + }) + + reader.on("error", function (er) { + t.fail("reader error", er) + }) + + parse.on("*", function (ev, e) { + var wanted = entries[entry++] + if (!wanted) { + t.fail("unexpected event: "+ev) + return + } + t.equal(ev, wanted[0], "event type should be "+wanted[0]) + + // if (ev !== wanted[0] || e.path !== wanted[1].path) { + // console.error(wanted) + // console.error([ev, e.props]) + // throw "break" + // } + + t.has(e.props, wanted[1], "properties "+wanted[1].path) + if (wanted[2]) { + e.on("end", function () { + if (!e.fields) { + t.ok(e.fields, "should get fields") + } else { + t.has(e.fields, wanted[2], "should get expected fields") + } + }) + } + }) + + reader.pipe(pack) + + writer.on("close", function () { + t.equal(entry, entries.length, "should get all expected entries") + t.pass("it finished") + t.end() + }) + +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/parse.js new file mode 100644 index 0000000..f765a50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/parse.js @@ -0,0 +1,359 @@ +var tap = require("tap") + , tar = require("../tar.js") + , fs = require("fs") + , path = require("path") + , file = path.resolve(__dirname, "fixtures/c.tar") + , index = 0 + + , expect = +[ [ 'entry', + { path: 'c.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 513, + mtime: new Date('Wed, 26 Oct 2011 01:10:58 GMT'), + cksum: 5422, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'entry', + { path: 'cc.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 513, + mtime: new Date('Wed, 26 Oct 2011 01:11:02 GMT'), + cksum: 5525, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'entry', + { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 100, + mtime: new Date('Thu, 27 Oct 2011 03:43:23 GMT'), + cksum: 18124, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'entry', + { path: 'Ω.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 2, + mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + cksum: 5695, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/Ω.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 120, + mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + cksum: 6702, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'Ω.txt', + ctime: 1319737909, + atime: 1319739061, + dev: 234881026, + ino: 51693379, + nlink: 1 } ], + [ 'entry', + { path: 'Ω.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 2, + mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + cksum: 5695, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + atime: new Date('Thu, 27 Oct 2011 18:11:01 GMT'), + dev: 234881026, + ino: 51693379, + nlink: 1 }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 353, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 14488, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + ctime: 1319686868, + atime: 1319741254, + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 1 } ], + [ 'entry', + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 200, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 14570, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + atime: new Date('Thu, 27 Oct 2011 18:47:34 GMT'), + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 1 }, + undefined ], + [ 'longPath', + { path: '././@LongLink', + mode: 0, + uid: 0, + gid: 0, + size: 201, + mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), + cksum: 4976, + type: 'L', + linkpath: '', + ustar: false }, + '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ], + [ 'entry', + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 1000, + gid: 1000, + size: 201, + mtime: new Date('Thu, 27 Oct 2011 22:21:50 GMT'), + cksum: 14086, + type: '0', + linkpath: '', + ustar: false }, + undefined ], + [ 'longLinkpath', + { path: '././@LongLink', + mode: 0, + uid: 0, + gid: 0, + size: 201, + mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), + cksum: 4975, + type: 'K', + linkpath: '', + ustar: false }, + '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ], + [ 'longPath', + { path: '././@LongLink', + mode: 0, + uid: 0, + gid: 0, + size: 201, + mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), + cksum: 4976, + type: 'L', + linkpath: '', + ustar: false }, + '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL' ], + [ 'entry', + { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', + mode: 511, + uid: 1000, + gid: 1000, + size: 0, + mtime: new Date('Fri, 28 Oct 2011 23:05:17 GMT'), + cksum: 21603, + type: '2', + linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + ustar: false }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/200-hard', + mode: 420, + uid: 24561, + gid: 20, + size: 143, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 6533, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { ctime: 1320617144, + atime: 1320617232, + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 } ], + [ 'entry', + { path: '200-hard', + mode: 420, + uid: 24561, + gid: 20, + size: 200, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 5526, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'), + atime: new Date('Sun, 06 Nov 2011 22:07:12 GMT'), + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 353, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 14488, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + ctime: 1320617144, + atime: 1320617406, + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 } ], + [ 'entry', + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 0, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 15173, + type: '1', + linkpath: '200-hard', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'), + atime: new Date('Sun, 06 Nov 2011 22:10:06 GMT'), + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 }, + undefined ] ] + + +tap.test("parser test", function (t) { + var parser = tar.Parse() + + parser.on("end", function () { + t.equal(index, expect.length, "saw all expected events") + t.end() + }) + + fs.createReadStream(file) + .pipe(parser) + .on("*", function (ev, entry) { + var wanted = expect[index] + if (!wanted) { + return t.fail("Unexpected event: " + ev) + } + var result = [ev, entry.props] + entry.on("end", function () { + result.push(entry.fields || entry.body) + + t.equal(ev, wanted[0], index + " event type") + t.equivalent(entry.props, wanted[1], wanted[1].path + " entry properties") + if (wanted[2]) { + t.equivalent(result[2], wanted[2], "metadata values") + } + index ++ + }) + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/zz-cleanup.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/zz-cleanup.js new file mode 100644 index 0000000..a00ff7f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/test/zz-cleanup.js @@ -0,0 +1,20 @@ +// clean up the fixtures + +var tap = require("tap") +, rimraf = require("rimraf") +, test = tap.test +, path = require("path") + +test("clean fixtures", function (t) { + rimraf(path.resolve(__dirname, "fixtures"), function (er) { + t.ifError(er, "rimraf ./fixtures/") + t.end() + }) +}) + +test("clean tmp", function (t) { + rimraf(path.resolve(__dirname, "tmp"), function (er) { + t.ifError(er, "rimraf ./tmp/") + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/LICENCE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/LICENCE new file mode 100644 index 0000000..74489e2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/README.md new file mode 100644 index 0000000..8116675 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/README.md @@ -0,0 +1,17 @@ +Use this module to convert a username/groupname to a uid/gid number. + +Usage: + +``` +npm install uid-number +``` + +Then, in your node program: + +```javascript +var uidNumber = require("uid-number") +uidNumber("isaacs", function (er, uid, gid) { + // gid is null because we didn't ask for a group name + // uid === 24561 because that's my number. +}) +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/get-uid-gid.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/get-uid-gid.js new file mode 100755 index 0000000..0b39174 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/get-uid-gid.js @@ -0,0 +1,24 @@ +if (module !== require.main) { + throw new Error("This file should not be loaded with require()") +} + +if (!process.getuid || !process.getgid) { + throw new Error("this file should not be called without uid/gid support") +} + +var argv = process.argv.slice(2) + , user = argv[0] || process.getuid() + , group = argv[1] || process.getgid() + +if (!isNaN(user)) user = +user +if (!isNaN(group)) group = +group + +console.error([user, group]) + +try { + process.setgid(group) + process.setuid(user) + console.log(JSON.stringify({uid:+process.getuid(), gid:+process.getgid()})) +} catch (ex) { + console.log(JSON.stringify({error:ex.message,errno:ex.errno})) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/package.json new file mode 100644 index 0000000..b841ec4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/package.json @@ -0,0 +1,50 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "uid-number", + "description": "Convert a username/group name to a uid/gid number", + "version": "0.0.3", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/uid-number.git" + }, + "main": "uid-number.js", + "dependencies": {}, + "devDependencies": {}, + "optionalDependencies": {}, + "engines": { + "node": "*" + }, + "license": "BSD", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "_id": "uid-number@0.0.3", + "_engineSupported": true, + "_npmVersion": "1.1.23", + "_nodeVersion": "v0.7.10-pre", + "_defaultsLoaded": true, + "dist": { + "shasum": "cefb0fa138d8d8098da71a40a0d04a8327d6e1cc", + "tarball": "http://registry.npmjs.org/uid-number/-/uid-number-0.0.3.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "cefb0fa138d8d8098da71a40a0d04a8327d6e1cc", + "_resolved": "https://registry.npmjs.org/uid-number/-/uid-number-0.0.3.tgz", + "_from": "uid-number@0.0.3", + "bugs": { + "url": "https://github.com/isaacs/uid-number/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/uid-number#readme" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/uid-number.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/uid-number.js new file mode 100644 index 0000000..93f372b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/uid-number/uid-number.js @@ -0,0 +1,54 @@ +module.exports = uidNumber + +// This module calls into get-uid-gid.js, which sets the +// uid and gid to the supplied argument, in order to find out their +// numeric value. This can't be done in the main node process, +// because otherwise node would be running as that user from this +// point on. + +var child_process = require("child_process") + , path = require("path") + , uidSupport = process.getuid && process.setuid + , uidCache = {} + , gidCache = {} + +function uidNumber (uid, gid, cb) { + if (!uidSupport) return cb() + if (typeof cb !== "function") cb = gid, gid = null + if (typeof cb !== "function") cb = uid, uid = null + if (gid == null) gid = process.getgid() + if (uid == null) uid = process.getuid() + if (!isNaN(gid)) gid = uidCache[gid] = +gid + if (!isNaN(uid)) uid = uidCache[uid] = +uid + + if (uidCache.hasOwnProperty(uid)) uid = uidCache[uid] + if (gidCache.hasOwnProperty(gid)) gid = gidCache[gid] + + if (typeof gid === "number" && typeof uid === "number") { + return process.nextTick(cb.bind(null, null, uid, gid)) + } + + var getter = require.resolve("./get-uid-gid.js") + + child_process.execFile( process.execPath + , [getter, uid, gid] + , function (code, out, err) { + if (er) return cb(new Error("could not get uid/gid\n" + err)) + try { + out = JSON.parse(out+"") + } catch (ex) { + return cb(ex) + } + + if (out.error) { + var er = new Error(out.error) + er.errno = out.errno + return cb(er) + } + + if (isNaN(out.uid) || isNaN(out.gid)) return cb(new Error( + "Could not get uid/gid: "+JSON.stringify(out))) + + cb(null, uidCache[uid] = +out.uid, uidCache[gid] = +out.gid) + }) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/package.json new file mode 100644 index 0000000..5422996 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/package.json @@ -0,0 +1,58 @@ +{ + "name": "tar-pack", + "version": "2.0.0", + "description": "Package and un-package modules of some sort (in tar/gz bundles).", + "scripts": { + "test": "mocha -R list" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ForbesLindesay/tar-pack.git" + }, + "license": "BSD", + "optionalDependencies": { + "graceful-fs": "1.2" + }, + "dependencies": { + "uid-number": "0.0.3", + "once": "~1.1.1", + "debug": "~0.7.2", + "rimraf": "~2.2.0", + "fstream": "~0.1.22", + "tar": "~0.1.17", + "fstream-ignore": "0.0.7", + "readable-stream": "~1.0.2", + "graceful-fs": "1.2" + }, + "devDependencies": { + "mocha": "*", + "rfile": "*", + "mkdirp": "*" + }, + "readme": "# Tar Pack\r\n\r\nPackage and un-package modules of some sort (in tar/gz bundles). This is mostly useful for package managers. Note that it doesn't check for or touch `package.json` so it can be used even if that's not the way you store your package info.\r\n\r\n[![Build Status](https://travis-ci.org/ForbesLindesay/tar-pack.png?branch=master)](https://travis-ci.org/ForbesLindesay/tar-pack)\r\n[![Dependency Status](https://gemnasium.com/ForbesLindesay/tar-pack.png)](https://gemnasium.com/ForbesLindesay/tar-pack)\r\n[![NPM version](https://badge.fury.io/js/tar-pack.png)](http://badge.fury.io/js/tar-pack)\r\n\r\n## Installation\r\n\r\n $ npm install tar-pack\r\n\r\n## API\r\n\r\n### pack(folder|packer, [options])\r\n\r\nPack the folder at `folder` into a gzipped tarball and return the tgz as a stream. Files ignored by `.gitignore` will not be in the package.\r\n\r\nYou can optionally pass a `fstream.DirReader` directly, instead of folder. For example, to create an npm package, do:\r\n\r\n```js\r\npack(require(\"fstream-npm\")(folder), [options])\r\n```\r\n\r\nOptions:\r\n\r\n - `noProprietary` (defaults to `false`) Set this to `true` to prevent any proprietary attributes being added to the tarball. These attributes are allowed by the spec, but may trip up some poorly written tarball parsers.\r\n - `ignoreFiles` (defaults to `['.gitignore']`) These files can specify files to be excluded from the package using the syntax of `.gitignore`. This option is ignored if you parse a `fstream.DirReader` instead of a string for folder.\r\n - `filter` (defaults to `entry => true`) A function that takes an entry and returns `true` if it should be included in the package and `false` if it should not. Entryies are of the form `{path, basename, dirname, type}` where (type is \"Directory\" or \"File\"). This function is ignored if you parse a `fstream.DirReader` instead of a string for folder.\r\n\r\nExample:\r\n\r\n```js\r\nvar write = require('fs').createWriteStream\r\nvar pack = require('tar-pack').pack\r\npack(process.cwd())\r\n .pipe(write(__dirname + '/package.tar.gz'))\r\n .on('error', function (err) {\r\n console.error(err.stack)\r\n })\r\n .on('close', function () {\r\n console.log('done')\r\n })\r\n```\r\n\r\n### unpack(folder, [options,] cb)\r\n\r\nReturn a stream that unpacks a tarball into a folder at `folder`. N.B. the output folder will be removed first if it already exists.\r\n\r\nThe callback is called with an optional error and, as its second argument, a string which is one of:\r\n\r\n - `'directory'`, indicating that the extracted package was a directory (either `.tar.gz` or `.tar`)\r\n - `'file'`, incating that the extracted package was just a single file (extracted to `defaultName`, see options)\r\n\r\nBasic Options:\r\n\r\n - `defaultName` (defaults to `index.js`) If the package is a single file, rather than a tarball, it will be \"extracted\" to this file name, set to `false` to disable.\r\n\r\nAdvanced Options (you probably don't need any of these):\r\n\r\n - `gid` - (defaults to `null`) the `gid` to use when writing files\r\n - `uid` - (defaults to `null`) the `uid` to use when writing files\r\n - `dmode` - (defaults to `0777`) The mode to use when creating directories\r\n - `fmode` - (defaults to `0666`) The mode to use when creating files\r\n - `unsafe` - (defaults to `false`) (on non win32 OSes it overrides `gid` and `uid` with the current processes IDs)\r\n\r\nExample:\r\n\r\n```js\r\nvar read = require('fs').createReadStream\r\nvar unpack = require('tar-pack').unpack\r\nread(process.cwd() + '/package.tar.gz')\r\n .pipe(unpack(__dirname + '/package/', function (err) {\r\n if (err) console.error(err.stack)\r\n else console.log('done')\r\n }))\r\n```\r\n\r\n## License\r\n\r\n BSD", + "readmeFilename": "README.md", + "_id": "tar-pack@2.0.0", + "dist": { + "shasum": "c2c401c02dd366138645e917b3a6baa256a9dcab", + "tarball": "http://registry.npmjs.org/tar-pack/-/tar-pack-2.0.0.tgz" + }, + "_from": "tar-pack@>=2.0.0 <2.1.0", + "_npmVersion": "1.2.10", + "_npmUser": { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + }, + "maintainers": [ + { + "name": "forbeslindesay", + "email": "forbes@lindesay.co.uk" + } + ], + "directories": {}, + "_shasum": "c2c401c02dd366138645e917b3a6baa256a9dcab", + "_resolved": "https://registry.npmjs.org/tar-pack/-/tar-pack-2.0.0.tgz", + "bugs": { + "url": "https://github.com/ForbesLindesay/tar-pack/issues" + }, + "homepage": "https://github.com/ForbesLindesay/tar-pack#readme" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed-file.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed-file.txt new file mode 100644 index 0000000..ba0e162 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed-file.txt @@ -0,0 +1 @@ +bar \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed.tar b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/packed.tar new file mode 100644 index 0000000000000000000000000000000000000000..35fd1745182fd4c3c4572a7d11e0d9f2f41658b3 GIT binary patch literal 3584 zcmeH{K?(vf3`KjCoIsPdnVhF1>cYhgG7ItaMy)WoaTOTwchfe|B)s3Bxg9R;eB7tN zMU~Br5C~06%Nc|=-cm2n9-7U8z1dH%5{R?&dH4oMGH-ABi yL%KoIHG#3+*H@hXjKIhLr)k=T|24n-pMCzr|M8#E=YD(E_7jX0PWO03Iah41>hVd7f>@lNzOAX*jS9n z6yoU}#YM2$YLcfTRTkX(XB^`12+V^V_A=KiO0 zKek7s5rQoBpML#Y?%7-;lMswHl_$Y|&HKO9x{dv7{OsQh`(H!<`vd?0`||=f!0QwM G4gdh@=127a literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/bar.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/bar.txt new file mode 100644 index 0000000..3f95386 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/bar.txt @@ -0,0 +1 @@ +baz \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/foo.txt b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/foo.txt new file mode 100644 index 0000000..ba0e162 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/fixtures/to-pack/foo.txt @@ -0,0 +1 @@ +bar \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/index.js new file mode 100644 index 0000000..85b5f41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar-pack/test/index.js @@ -0,0 +1,67 @@ +var tar = require('../') +var path = require('path') +var rfile = require('rfile') +var rimraf = require('rimraf').sync +var mkdir = require('mkdirp').sync + +var read = require('fs').createReadStream +var write = require('fs').createWriteStream +var assert = require('assert') + +beforeEach(function () { + rimraf(__dirname + '/output') +}) +afterEach(function () { + rimraf(__dirname + '/output') +}) +describe('tarball.pipe(unpack(directory, callback))', function () { + it('unpacks the tarball into the directory', function (done) { + read(__dirname + '/fixtures/packed.tar').pipe(tar.unpack(__dirname + '/output/unpacked', function (err) { + if (err) return done(err) + assert.equal(rfile('./output/unpacked/bar.txt'), rfile('./fixtures/to-pack/bar.txt')) + assert.equal(rfile('./output/unpacked/foo.txt'), rfile('./fixtures/to-pack/foo.txt')) + done() + })) + }) +}) +describe('gziptarball.pipe(unpack(directory, callback))', function () { + it('unpacks the tarball into the directory', function (done) { + read(__dirname + '/fixtures/packed.tar.gz').pipe(tar.unpack(__dirname + '/output/unpacked', function (err) { + if (err) return done(err) + assert.equal(rfile('./output/unpacked/bar.txt'), rfile('./fixtures/to-pack/bar.txt')) + assert.equal(rfile('./output/unpacked/foo.txt'), rfile('./fixtures/to-pack/foo.txt')) + done() + })) + }) +}) +describe('file.pipe(unpack(directory, callback))', function () { + it('copies the file into the directory', function (done) { + read(__dirname + '/fixtures/packed-file.txt').pipe(tar.unpack(__dirname + '/output/unpacked', function (err) { + if (err) return done(err) + assert.equal(rfile('./output/unpacked/index.js'), rfile('./fixtures/packed-file.txt')) + done() + })) + }) +}) +describe('pack(directory).pipe(tarball)', function () { + it('packs the directory into the output', function (done) { + var called = false + mkdir(__dirname + '/output/') + tar.pack(__dirname + '/fixtures/to-pack').pipe(write(__dirname + '/output/packed.tar.gz')) + .on('error', function (err) { + if (called) return + called = true + done(err) + }) + .on('close', function () { + if (called) return + called = true + read(__dirname + '/output/packed.tar.gz').pipe(tar.unpack(__dirname + '/output/unpacked', function (err) { + if (err) return done(err) + assert.equal(rfile('./output/unpacked/bar.txt'), rfile('./fixtures/to-pack/bar.txt')) + assert.equal(rfile('./output/unpacked/foo.txt'), rfile('./fixtures/to-pack/foo.txt')) + done() + })) + }) + }) +}) \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.npmignore new file mode 100644 index 0000000..c167ad5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.npmignore @@ -0,0 +1,5 @@ +.*.swp +node_modules +examples/extract/ +test/tmp/ +test/fixtures/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.travis.yml new file mode 100644 index 0000000..fca8ef0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.10 + - 0.11 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/LICENSE new file mode 100644 index 0000000..019b7e4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/LICENSE @@ -0,0 +1,12 @@ +The ISC License +Copyright (c) Isaac Z. Schlueter and Contributors +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/README.md new file mode 100644 index 0000000..cfda2ac --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/README.md @@ -0,0 +1,50 @@ +# node-tar + +Tar for Node.js. + +[![NPM](https://nodei.co/npm/tar.png)](https://nodei.co/npm/tar/) + +## API + +See `examples/` for usage examples. + +### var tar = require('tar') + +Returns an object with `.Pack`, `.Extract` and `.Parse` methods. + +### tar.Pack([properties]) + +Returns a through stream. Use +[fstream](https://npmjs.org/package/fstream) to write files into the +pack stream and you will receive tar archive data from the pack +stream. + +This only works with directories, it does not work with individual files. + +The optional `properties` object are used to set properties in the tar +'Global Extended Header'. If the `fromBase` property is set to true, +the tar will contain files relative to the path passed, and not with +the path included. + +### tar.Extract([options]) + +Returns a through stream. Write tar data to the stream and the files +in the tarball will be extracted onto the filesystem. + +`options` can be: + +```js +{ + path: '/path/to/extract/tar/into', + strip: 0, // how many path segments to strip from the root when extracting +} +``` + +`options` also get passed to the `fstream.Writer` instance that `tar` +uses internally. + +### tar.Parse() + +Returns a writable stream. Write tar data to it and it will emit +`entry` events for each entry parsed from the tarball. This is used by +`tar.Extract`. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/extracter.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/extracter.js new file mode 100644 index 0000000..f6253a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/extracter.js @@ -0,0 +1,19 @@ +var tar = require("../tar.js") + , fs = require("fs") + + +function onError(err) { + console.error('An error occurred:', err) +} + +function onEnd() { + console.log('Extracted!') +} + +var extractor = tar.Extract({path: __dirname + "/extract"}) + .on('error', onError) + .on('end', onEnd); + +fs.createReadStream(__dirname + "/../test/fixtures/c.tar") + .on('error', onError) + .pipe(extractor); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/packer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/packer.js new file mode 100644 index 0000000..039969c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/packer.js @@ -0,0 +1,24 @@ +var tar = require("../tar.js") + , fstream = require("fstream") + , fs = require("fs") + +var dirDest = fs.createWriteStream('dir.tar') + + +function onError(err) { + console.error('An error occurred:', err) +} + +function onEnd() { + console.log('Packed!') +} + +var packer = tar.Pack({ noProprietary: true }) + .on('error', onError) + .on('end', onEnd); + +// This must be a "directory" +fstream.Reader({ path: __dirname, type: "Directory" }) + .on('error', onError) + .pipe(packer) + .pipe(dirDest) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/reader.js new file mode 100644 index 0000000..39f3f08 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/examples/reader.js @@ -0,0 +1,36 @@ +var tar = require("../tar.js") + , fs = require("fs") + +fs.createReadStream(__dirname + "/../test/fixtures/c.tar") + .pipe(tar.Parse()) + .on("extendedHeader", function (e) { + console.error("extended pax header", e.props) + e.on("end", function () { + console.error("extended pax fields:", e.fields) + }) + }) + .on("ignoredEntry", function (e) { + console.error("ignoredEntry?!?", e.props) + }) + .on("longLinkpath", function (e) { + console.error("longLinkpath entry", e.props) + e.on("end", function () { + console.error("value=%j", e.body.toString()) + }) + }) + .on("longPath", function (e) { + console.error("longPath entry", e.props) + e.on("end", function () { + console.error("value=%j", e.body.toString()) + }) + }) + .on("entry", function (e) { + console.error("entry", e.props) + e.on("data", function (c) { + console.error(" >>>" + c.toString().replace(/\n/g, "\\n")) + }) + e.on("end", function () { + console.error(" << 0 + return !this._needDrain +} + +EntryWriter.prototype.end = function (c) { + // console.error(".. ew end") + if (c) this._buffer.push(c) + this._buffer.push(EOF) + this._ended = true + this._process() + this._needDrain = this._buffer.length > 0 +} + +EntryWriter.prototype.pause = function () { + // console.error(".. ew pause") + this._paused = true + this.emit("pause") +} + +EntryWriter.prototype.resume = function () { + // console.error(".. ew resume") + this._paused = false + this.emit("resume") + this._process() +} + +EntryWriter.prototype.add = function (entry) { + // console.error(".. ew add") + if (!this.parent) return this.emit("error", new Error("no parent")) + + // make sure that the _header and such is emitted, and clear out + // the _currentEntry link on the parent. + if (!this._ended) this.end() + + return this.parent.add(entry) +} + +EntryWriter.prototype._header = function () { + // console.error(".. ew header") + if (this._didHeader) return + this._didHeader = true + + var headerBlock = TarHeader.encode(this.props) + + if (this.props.needExtended && !this._meta) { + var me = this + + ExtendedHeaderWriter = ExtendedHeaderWriter || + require("./extended-header-writer.js") + + ExtendedHeaderWriter(this.props) + .on("data", function (c) { + me.emit("data", c) + }) + .on("error", function (er) { + me.emit("error", er) + }) + .end() + } + + // console.error(".. .. ew headerBlock emitting") + this.emit("data", headerBlock) + this.emit("header") +} + +EntryWriter.prototype._process = function () { + // console.error(".. .. ew process") + if (!this._didHeader && !this._meta) { + this._header() + } + + if (this._paused || this._processing) { + // console.error(".. .. .. paused=%j, processing=%j", this._paused, this._processing) + return + } + + this._processing = true + + var buf = this._buffer + for (var i = 0; i < buf.length; i ++) { + // console.error(".. .. .. i=%d", i) + + var c = buf[i] + + if (c === EOF) this._stream.end() + else this._stream.write(c) + + if (this._paused) { + // console.error(".. .. .. paused mid-emission") + this._processing = false + if (i < buf.length) { + this._needDrain = true + this._buffer = buf.slice(i + 1) + } + return + } + } + + // console.error(".. .. .. emitted") + this._buffer.length = 0 + this._processing = false + + // console.error(".. .. .. emitting drain") + this.emit("drain") +} + +EntryWriter.prototype.destroy = function () {} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/entry.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/entry.js new file mode 100644 index 0000000..4af5c41 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/entry.js @@ -0,0 +1,213 @@ +// A passthrough read/write stream that sets its properties +// based on a header, extendedHeader, and globalHeader +// +// Can be either a file system object of some sort, or +// a pax/ustar metadata entry. + +module.exports = Entry + +var TarHeader = require("./header.js") + , tar = require("../tar") + , assert = require("assert").ok + , Stream = require("stream").Stream + , inherits = require("inherits") + , fstream = require("fstream").Abstract + +function Entry (header, extended, global) { + Stream.call(this) + this.readable = true + this.writable = true + + this._needDrain = false + this._paused = false + this._reading = false + this._ending = false + this._ended = false + this._remaining = 0 + this._queue = [] + this._index = 0 + this._queueLen = 0 + + this._read = this._read.bind(this) + + this.props = {} + this._header = header + this._extended = extended || {} + + // globals can change throughout the course of + // a file parse operation. Freeze it at its current state. + this._global = {} + var me = this + Object.keys(global || {}).forEach(function (g) { + me._global[g] = global[g] + }) + + this._setProps() +} + +inherits(Entry, Stream) + +Entry.prototype.write = function (c) { + if (this._ending) this.error("write() after end()", null, true) + if (this._remaining === 0) { + this.error("invalid bytes past eof") + } + + // often we'll get a bunch of \0 at the end of the last write, + // since chunks will always be 512 bytes when reading a tarball. + if (c.length > this._remaining) { + c = c.slice(0, this._remaining) + } + this._remaining -= c.length + + // put it on the stack. + var ql = this._queueLen + this._queue.push(c) + this._queueLen ++ + + this._read() + + // either paused, or buffered + if (this._paused || ql > 0) { + this._needDrain = true + return false + } + + return true +} + +Entry.prototype.end = function (c) { + if (c) this.write(c) + this._ending = true + this._read() +} + +Entry.prototype.pause = function () { + this._paused = true + this.emit("pause") +} + +Entry.prototype.resume = function () { + // console.error(" Tar Entry resume", this.path) + this.emit("resume") + this._paused = false + this._read() + return this._queueLen - this._index > 1 +} + + // This is bound to the instance +Entry.prototype._read = function () { + // console.error(" Tar Entry _read", this.path) + + if (this._paused || this._reading || this._ended) return + + // set this flag so that event handlers don't inadvertently + // get multiple _read() calls running. + this._reading = true + + // have any data to emit? + while (this._index < this._queueLen && !this._paused) { + var chunk = this._queue[this._index ++] + this.emit("data", chunk) + } + + // check if we're drained + if (this._index >= this._queueLen) { + this._queue.length = this._queueLen = this._index = 0 + if (this._needDrain) { + this._needDrain = false + this.emit("drain") + } + if (this._ending) { + this._ended = true + this.emit("end") + } + } + + // if the queue gets too big, then pluck off whatever we can. + // this should be fairly rare. + var mql = this._maxQueueLen + if (this._queueLen > mql && this._index > 0) { + mql = Math.min(this._index, mql) + this._index -= mql + this._queueLen -= mql + this._queue = this._queue.slice(mql) + } + + this._reading = false +} + +Entry.prototype._setProps = function () { + // props = extended->global->header->{} + var header = this._header + , extended = this._extended + , global = this._global + , props = this.props + + // first get the values from the normal header. + var fields = tar.fields + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = header[field] + if (typeof val !== "undefined") props[field] = val + } + + // next, the global header for this file. + // numeric values, etc, will have already been parsed. + ;[global, extended].forEach(function (p) { + Object.keys(p).forEach(function (f) { + if (typeof p[f] !== "undefined") props[f] = p[f] + }) + }) + + // no nulls allowed in path or linkpath + ;["path", "linkpath"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = props[p].split("\0")[0] + } + }) + + + // set date fields to be a proper date + ;["mtime", "ctime", "atime"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = new Date(props[p] * 1000) + } + }) + + // set the type so that we know what kind of file to create + var type + switch (tar.types[props.type]) { + case "OldFile": + case "ContiguousFile": + type = "File" + break + + case "GNUDumpDir": + type = "Directory" + break + + case undefined: + type = "Unknown" + break + + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + default: + type = tar.types[props.type] + } + + this.type = type + this.path = props.path + this.size = props.size + + // size is special, since it signals when the file needs to end. + this._remaining = props.size +} + +Entry.prototype.warn = fstream.warn +Entry.prototype.error = fstream.error diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header-writer.js new file mode 100644 index 0000000..1728c45 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header-writer.js @@ -0,0 +1,191 @@ + +module.exports = ExtendedHeaderWriter + +var inherits = require("inherits") + , EntryWriter = require("./entry-writer.js") + +inherits(ExtendedHeaderWriter, EntryWriter) + +var tar = require("../tar.js") + , path = require("path") + , TarHeader = require("./header.js") + +// props is the props of the thing we need to write an +// extended header for. +// Don't be shy with it. Just encode everything. +function ExtendedHeaderWriter (props) { + // console.error(">> ehw ctor") + var me = this + + if (!(me instanceof ExtendedHeaderWriter)) { + return new ExtendedHeaderWriter(props) + } + + me.fields = props + + var p = + { path : ("PaxHeader" + path.join("/", props.path || "")) + .replace(/\\/g, "/").substr(0, 100) + , mode : props.mode || 0666 + , uid : props.uid || 0 + , gid : props.gid || 0 + , size : 0 // will be set later + , mtime : props.mtime || Date.now() / 1000 + , type : "x" + , linkpath : "" + , ustar : "ustar\0" + , ustarver : "00" + , uname : props.uname || "" + , gname : props.gname || "" + , devmaj : props.devmaj || 0 + , devmin : props.devmin || 0 + } + + + EntryWriter.call(me, p) + // console.error(">> ehw props", me.props) + me.props = p + + me._meta = true +} + +ExtendedHeaderWriter.prototype.end = function () { + // console.error(">> ehw end") + var me = this + + if (me._ended) return + me._ended = true + + me._encodeFields() + + if (me.props.size === 0) { + // nothing to write! + me._ready = true + me._stream.end() + return + } + + me._stream.write(TarHeader.encode(me.props)) + me.body.forEach(function (l) { + me._stream.write(l) + }) + me._ready = true + + // console.error(">> ehw _process calling end()", me.props) + this._stream.end() +} + +ExtendedHeaderWriter.prototype._encodeFields = function () { + // console.error(">> ehw _encodeFields") + this.body = [] + if (this.fields.prefix) { + this.fields.path = this.fields.prefix + "/" + this.fields.path + this.fields.prefix = "" + } + encodeFields(this.fields, "", this.body, this.fields.noProprietary) + var me = this + this.body.forEach(function (l) { + me.props.size += l.length + }) +} + +function encodeFields (fields, prefix, body, nop) { + // console.error(">> >> ehw encodeFields") + // "%d %s=%s\n", , , + // The length is a decimal number, and includes itself and the \n + // Numeric values are decimal strings. + + Object.keys(fields).forEach(function (k) { + var val = fields[k] + , numeric = tar.numeric[k] + + if (prefix) k = prefix + "." + k + + // already including NODETAR.type, don't need File=true also + if (k === fields.type && val === true) return + + switch (k) { + // don't include anything that's always handled just fine + // in the normal header, or only meaningful in the context + // of nodetar + case "mode": + case "cksum": + case "ustar": + case "ustarver": + case "prefix": + case "basename": + case "dirname": + case "needExtended": + case "block": + case "filter": + return + + case "rdev": + if (val === 0) return + break + + case "nlink": + case "dev": // Truly a hero among men, Creator of Star! + case "ino": // Speak his name with reverent awe! It is: + k = "SCHILY." + k + break + + default: break + } + + if (val && typeof val === "object" && + !Buffer.isBuffer(val)) encodeFields(val, k, body, nop) + else if (val === null || val === undefined) return + else body.push.apply(body, encodeField(k, val, nop)) + }) + + return body +} + +function encodeField (k, v, nop) { + // lowercase keys must be valid, otherwise prefix with + // "NODETAR." + if (k.charAt(0) === k.charAt(0).toLowerCase()) { + var m = k.split(".")[0] + if (!tar.knownExtended[m]) k = "NODETAR." + k + } + + // no proprietary + if (nop && k.charAt(0) !== k.charAt(0).toLowerCase()) { + return [] + } + + if (typeof val === "number") val = val.toString(10) + + var s = new Buffer(" " + k + "=" + v + "\n") + , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1 + + // console.error("1 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + // if adding that many digits will make it go over that length, + // then add one to it. For example, if the string is: + // " foo=bar\n" + // then that's 9 characters. With the "9", that bumps the length + // up to 10. However, this is invalid: + // "10 foo=bar\n" + // but, since that's actually 11 characters, since 10 adds another + // character to the length, and the length includes the number + // itself. In that case, just bump it up again. + if (s.length + digits >= Math.pow(10, digits)) digits += 1 + // console.error("2 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + var len = digits + s.length + // console.error("3 s=%j digits=%j s.length=%d len=%d", s.toString(), digits, s.length, len) + var lenBuf = new Buffer("" + len) + if (lenBuf.length + s.length !== len) { + throw new Error("Bad length calculation\n"+ + "len="+len+"\n"+ + "lenBuf="+JSON.stringify(lenBuf.toString())+"\n"+ + "lenBuf.length="+lenBuf.length+"\n"+ + "digits="+digits+"\n"+ + "s="+JSON.stringify(s.toString())+"\n"+ + "s.length="+s.length) + } + + return [lenBuf, s] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header.js new file mode 100644 index 0000000..74f432c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extended-header.js @@ -0,0 +1,140 @@ +// An Entry consisting of: +// +// "%d %s=%s\n", , , +// +// The length is a decimal number, and includes itself and the \n +// \0 does not terminate anything. Only the length terminates the string. +// Numeric values are decimal strings. + +module.exports = ExtendedHeader + +var Entry = require("./entry.js") + , inherits = require("inherits") + , tar = require("../tar.js") + , numeric = tar.numeric + , keyTrans = { "SCHILY.dev": "dev" + , "SCHILY.ino": "ino" + , "SCHILY.nlink": "nlink" } + +function ExtendedHeader () { + Entry.apply(this, arguments) + this.on("data", this._parse) + this.fields = {} + this._position = 0 + this._fieldPos = 0 + this._state = SIZE + this._sizeBuf = [] + this._keyBuf = [] + this._valBuf = [] + this._size = -1 + this._key = "" +} + +inherits(ExtendedHeader, Entry) +ExtendedHeader.prototype._parse = parse + +var s = 0 + , states = ExtendedHeader.states = {} + , SIZE = states.SIZE = s++ + , KEY = states.KEY = s++ + , VAL = states.VAL = s++ + , ERR = states.ERR = s++ + +Object.keys(states).forEach(function (s) { + states[states[s]] = states[s] +}) + +states[s] = null + +// char code values for comparison +var _0 = "0".charCodeAt(0) + , _9 = "9".charCodeAt(0) + , point = ".".charCodeAt(0) + , a = "a".charCodeAt(0) + , Z = "Z".charCodeAt(0) + , a = "a".charCodeAt(0) + , z = "z".charCodeAt(0) + , space = " ".charCodeAt(0) + , eq = "=".charCodeAt(0) + , cr = "\n".charCodeAt(0) + +function parse (c) { + if (this._state === ERR) return + + for ( var i = 0, l = c.length + ; i < l + ; this._position++, this._fieldPos++, i++) { + // console.error("top of loop, size="+this._size) + + var b = c[i] + + if (this._size >= 0 && this._fieldPos > this._size) { + error(this, "field exceeds length="+this._size) + return + } + + switch (this._state) { + case ERR: return + + case SIZE: + // console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString()) + if (b === space) { + this._state = KEY + // this._fieldPos = this._sizeBuf.length + this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10) + this._sizeBuf.length = 0 + continue + } + if (b < _0 || b > _9) { + error(this, "expected [" + _0 + ".." + _9 + "], got " + b) + return + } + this._sizeBuf.push(b) + continue + + case KEY: + // can be any char except =, not > size. + if (b === eq) { + this._state = VAL + this._key = new Buffer(this._keyBuf).toString() + if (keyTrans[this._key]) this._key = keyTrans[this._key] + this._keyBuf.length = 0 + continue + } + this._keyBuf.push(b) + continue + + case VAL: + // field must end with cr + if (this._fieldPos === this._size - 1) { + // console.error("finished with "+this._key) + if (b !== cr) { + error(this, "expected \\n at end of field") + return + } + var val = new Buffer(this._valBuf).toString() + if (numeric[this._key]) { + val = parseFloat(val) + } + this.fields[this._key] = val + + this._valBuf.length = 0 + this._state = SIZE + this._size = -1 + this._fieldPos = -1 + continue + } + this._valBuf.push(b) + continue + } + } +} + +function error (me, msg) { + msg = "invalid header: " + msg + + "\nposition=" + me._position + + "\nfield position=" + me._fieldPos + + me.error(msg) + me.state = ERR +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extract.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extract.js new file mode 100644 index 0000000..fe1bb97 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/extract.js @@ -0,0 +1,94 @@ +// give it a tarball and a path, and it'll dump the contents + +module.exports = Extract + +var tar = require("../tar.js") + , fstream = require("fstream") + , inherits = require("inherits") + , path = require("path") + +function Extract (opts) { + if (!(this instanceof Extract)) return new Extract(opts) + tar.Parse.apply(this) + + if (typeof opts !== "object") { + opts = { path: opts } + } + + // better to drop in cwd? seems more standard. + opts.path = opts.path || path.resolve("node-tar-extract") + opts.type = "Directory" + opts.Directory = true + + // similar to --strip or --strip-components + opts.strip = +opts.strip + if (!opts.strip || opts.strip <= 0) opts.strip = 0 + + this._fst = fstream.Writer(opts) + + this.pause() + var me = this + + // Hardlinks in tarballs are relative to the root + // of the tarball. So, they need to be resolved against + // the target directory in order to be created properly. + me.on("entry", function (entry) { + // if there's a "strip" argument, then strip off that many + // path components. + if (opts.strip) { + var p = entry.path.split("/").slice(opts.strip).join("/") + entry.path = entry.props.path = p + if (entry.linkpath) { + var lp = entry.linkpath.split("/").slice(opts.strip).join("/") + entry.linkpath = entry.props.linkpath = lp + } + } + if (entry.type === "Link") { + entry.linkpath = entry.props.linkpath = + path.join(opts.path, path.join("/", entry.props.linkpath)) + } + + if (entry.type === "SymbolicLink") { + var dn = path.dirname(entry.path) || "" + var linkpath = entry.props.linkpath + var target = path.resolve(opts.path, dn, linkpath) + if (target.indexOf(opts.path) !== 0) { + linkpath = path.join(opts.path, path.join("/", linkpath)) + } + entry.linkpath = entry.props.linkpath = linkpath + } + }) + + this._fst.on("ready", function () { + me.pipe(me._fst, { end: false }) + me.resume() + }) + + this._fst.on('error', function(err) { + me.emit('error', err) + }) + + this._fst.on('drain', function() { + me.emit('drain') + }) + + // this._fst.on("end", function () { + // console.error("\nEEEE Extract End", me._fst.path) + // }) + + this._fst.on("close", function () { + // console.error("\nEEEE Extract End", me._fst.path) + me.emit("finish") + me.emit("end") + me.emit("close") + }) +} + +inherits(Extract, tar.Parse) + +Extract.prototype._streamEnd = function () { + var me = this + if (!me._ended || me._entry) me.error("unexpected eof") + me._fst.end() + // my .end() is coming later. +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/global-header-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/global-header-writer.js new file mode 100644 index 0000000..0bfc7b8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/global-header-writer.js @@ -0,0 +1,14 @@ +module.exports = GlobalHeaderWriter + +var ExtendedHeaderWriter = require("./extended-header-writer.js") + , inherits = require("inherits") + +inherits(GlobalHeaderWriter, ExtendedHeaderWriter) + +function GlobalHeaderWriter (props) { + if (!(this instanceof GlobalHeaderWriter)) { + return new GlobalHeaderWriter(props) + } + ExtendedHeaderWriter.call(this, props) + this.props.type = "g" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/header.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/header.js new file mode 100644 index 0000000..05b237c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/header.js @@ -0,0 +1,385 @@ +// parse a 512-byte header block to a data object, or vice-versa +// If the data won't fit nicely in a simple header, then generate +// the appropriate extended header file, and return that. + +module.exports = TarHeader + +var tar = require("../tar.js") + , fields = tar.fields + , fieldOffs = tar.fieldOffs + , fieldEnds = tar.fieldEnds + , fieldSize = tar.fieldSize + , numeric = tar.numeric + , assert = require("assert").ok + , space = " ".charCodeAt(0) + , slash = "/".charCodeAt(0) + , bslash = process.platform === "win32" ? "\\".charCodeAt(0) : null + +function TarHeader (block) { + if (!(this instanceof TarHeader)) return new TarHeader(block) + if (block) this.decode(block) +} + +TarHeader.prototype = + { decode : decode + , encode: encode + , calcSum: calcSum + , checkSum: checkSum + } + +TarHeader.parseNumeric = parseNumeric +TarHeader.encode = encode +TarHeader.decode = decode + +// note that this will only do the normal ustar header, not any kind +// of extended posix header file. If something doesn't fit comfortably, +// then it will set obj.needExtended = true, and set the block to +// the closest approximation. +function encode (obj) { + if (!obj && !(this instanceof TarHeader)) throw new Error( + "encode must be called on a TarHeader, or supplied an object") + + obj = obj || this + var block = obj.block = new Buffer(512) + + // if the object has a "prefix", then that's actually an extension of + // the path field. + if (obj.prefix) { + // console.error("%% header encoding, got a prefix", obj.prefix) + obj.path = obj.prefix + "/" + obj.path + // console.error("%% header encoding, prefixed path", obj.path) + obj.prefix = "" + } + + obj.needExtended = false + + if (obj.mode) { + if (typeof obj.mode === "string") obj.mode = parseInt(obj.mode, 8) + obj.mode = obj.mode & 0777 + } + + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , off = fieldOffs[f] + , end = fieldEnds[f] + , ret + + switch (field) { + case "cksum": + // special, done below, after all the others + break + + case "prefix": + // special, this is an extension of the "path" field. + // console.error("%% header encoding, skip prefix later") + break + + case "type": + // convert from long name to a single char. + var type = obj.type || "0" + if (type.length > 1) { + type = tar.types[obj.type] + if (!type) type = "0" + } + writeText(block, off, end, type) + break + + case "path": + // uses the "prefix" field if > 100 bytes, but <= 255 + var pathLen = Buffer.byteLength(obj.path) + , pathFSize = fieldSize[fields.path] + , prefFSize = fieldSize[fields.prefix] + + // paths between 100 and 255 should use the prefix field. + // longer than 255 + if (pathLen > pathFSize && + pathLen <= pathFSize + prefFSize) { + // need to find a slash somewhere in the middle so that + // path and prefix both fit in their respective fields + var searchStart = pathLen - 1 - pathFSize + , searchEnd = prefFSize + , found = false + , pathBuf = new Buffer(obj.path) + + for ( var s = searchStart + ; (s <= searchEnd) + ; s ++ ) { + if (pathBuf[s] === slash || pathBuf[s] === bslash) { + found = s + break + } + } + + if (found !== false) { + prefix = pathBuf.slice(0, found).toString("utf8") + path = pathBuf.slice(found + 1).toString("utf8") + + ret = writeText(block, off, end, path) + off = fieldOffs[fields.prefix] + end = fieldEnds[fields.prefix] + // console.error("%% header writing prefix", off, end, prefix) + ret = writeText(block, off, end, prefix) || ret + break + } + } + + // paths less than 100 chars don't need a prefix + // and paths longer than 255 need an extended header and will fail + // on old implementations no matter what we do here. + // Null out the prefix, and fallthrough to default. + // console.error("%% header writing no prefix") + var poff = fieldOffs[fields.prefix] + , pend = fieldEnds[fields.prefix] + writeText(block, poff, pend, "") + // fallthrough + + // all other fields are numeric or text + default: + ret = numeric[field] + ? writeNumeric(block, off, end, obj[field]) + : writeText(block, off, end, obj[field] || "") + break + } + obj.needExtended = obj.needExtended || ret + } + + var off = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + writeNumeric(block, off, end, calcSum.call(this, block)) + + return block +} + +// if it's a negative number, or greater than will fit, +// then use write256. +var MAXNUM = { 12: 077777777777 + , 11: 07777777777 + , 8 : 07777777 + , 7 : 0777777 } +function writeNumeric (block, off, end, num) { + var writeLen = end - off + , maxNum = MAXNUM[writeLen] || 0 + + num = num || 0 + // console.error(" numeric", num) + + if (num instanceof Date || + Object.prototype.toString.call(num) === "[object Date]") { + num = num.getTime() / 1000 + } + + if (num > maxNum || num < 0) { + write256(block, off, end, num) + // need an extended header if negative or too big. + return true + } + + // god, tar is so annoying + // if the string is small enough, you should put a space + // between the octal string and the \0, but if it doesn't + // fit, then don't. + var numStr = Math.floor(num).toString(8) + if (num < MAXNUM[writeLen - 1]) numStr += " " + + // pad with "0" chars + if (numStr.length < writeLen) { + numStr = (new Array(writeLen - numStr.length).join("0")) + numStr + } + + if (numStr.length !== writeLen - 1) { + throw new Error("invalid length: " + JSON.stringify(numStr) + "\n" + + "expected: "+writeLen) + } + block.write(numStr, off, writeLen, "utf8") + block[end - 1] = 0 +} + +function write256 (block, off, end, num) { + var buf = block.slice(off, end) + var positive = num >= 0 + buf[0] = positive ? 0x80 : 0xFF + + // get the number as a base-256 tuple + if (!positive) num *= -1 + var tuple = [] + do { + var n = num % 256 + tuple.push(n) + num = (num - n) / 256 + } while (num) + + var bytes = tuple.length + + var fill = buf.length - bytes + for (var i = 1; i < fill; i ++) { + buf[i] = positive ? 0 : 0xFF + } + + // tuple is a base256 number, with [0] as the *least* significant byte + // if it's negative, then we need to flip all the bits once we hit the + // first non-zero bit. The 2's-complement is (0x100 - n), and the 1's- + // complement is (0xFF - n). + var zero = true + for (i = bytes; i > 0; i --) { + var byte = tuple[bytes - i] + if (positive) buf[fill + i] = byte + else if (zero && byte === 0) buf[fill + i] = 0 + else if (zero) { + zero = false + buf[fill + i] = 0x100 - byte + } else buf[fill + i] = 0xFF - byte + } +} + +function writeText (block, off, end, str) { + // strings are written as utf8, then padded with \0 + var strLen = Buffer.byteLength(str) + , writeLen = Math.min(strLen, end - off) + // non-ascii fields need extended headers + // long fields get truncated + , needExtended = strLen !== str.length || strLen > writeLen + + // write the string, and null-pad + if (writeLen > 0) block.write(str, off, writeLen, "utf8") + for (var i = off + writeLen; i < end; i ++) block[i] = 0 + + return needExtended +} + +function calcSum (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + if (!block) throw new Error("Need block to checksum") + + // now figure out what it would be if the cksum was " " + var sum = 0 + , start = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + for (var i = 0; i < fieldOffs[fields.cksum]; i ++) { + sum += block[i] + } + + for (var i = start; i < end; i ++) { + sum += space + } + + for (var i = end; i < 512; i ++) { + sum += block[i] + } + + return sum +} + + +function checkSum (block) { + var sum = calcSum.call(this, block) + block = block || this.block + + var cksum = block.slice(fieldOffs[fields.cksum], fieldEnds[fields.cksum]) + cksum = parseNumeric(cksum) + + return cksum === sum +} + +function decode (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + this.block = block + this.cksumValid = this.checkSum() + + var prefix = null + + // slice off each field. + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = block.slice(fieldOffs[f], fieldEnds[f]) + + switch (field) { + case "ustar": + // if not ustar, then everything after that is just padding. + if (val.toString() !== "ustar\0") { + this.ustar = false + return + } else { + // console.error("ustar:", val, val.toString()) + this.ustar = val.toString() + } + break + + // prefix is special, since it might signal the xstar header + case "prefix": + var atime = parseNumeric(val.slice(131, 131 + 12)) + , ctime = parseNumeric(val.slice(131 + 12, 131 + 12 + 12)) + if ((val[130] === 0 || val[130] === space) && + typeof atime === "number" && + typeof ctime === "number" && + val[131 + 12] === space && + val[131 + 12 + 12] === space) { + this.atime = atime + this.ctime = ctime + val = val.slice(0, 130) + } + prefix = val.toString("utf8").replace(/\0+$/, "") + // console.error("%% header reading prefix", prefix) + break + + // all other fields are null-padding text + // or a number. + default: + if (numeric[field]) { + this[field] = parseNumeric(val) + } else { + this[field] = val.toString("utf8").replace(/\0+$/, "") + } + break + } + } + + // if we got a prefix, then prepend it to the path. + if (prefix) { + this.path = prefix + "/" + this.path + // console.error("%% header got a prefix", this.path) + } +} + +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null + + // build up a base-256 tuple from the least sig to the highest + var zero = false + , tuple = [] + for (var i = buf.length - 1; i > 0; i --) { + var byte = buf[i] + if (positive) tuple.push(byte) + else if (zero && byte === 0) tuple.push(0) + else if (zero) { + zero = false + tuple.push(0x100 - byte) + } else tuple.push(0xFF - byte) + } + + for (var sum = 0, i = 0, l = tuple.length; i < l; i ++) { + sum += tuple[i] * Math.pow(256, i) + } + + return positive ? sum : -1 * sum +} + +function parseNumeric (f) { + if (f[0] & 0x80) return parse256(f) + + var str = f.toString("utf8").split("\0")[0].trim() + , res = parseInt(str, 8) + + return isNaN(res) ? null : res +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/pack.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/pack.js new file mode 100644 index 0000000..5a3bb95 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/pack.js @@ -0,0 +1,236 @@ +// pipe in an fstream, and it'll make a tarball. +// key-value pair argument is global extended header props. + +module.exports = Pack + +var EntryWriter = require("./entry-writer.js") + , Stream = require("stream").Stream + , path = require("path") + , inherits = require("inherits") + , GlobalHeaderWriter = require("./global-header-writer.js") + , collect = require("fstream").collect + , eof = new Buffer(512) + +for (var i = 0; i < 512; i ++) eof[i] = 0 + +inherits(Pack, Stream) + +function Pack (props) { + // console.error("-- p ctor") + var me = this + if (!(me instanceof Pack)) return new Pack(props) + + if (props) me._noProprietary = props.noProprietary + else me._noProprietary = false + + me._global = props + + me.readable = true + me.writable = true + me._buffer = [] + // console.error("-- -- set current to null in ctor") + me._currentEntry = null + me._processing = false + + me._pipeRoot = null + me.on("pipe", function (src) { + if (src.root === me._pipeRoot) return + me._pipeRoot = src + src.on("end", function () { + me._pipeRoot = null + }) + me.add(src) + }) +} + +Pack.prototype.addGlobal = function (props) { + // console.error("-- p addGlobal") + if (this._didGlobal) return + this._didGlobal = true + + var me = this + GlobalHeaderWriter(props) + .on("data", function (c) { + me.emit("data", c) + }) + .end() +} + +Pack.prototype.add = function (stream) { + if (this._global && !this._didGlobal) this.addGlobal(this._global) + + if (this._ended) return this.emit("error", new Error("add after end")) + + collect(stream) + this._buffer.push(stream) + this._process() + this._needDrain = this._buffer.length > 0 + return !this._needDrain +} + +Pack.prototype.pause = function () { + this._paused = true + if (this._currentEntry) this._currentEntry.pause() + this.emit("pause") +} + +Pack.prototype.resume = function () { + this._paused = false + if (this._currentEntry) this._currentEntry.resume() + this.emit("resume") + this._process() +} + +Pack.prototype.end = function () { + this._ended = true + this._buffer.push(eof) + this._process() +} + +Pack.prototype._process = function () { + var me = this + if (me._paused || me._processing) { + return + } + + var entry = me._buffer.shift() + + if (!entry) { + if (me._needDrain) { + me.emit("drain") + } + return + } + + if (entry.ready === false) { + // console.error("-- entry is not ready", entry) + me._buffer.unshift(entry) + entry.on("ready", function () { + // console.error("-- -- ready!", entry) + me._process() + }) + return + } + + me._processing = true + + if (entry === eof) { + // need 2 ending null blocks. + me.emit("data", eof) + me.emit("data", eof) + me.emit("end") + me.emit("close") + return + } + + // Change the path to be relative to the root dir that was + // added to the tarball. + // + // XXX This should be more like how -C works, so you can + // explicitly set a root dir, and also explicitly set a pathname + // in the tarball to use. That way we can skip a lot of extra + // work when resolving symlinks for bundled dependencies in npm. + + var root = path.dirname((entry.root || entry).path); + if (me._global && me._global.fromBase && entry.root && entry.root.path) { + // user set 'fromBase: true' indicating tar root should be directory itself + root = entry.root.path; + } + + var wprops = {} + + Object.keys(entry.props || {}).forEach(function (k) { + wprops[k] = entry.props[k] + }) + + if (me._noProprietary) wprops.noProprietary = true + + wprops.path = path.relative(root, entry.path || '') + + // actually not a matter of opinion or taste. + if (process.platform === "win32") { + wprops.path = wprops.path.replace(/\\/g, "/") + } + + if (!wprops.type) + wprops.type = 'Directory' + + switch (wprops.type) { + // sockets not supported + case "Socket": + return + + case "Directory": + wprops.path += "/" + wprops.size = 0 + break + + case "Link": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(root, lp) || "." + wprops.size = 0 + break + + case "SymbolicLink": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(path.dirname(entry.path), lp) || "." + wprops.size = 0 + break + } + + // console.error("-- new writer", wprops) + // if (!wprops.type) { + // // console.error("-- no type?", entry.constructor.name, entry) + // } + + // console.error("-- -- set current to new writer", wprops.path) + var writer = me._currentEntry = EntryWriter(wprops) + + writer.parent = me + + // writer.on("end", function () { + // // console.error("-- -- writer end", writer.path) + // }) + + writer.on("data", function (c) { + me.emit("data", c) + }) + + writer.on("header", function () { + Buffer.prototype.toJSON = function () { + return this.toString().split(/\0/).join(".") + } + // console.error("-- -- writer header %j", writer.props) + if (writer.props.size === 0) nextEntry() + }) + writer.on("close", nextEntry) + + var ended = false + function nextEntry () { + if (ended) return + ended = true + + // console.error("-- -- writer close", writer.path) + // console.error("-- -- set current to null", wprops.path) + me._currentEntry = null + me._processing = false + me._process() + } + + writer.on("error", function (er) { + // console.error("-- -- writer error", writer.path) + me.emit("error", er) + }) + + // if it's the root, then there's no need to add its entries, + // or data, since they'll be added directly. + if (entry === me._pipeRoot) { + // console.error("-- is the root, don't auto-add") + writer.add = null + } + + entry.pipe(writer) +} + +Pack.prototype.destroy = function () {} +Pack.prototype.write = function () {} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/parse.js new file mode 100644 index 0000000..1c53d9d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/lib/parse.js @@ -0,0 +1,271 @@ + +// A writable stream. +// It emits "entry" events, which provide a readable stream that has +// header info attached. + +module.exports = Parse.create = Parse + +var stream = require("stream") + , Stream = stream.Stream + , BlockStream = require("block-stream") + , tar = require("../tar.js") + , TarHeader = require("./header.js") + , Entry = require("./entry.js") + , BufferEntry = require("./buffer-entry.js") + , ExtendedHeader = require("./extended-header.js") + , assert = require("assert").ok + , inherits = require("inherits") + , fstream = require("fstream") + +// reading a tar is a lot like reading a directory +// However, we're actually not going to run the ctor, +// since it does a stat and various other stuff. +// This inheritance gives us the pause/resume/pipe +// behavior that is desired. +inherits(Parse, fstream.Reader) + +function Parse () { + var me = this + if (!(me instanceof Parse)) return new Parse() + + // doesn't apply fstream.Reader ctor? + // no, becasue we don't want to stat/etc, we just + // want to get the entry/add logic from .pipe() + Stream.apply(me) + + me.writable = true + me.readable = true + me._stream = new BlockStream(512) + me.position = 0 + me._ended = false + + me._stream.on("error", function (e) { + me.emit("error", e) + }) + + me._stream.on("data", function (c) { + me._process(c) + }) + + me._stream.on("end", function () { + me._streamEnd() + }) + + me._stream.on("drain", function () { + me.emit("drain") + }) +} + +// overridden in Extract class, since it needs to +// wait for its DirWriter part to finish before +// emitting "end" +Parse.prototype._streamEnd = function () { + var me = this + if (!me._ended || me._entry) me.error("unexpected eof") + me.emit("end") +} + +// a tar reader is actually a filter, not just a readable stream. +// So, you should pipe a tarball stream into it, and it needs these +// write/end methods to do that. +Parse.prototype.write = function (c) { + if (this._ended) { + // gnutar puts a LOT of nulls at the end. + // you can keep writing these things forever. + // Just ignore them. + for (var i = 0, l = c.length; i > l; i ++) { + if (c[i] !== 0) return this.error("write() after end()") + } + return + } + return this._stream.write(c) +} + +Parse.prototype.end = function (c) { + this._ended = true + return this._stream.end(c) +} + +// don't need to do anything, since we're just +// proxying the data up from the _stream. +// Just need to override the parent's "Not Implemented" +// error-thrower. +Parse.prototype._read = function () {} + +Parse.prototype._process = function (c) { + assert(c && c.length === 512, "block size should be 512") + + // one of three cases. + // 1. A new header + // 2. A part of a file/extended header + // 3. One of two or more EOF null blocks + + if (this._entry) { + var entry = this._entry + entry.write(c) + if (entry._remaining === 0) { + entry.end() + this._entry = null + } + } else { + // either zeroes or a header + var zero = true + for (var i = 0; i < 512 && zero; i ++) { + zero = c[i] === 0 + } + + // eof is *at least* 2 blocks of nulls, and then the end of the + // file. you can put blocks of nulls between entries anywhere, + // so appending one tarball to another is technically valid. + // ending without the eof null blocks is not allowed, however. + if (zero) { + if (this._eofStarted) + this._ended = true + this._eofStarted = true + } else { + this._eofStarted = false + this._startEntry(c) + } + } + + this.position += 512 +} + +// take a header chunk, start the right kind of entry. +Parse.prototype._startEntry = function (c) { + var header = new TarHeader(c) + , self = this + , entry + , ev + , EntryType + , onend + , meta = false + + if (null === header.size || !header.cksumValid) { + var e = new Error("invalid tar file") + e.header = header + e.tar_file_offset = this.position + e.tar_block = this.position / 512 + return this.emit("error", e) + } + + switch (tar.types[header.type]) { + case "File": + case "OldFile": + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + case "ContiguousFile": + case "GNUDumpDir": + // start a file. + // pass in any extended headers + // These ones consumers are typically most interested in. + EntryType = Entry + ev = "entry" + break + + case "GlobalExtendedHeader": + // extended headers that apply to the rest of the tarball + EntryType = ExtendedHeader + onend = function () { + self._global = self._global || {} + Object.keys(entry.fields).forEach(function (k) { + self._global[k] = entry.fields[k] + }) + } + ev = "globalExtendedHeader" + meta = true + break + + case "ExtendedHeader": + case "OldExtendedHeader": + // extended headers that apply to the next entry + EntryType = ExtendedHeader + onend = function () { + self._extended = entry.fields + } + ev = "extendedHeader" + meta = true + break + + case "NextFileHasLongLinkpath": + // set linkpath= in extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.linkpath = entry.body + } + ev = "longLinkpath" + meta = true + break + + case "NextFileHasLongPath": + case "OldGnuLongPath": + // set path= in file-extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.path = entry.body + } + ev = "longPath" + meta = true + break + + default: + // all the rest we skip, but still set the _entry + // member, so that we can skip over their data appropriately. + // emit an event to say that this is an ignored entry type? + EntryType = Entry + ev = "ignoredEntry" + break + } + + var global, extended + if (meta) { + global = extended = null + } else { + var global = this._global + var extended = this._extended + + // extendedHeader only applies to one entry, so once we start + // an entry, it's over. + this._extended = null + } + entry = new EntryType(header, extended, global) + entry.meta = meta + + // only proxy data events of normal files. + if (!meta) { + entry.on("data", function (c) { + me.emit("data", c) + }) + } + + if (onend) entry.on("end", onend) + + this._entry = entry + var me = this + + entry.on("pause", function () { + me.pause() + }) + + entry.on("resume", function () { + me.resume() + }) + + if (this.listeners("*").length) { + this.emit("*", ev, entry) + } + + this.emit(ev, entry) + + // Zero-byte entry. End immediately. + if (entry.props.size === 0) { + entry.end() + this._entry = null + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENCE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENCE new file mode 100644 index 0000000..74489e2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/README.md new file mode 100644 index 0000000..c16e9c4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/README.md @@ -0,0 +1,14 @@ +# block-stream + +A stream of blocks. + +Write data into it, and it'll output data in buffer blocks the size you +specify, padding with zeroes if necessary. + +```javascript +var block = new BlockStream(512) +fs.createReadStream("some-file").pipe(block) +block.pipe(fs.createWriteStream("block-file")) +``` + +When `.end()` or `.flush()` is called, it'll pad the block with zeroes. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js new file mode 100644 index 0000000..9328844 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream-pause.js @@ -0,0 +1,70 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + f.pause() + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + f.resume() + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream.js new file mode 100644 index 0000000..1141f3a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/block-stream.js @@ -0,0 +1,68 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js new file mode 100644 index 0000000..93e4068 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper-pause.js @@ -0,0 +1,70 @@ +var BlockStream = require("dropper") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + f.pause() + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + f.resume() + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper.js new file mode 100644 index 0000000..55fa133 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/bench/dropper.js @@ -0,0 +1,68 @@ +var BlockStream = require("dropper") + +var blockSizes = [16, 25, 1024] + , writeSizes = [4, 8, 15, 16, 17, 64, 100] + , writeCounts = [1, 10, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/block-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/block-stream.js new file mode 100644 index 0000000..008de03 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/block-stream.js @@ -0,0 +1,209 @@ +// write data to it, and it'll emit data in 512 byte blocks. +// if you .end() or .flush(), it'll emit whatever it's got, +// padded with nulls to 512 bytes. + +module.exports = BlockStream + +var Stream = require("stream").Stream + , inherits = require("inherits") + , assert = require("assert").ok + , debug = process.env.DEBUG ? console.error : function () {} + +function BlockStream (size, opt) { + this.writable = this.readable = true + this._opt = opt || {} + this._chunkSize = size || 512 + this._offset = 0 + this._buffer = [] + this._bufferLength = 0 + if (this._opt.nopad) this._zeroes = false + else { + this._zeroes = new Buffer(this._chunkSize) + for (var i = 0; i < this._chunkSize; i ++) { + this._zeroes[i] = 0 + } + } +} + +inherits(BlockStream, Stream) + +BlockStream.prototype.write = function (c) { + // debug(" BS write", c) + if (this._ended) throw new Error("BlockStream: write after end") + if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "") + if (c.length) { + this._buffer.push(c) + this._bufferLength += c.length + } + // debug("pushed onto buffer", this._bufferLength) + if (this._bufferLength >= this._chunkSize) { + if (this._paused) { + // debug(" BS paused, return false, need drain") + this._needDrain = true + return false + } + this._emitChunk() + } + return true +} + +BlockStream.prototype.pause = function () { + // debug(" BS pausing") + this._paused = true +} + +BlockStream.prototype.resume = function () { + // debug(" BS resume") + this._paused = false + return this._emitChunk() +} + +BlockStream.prototype.end = function (chunk) { + // debug("end", chunk) + if (typeof chunk === "function") cb = chunk, chunk = null + if (chunk) this.write(chunk) + this._ended = true + this.flush() +} + +BlockStream.prototype.flush = function () { + this._emitChunk(true) +} + +BlockStream.prototype._emitChunk = function (flush) { + // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused) + + // emit a chunk + if (flush && this._zeroes) { + // debug(" BS push zeroes", this._bufferLength) + // push a chunk of zeroes + var padBytes = (this._bufferLength % this._chunkSize) + if (padBytes !== 0) padBytes = this._chunkSize - padBytes + if (padBytes > 0) { + // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes)) + this._buffer.push(this._zeroes.slice(0, padBytes)) + this._bufferLength += padBytes + // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength) + } + } + + if (this._emitting || this._paused) return + this._emitting = true + + // debug(" BS entering loops") + var bufferIndex = 0 + while (this._bufferLength >= this._chunkSize && + (flush || !this._paused)) { + // debug(" BS data emission loop", this._bufferLength) + + var out + , outOffset = 0 + , outHas = this._chunkSize + + while (outHas > 0 && (flush || !this._paused) ) { + // debug(" BS data inner emit loop", this._bufferLength) + var cur = this._buffer[bufferIndex] + , curHas = cur.length - this._offset + // debug("cur=", cur) + // debug("curHas=%j", curHas) + // If it's not big enough to fill the whole thing, then we'll need + // to copy multiple buffers into one. However, if it is big enough, + // then just slice out the part we want, to save unnecessary copying. + // Also, need to copy if we've already done some copying, since buffers + // can't be joined like cons strings. + if (out || curHas < outHas) { + out = out || new Buffer(this._chunkSize) + cur.copy(out, outOffset, + this._offset, this._offset + Math.min(curHas, outHas)) + } else if (cur.length === outHas && this._offset === 0) { + // shortcut -- cur is exactly long enough, and no offset. + out = cur + } else { + // slice out the piece of cur that we need. + out = cur.slice(this._offset, this._offset + outHas) + } + + if (curHas > outHas) { + // means that the current buffer couldn't be completely output + // update this._offset to reflect how much WAS written + this._offset += outHas + outHas = 0 + } else { + // output the entire current chunk. + // toss it away + outHas -= curHas + outOffset += curHas + bufferIndex ++ + this._offset = 0 + } + } + + this._bufferLength -= this._chunkSize + assert(out.length === this._chunkSize) + // debug("emitting data", out) + // debug(" BS emitting, paused=%j", this._paused, this._bufferLength) + this.emit("data", out) + out = null + } + // debug(" BS out of loops", this._bufferLength) + + // whatever is left, it's not enough to fill up a block, or we're paused + this._buffer = this._buffer.slice(bufferIndex) + if (this._paused) { + // debug(" BS paused, leaving", this._bufferLength) + this._needsDrain = true + this._emitting = false + return + } + + // if flushing, and not using null-padding, then need to emit the last + // chunk(s) sitting in the queue. We know that it's not enough to + // fill up a whole block, because otherwise it would have been emitted + // above, but there may be some offset. + var l = this._buffer.length + if (flush && !this._zeroes && l) { + if (l === 1) { + if (this._offset) { + this.emit("data", this._buffer[0].slice(this._offset)) + } else { + this.emit("data", this._buffer[0]) + } + } else { + var outHas = this._bufferLength + , out = new Buffer(outHas) + , outOffset = 0 + for (var i = 0; i < l; i ++) { + var cur = this._buffer[i] + , curHas = cur.length - this._offset + cur.copy(out, outOffset, this._offset) + this._offset = 0 + outOffset += curHas + this._bufferLength -= curHas + } + this.emit("data", out) + } + // truncate + this._buffer.length = 0 + this._bufferLength = 0 + this._offset = 0 + } + + // now either drained or ended + // debug("either draining, or ended", this._bufferLength, this._ended) + // means that we've flushed out all that we can so far. + if (this._needDrain) { + // debug("emitting drain", this._bufferLength) + this._needDrain = false + this.emit("drain") + } + + if ((this._bufferLength === 0) && this._ended && !this._endEmitted) { + // debug("emitting end", this._bufferLength) + this._endEmitted = true + this.emit("end") + } + + this._emitting = false + + // debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/package.json new file mode 100644 index 0000000..97d9d42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/package.json @@ -0,0 +1,55 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "block-stream", + "description": "a stream of blocks", + "version": "0.0.8", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/block-stream.git" + }, + "engines": { + "node": "0.4 || >=0.5.8" + }, + "main": "block-stream.js", + "dependencies": { + "inherits": "~2.0.0" + }, + "devDependencies": { + "tap": "0.x" + }, + "scripts": { + "test": "tap test/" + }, + "license": "ISC", + "gitHead": "b35520314f4763af0788d65a846bb43d9c0a8f02", + "bugs": { + "url": "https://github.com/isaacs/block-stream/issues" + }, + "homepage": "https://github.com/isaacs/block-stream#readme", + "_id": "block-stream@0.0.8", + "_shasum": "0688f46da2bbf9cff0c4f68225a0cb95cbe8a46b", + "_from": "block-stream@*", + "_npmVersion": "2.10.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "0688f46da2bbf9cff0c4f68225a0cb95cbe8a46b", + "tarball": "http://registry.npmjs.org/block-stream/-/block-stream-0.0.8.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.8.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/basic.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/basic.js new file mode 100644 index 0000000..b4b9305 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/basic.js @@ -0,0 +1,27 @@ +var tap = require("tap") + , BlockStream = require("../block-stream.js") + +tap.test("basic test", function (t) { + var b = new BlockStream(16) + var fs = require("fs") + var fstr = fs.createReadStream(__filename, {encoding: "utf8"}) + fstr.pipe(b) + + var stat + t.doesNotThrow(function () { + stat = fs.statSync(__filename) + }, "stat should not throw") + + var totalBytes = 0 + b.on("data", function (c) { + t.equal(c.length, 16, "chunks should be 16 bytes long") + t.type(c, Buffer, "chunks should be buffer objects") + totalBytes += c.length + }) + b.on("end", function () { + var expectedBytes = stat.size + (16 - stat.size % 16) + t.equal(totalBytes, expectedBytes, "Should be multiple of 16") + t.end() + }) + +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js new file mode 100644 index 0000000..7a8de88 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad-thorough.js @@ -0,0 +1,68 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16]//, 25]//, 1024] + , writeSizes = [4, 15, 16, 17, 64 ]//, 64, 100] + , writeCounts = [1, 10]//, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize, {nopad: true }) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = writeSize * writeCount * 2 + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad.js new file mode 100644 index 0000000..6d38429 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/nopad.js @@ -0,0 +1,57 @@ +var BlockStream = require("../") +var tap = require("tap") + + +tap.test("don't pad, small writes", function (t) { + var f = new BlockStream(16, { nopad: true }) + t.plan(1) + + f.on("data", function (c) { + t.equal(c.toString(), "abc", "should get 'abc'") + }) + + f.on("end", function () { t.end() }) + + f.write(new Buffer("a")) + f.write(new Buffer("b")) + f.write(new Buffer("c")) + f.end() +}) + +tap.test("don't pad, exact write", function (t) { + var f = new BlockStream(16, { nopad: true }) + t.plan(1) + + var first = true + f.on("data", function (c) { + if (first) { + first = false + t.equal(c.toString(), "abcdefghijklmnop", "first chunk") + } else { + t.fail("should only get one") + } + }) + + f.on("end", function () { t.end() }) + + f.end(new Buffer("abcdefghijklmnop")) +}) + +tap.test("don't pad, big write", function (t) { + var f = new BlockStream(16, { nopad: true }) + t.plan(2) + + var first = true + f.on("data", function (c) { + if (first) { + first = false + t.equal(c.toString(), "abcdefghijklmnop", "first chunk") + } else { + t.equal(c.toString(), "q") + } + }) + + f.on("end", function () { t.end() }) + + f.end(new Buffer("abcdefghijklmnopq")) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/pause-resume.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/pause-resume.js new file mode 100644 index 0000000..64d0d09 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/pause-resume.js @@ -0,0 +1,73 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16] + , writeSizes = [15, 16, 17] + , writeCounts = [1, 10]//, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + var paused = false + + f.on("data", function (c) { + timeouts ++ + t.notOk(paused, "should not be paused when emitting data") + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + paused = true + f.pause() + process.nextTick(function () { + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + paused = false + f.resume() + timeouts -- + }) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = expectChunks * blockSize + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 200) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/thorough.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/thorough.js new file mode 100644 index 0000000..1cc9ea0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/thorough.js @@ -0,0 +1,68 @@ +var BlockStream = require("../block-stream.js") + +var blockSizes = [16]//, 25]//, 1024] + , writeSizes = [4, 15, 16, 17, 64 ]//, 64, 100] + , writeCounts = [1, 10]//, 100] + , tap = require("tap") + +writeCounts.forEach(function (writeCount) { +blockSizes.forEach(function (blockSize) { +writeSizes.forEach(function (writeSize) { + tap.test("writeSize=" + writeSize + + " blockSize="+blockSize + + " writeCount="+writeCount, function (t) { + var f = new BlockStream(blockSize) + + var actualChunks = 0 + var actualBytes = 0 + var timeouts = 0 + + f.on("data", function (c) { + timeouts ++ + + actualChunks ++ + actualBytes += c.length + + // make sure that no data gets corrupted, and basic sanity + var before = c.toString() + // simulate a slow write operation + setTimeout(function () { + timeouts -- + + var after = c.toString() + t.equal(after, before, "should not change data") + + // now corrupt it, to find leaks. + for (var i = 0; i < c.length; i ++) { + c[i] = "x".charCodeAt(0) + } + }, 100) + }) + + f.on("end", function () { + // round up to the nearest block size + var expectChunks = Math.ceil(writeSize * writeCount * 2 / blockSize) + var expectBytes = expectChunks * blockSize + t.equal(actualBytes, expectBytes, + "bytes=" + expectBytes + " writeSize=" + writeSize) + t.equal(actualChunks, expectChunks, + "chunks=" + expectChunks + " writeSize=" + writeSize) + + // wait for all the timeout checks to finish, then end the test + setTimeout(function WAIT () { + if (timeouts > 0) return setTimeout(WAIT) + t.end() + }, 100) + }) + + for (var i = 0; i < writeCount; i ++) { + var a = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) a[j] = "a".charCodeAt(0) + var b = new Buffer(writeSize); + for (var j = 0; j < writeSize; j ++) b[j] = "b".charCodeAt(0) + f.write(a) + f.write(b) + } + f.end() + }) +}) }) }) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/two-stream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/two-stream.js new file mode 100644 index 0000000..c6db79a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/block-stream/test/two-stream.js @@ -0,0 +1,59 @@ +var log = console.log, + assert = require( 'assert' ), + BlockStream = require("../block-stream.js"), + isize = 0, tsize = 0, fsize = 0, psize = 0, i = 0, + filter = null, paper = null, stack = null, + +// a source data buffer +tsize = 1 * 1024; // <- 1K +stack = new Buffer( tsize ); +for ( ; i < tsize; i++) stack[i] = "x".charCodeAt(0); + +isize = 1 * 1024; // <- initial packet size with 4K no bug! +fsize = 2 * 1024 ; // <- first block-stream size +psize = Math.ceil( isize / 6 ); // <- second block-stream size + +fexpected = Math.ceil( tsize / fsize ); // <- packets expected for first +pexpected = Math.ceil( tsize / psize ); // <- packets expected for second + + +filter = new BlockStream( fsize, { nopad : true } ); +paper = new BlockStream( psize, { nopad : true } ); + + +var fcounter = 0; +filter.on( 'data', function (c) { + // verify that they're not null-padded + for (var i = 0; i < c.length; i ++) { + assert.strictEqual(c[i], "x".charCodeAt(0)) + } + ++fcounter; +} ); + +var pcounter = 0; +paper.on( 'data', function (c) { + // verify that they're not null-padded + for (var i = 0; i < c.length; i ++) { + assert.strictEqual(c[i], "x".charCodeAt(0)) + } + ++pcounter; +} ); + +filter.pipe( paper ); + +filter.on( 'end', function () { + log("fcounter: %s === %s", fcounter, fexpected) + assert.strictEqual( fcounter, fexpected ); +} ); + +paper.on( 'end', function () { + log("pcounter: %s === %s", pcounter, pexpected); + assert.strictEqual( pcounter, pexpected ); +} ); + + +for ( i = 0, j = isize; j <= tsize; j += isize ) { + filter.write( stack.slice( j - isize, j ) ); +} + +filter.end(); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.npmignore new file mode 100644 index 0000000..494272a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.npmignore @@ -0,0 +1,5 @@ +.*.swp +node_modules/ +examples/deep-copy/ +examples/path/ +examples/filter-copy/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.travis.yml b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.travis.yml new file mode 100644 index 0000000..a092c82 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - iojs + - 0.12 + - 0.10 + - 0.8 +before_install: + - "npm config set spin false" + - "npm install -g npm/npm" diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/README.md new file mode 100644 index 0000000..9d8cb77 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/README.md @@ -0,0 +1,76 @@ +Like FS streams, but with stat on them, and supporting directories and +symbolic links, as well as normal files. Also, you can use this to set +the stats on a file, even if you don't change its contents, or to create +a symlink, etc. + +So, for example, you can "write" a directory, and it'll call `mkdir`. You +can specify a uid and gid, and it'll call `chown`. You can specify a +`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink +and provide a `linkpath` and it'll call `symlink`. + +Note that it won't automatically resolve symbolic links. So, if you +call `fstream.Reader('/some/symlink')` then you'll get an object +that stats and then ends immediately (since it has no data). To follow +symbolic links, do this: `fstream.Reader({path:'/some/symlink', follow: +true })`. + +There are various checks to make sure that the bytes emitted are the +same as the intended size, if the size is set. + +## Examples + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + }) + .write("hello\n") + .end() +``` + +This will create the directories if they're missing, and then write +`hello\n` into the file, chmod it to 0755, and assert that 6 bytes have +been written when it's done. + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + , flags: "a" + }) + .write("hello\n") + .end() +``` + +You can pass flags in, if you want to append to a file. + +```javascript +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , SymbolicLink: true + , mode: "0755" // octal strings supported + }) + .end() +``` + +If isSymbolicLink is a function, it'll be called, and if it returns +true, then it'll treat it as a symlink. If it's not a function, then +any truish value will make a symlink, or you can set `type: +'SymbolicLink'`, which does the same thing. + +Note that the linkpath is relative to the symbolic link location, not +the parent dir or cwd. + +```javascript +fstream + .Reader("path/to/dir") + .pipe(fstream.Writer("path/to/other/dir")) +``` + +This will do like `cp -Rp path/to/dir path/to/other/dir`. If the other +dir exists and isn't a directory, then it'll emit an error. It'll also +set the uid, gid, mode, etc. to be identical. In this way, it's more +like `rsync -a` than simply a copy. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/filter-pipe.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/filter-pipe.js new file mode 100644 index 0000000..fc59cfc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/filter-pipe.js @@ -0,0 +1,133 @@ +var fstream = require('../fstream.js') +var path = require('path') + +var r = fstream.Reader({ + path: path.dirname(__dirname), + filter: function () { + return !this.basename.match(/^\./) && + !this.basename.match(/^node_modules$/) && + !this.basename.match(/^deep-copy$/) && + !this.basename.match(/^filter-copy$/) + } +}) + +// this writer will only write directories +var w = fstream.Writer({ + path: path.resolve(__dirname, 'filter-copy'), + type: 'Directory', + filter: function () { + return this.type === 'Directory' + } +}) + +var indent = '' + +r.on('entry', appears) +r.on('ready', function () { + console.error('ready to begin!', r.path) +}) + +function appears (entry) { + console.error(indent + 'a %s appears!', entry.type, entry.basename, typeof entry.basename) + if (foggy) { + console.error('FOGGY!') + var p = entry + do { + console.error(p.depth, p.path, p._paused) + p = p.parent + } while (p) + + throw new Error('\u001b[mshould not have entries while foggy') + } + indent += '\t' + entry.on('data', missile(entry)) + entry.on('end', runaway(entry)) + entry.on('entry', appears) +} + +var foggy +function missile (entry) { + function liftFog (who) { + if (!foggy) return + if (who) { + console.error('%s breaks the spell!', who && who.path) + } else { + console.error('the spell expires!') + } + console.error('\u001b[mthe fog lifts!\n') + clearTimeout(foggy) + foggy = null + if (entry._paused) entry.resume() + } + + if (entry.type === 'Directory') { + var ended = false + entry.once('end', function () { ended = true }) + return function (c) { + // throw in some pathological pause()/resume() behavior + // just for extra fun. + process.nextTick(function () { + if (!foggy && !ended) { // && Math.random() < 0.3) { + console.error(indent + '%s casts a spell', entry.basename) + console.error('\na slowing fog comes over the battlefield...\n\u001b[32m') + entry.pause() + entry.once('resume', liftFog) + foggy = setTimeout(liftFog, 1000) + } + }) + } + } + + return function (c) { + var e = Math.random() < 0.5 + console.error(indent + '%s %s for %d damage!', + entry.basename, + e ? 'is struck' : 'fires a chunk', + c.length) + } +} + +function runaway (entry) { + return function () { + var e = Math.random() < 0.5 + console.error(indent + '%s %s', + entry.basename, + e ? 'turns to flee' : 'is vanquished!') + indent = indent.slice(0, -1) + } +} + +w.on('entry', attacks) +// w.on('ready', function () { attacks(w) }) +function attacks (entry) { + console.error(indent + '%s %s!', entry.basename, + entry.type === 'Directory' ? 'calls for backup' : 'attacks') + entry.on('entry', attacks) +} + +var ended = false +var i = 1 +r.on('end', function () { + if (foggy) clearTimeout(foggy) + console.error("\u001b[mIT'S OVER!!") + console.error('A WINNAR IS YOU!') + + console.log('ok ' + (i++) + ' A WINNAR IS YOU') + ended = true + // now go through and verify that everything in there is a dir. + var p = path.resolve(__dirname, 'filter-copy') + var checker = fstream.Reader({ path: p }) + checker.checker = true + checker.on('child', function (e) { + var ok = e.type === 'Directory' + console.log((ok ? '' : 'not ') + 'ok ' + (i++) + + ' should be a dir: ' + + e.path.substr(checker.path.length + 1)) + }) +}) + +process.on('exit', function () { + console.log((ended ? '' : 'not ') + 'ok ' + (i++) + ' ended') +}) + +r.pipe(w) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/pipe.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/pipe.js new file mode 100644 index 0000000..c611dd5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/pipe.js @@ -0,0 +1,117 @@ +var fstream = require('../fstream.js') +var path = require('path') + +var r = fstream.Reader({ + path: path.dirname(__dirname), + filter: function () { + return !this.basename.match(/^\./) && + !this.basename.match(/^node_modules$/) && + !this.basename.match(/^deep-copy$/) + } +}) + +var w = fstream.Writer({ + path: path.resolve(__dirname, 'deep-copy'), + type: 'Directory' +}) + +var indent = '' + +r.on('entry', appears) +r.on('ready', function () { + console.error('ready to begin!', r.path) +}) + +function appears (entry) { + console.error(indent + 'a %s appears!', entry.type, entry.basename, typeof entry.basename, entry) + if (foggy) { + console.error('FOGGY!') + var p = entry + do { + console.error(p.depth, p.path, p._paused) + p = p.parent + } while (p) + + throw new Error('\u001b[mshould not have entries while foggy') + } + indent += '\t' + entry.on('data', missile(entry)) + entry.on('end', runaway(entry)) + entry.on('entry', appears) +} + +var foggy +function missile (entry) { + function liftFog (who) { + if (!foggy) return + if (who) { + console.error('%s breaks the spell!', who && who.path) + } else { + console.error('the spell expires!') + } + console.error('\u001b[mthe fog lifts!\n') + clearTimeout(foggy) + foggy = null + if (entry._paused) entry.resume() + } + + if (entry.type === 'Directory') { + var ended = false + entry.once('end', function () { ended = true }) + return function (c) { + // throw in some pathological pause()/resume() behavior + // just for extra fun. + process.nextTick(function () { + if (!foggy && !ended) { // && Math.random() < 0.3) { + console.error(indent + '%s casts a spell', entry.basename) + console.error('\na slowing fog comes over the battlefield...\n\u001b[32m') + entry.pause() + entry.once('resume', liftFog) + foggy = setTimeout(liftFog, 10) + } + }) + } + } + + return function (c) { + var e = Math.random() < 0.5 + console.error(indent + '%s %s for %d damage!', + entry.basename, + e ? 'is struck' : 'fires a chunk', + c.length) + } +} + +function runaway (entry) { + return function () { + var e = Math.random() < 0.5 + console.error(indent + '%s %s', + entry.basename, + e ? 'turns to flee' : 'is vanquished!') + indent = indent.slice(0, -1) + } +} + +w.on('entry', attacks) +// w.on('ready', function () { attacks(w) }) +function attacks (entry) { + console.error(indent + '%s %s!', entry.basename, + entry.type === 'Directory' ? 'calls for backup' : 'attacks') + entry.on('entry', attacks) +} + +var ended = false +r.on('end', function () { + if (foggy) clearTimeout(foggy) + console.error("\u001b[mIT'S OVER!!") + console.error('A WINNAR IS YOU!') + + console.log('ok 1 A WINNAR IS YOU') + ended = true +}) + +process.on('exit', function () { + console.log((ended ? '' : 'not ') + 'ok 2 ended') +}) + +r.pipe(w) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/reader.js new file mode 100644 index 0000000..19affbe --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/reader.js @@ -0,0 +1,68 @@ +var fstream = require('../fstream.js') +var tap = require('tap') +var fs = require('fs') +var path = require('path') +var dir = path.dirname(__dirname) + +tap.test('reader test', function (t) { + var children = -1 + var gotReady = false + var ended = false + + var r = fstream.Reader({ + path: dir, + filter: function () { + // return this.parent === r + return this.parent === r || this === r + } + }) + + r.on('ready', function () { + gotReady = true + children = fs.readdirSync(dir).length + console.error('Setting expected children to ' + children) + t.equal(r.type, 'Directory', 'should be a directory') + }) + + r.on('entry', function (entry) { + children-- + if (!gotReady) { + t.fail('children before ready!') + } + t.equal(entry.dirname, r.path, 'basename is parent dir') + }) + + r.on('error', function (er) { + t.fail(er) + t.end() + process.exit(1) + }) + + r.on('end', function () { + t.equal(children, 0, 'should have seen all children') + ended = true + }) + + var closed = false + r.on('close', function () { + t.ok(ended, 'saw end before close') + t.notOk(closed, 'close should only happen once') + closed = true + t.end() + }) +}) + +tap.test('reader error test', function (t) { + // assumes non-root on a *nix system + var r = fstream.Reader({ path: '/etc/shadow' }) + + r.once('error', function (er) { + t.ok(true) + t.end() + }) + + r.on('end', function () { + t.fail('reader ended without error') + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/symlink-write.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/symlink-write.js new file mode 100644 index 0000000..f6f5109 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/examples/symlink-write.js @@ -0,0 +1,25 @@ +var fstream = require('../fstream.js') +var notOpen = false + +fstream + .Writer({ + path: 'path/to/symlink', + linkpath: './file', + isSymbolicLink: true, + mode: '0755' // octal strings supported + }) + .on('close', function () { + notOpen = true + var fs = require('fs') + var s = fs.lstatSync('path/to/symlink') + var isSym = s.isSymbolicLink() + console.log((isSym ? '' : 'not ') + 'ok 1 should be symlink') + var t = fs.readlinkSync('path/to/symlink') + var isTarget = t === './file' + console.log((isTarget ? '' : 'not ') + 'ok 2 should link to ./file') + }) + .end() + +process.on('exit', function () { + console.log((notOpen ? '' : 'not ') + 'ok 3 should be closed') +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/fstream.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/fstream.js new file mode 100644 index 0000000..c0eb3be --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/fstream.js @@ -0,0 +1,35 @@ +exports.Abstract = require('./lib/abstract.js') +exports.Reader = require('./lib/reader.js') +exports.Writer = require('./lib/writer.js') + +exports.File = { + Reader: require('./lib/file-reader.js'), + Writer: require('./lib/file-writer.js') +} + +exports.Dir = { + Reader: require('./lib/dir-reader.js'), + Writer: require('./lib/dir-writer.js') +} + +exports.Link = { + Reader: require('./lib/link-reader.js'), + Writer: require('./lib/link-writer.js') +} + +exports.Proxy = { + Reader: require('./lib/proxy-reader.js'), + Writer: require('./lib/proxy-writer.js') +} + +exports.Reader.Dir = exports.DirReader = exports.Dir.Reader +exports.Reader.File = exports.FileReader = exports.File.Reader +exports.Reader.Link = exports.LinkReader = exports.Link.Reader +exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader + +exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer +exports.Writer.File = exports.FileWriter = exports.File.Writer +exports.Writer.Link = exports.LinkWriter = exports.Link.Writer +exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer + +exports.collect = require('./lib/collect.js') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/abstract.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/abstract.js new file mode 100644 index 0000000..94af1ae --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/abstract.js @@ -0,0 +1,85 @@ +// the parent class for all fstreams. + +module.exports = Abstract + +var Stream = require('stream').Stream +var inherits = require('inherits') + +function Abstract () { + Stream.call(this) +} + +inherits(Abstract, Stream) + +Abstract.prototype.on = function (ev, fn) { + if (ev === 'ready' && this.ready) { + process.nextTick(fn.bind(this)) + } else { + Stream.prototype.on.call(this, ev, fn) + } + return this +} + +Abstract.prototype.abort = function () { + this._aborted = true + this.emit('abort') +} + +Abstract.prototype.destroy = function () {} + +Abstract.prototype.warn = function (msg, code) { + var self = this + var er = decorate(msg, code, self) + if (!self.listeners('warn')) { + console.error('%s %s\n' + + 'path = %s\n' + + 'syscall = %s\n' + + 'fstream_type = %s\n' + + 'fstream_path = %s\n' + + 'fstream_unc_path = %s\n' + + 'fstream_class = %s\n' + + 'fstream_stack =\n%s\n', + code || 'UNKNOWN', + er.stack, + er.path, + er.syscall, + er.fstream_type, + er.fstream_path, + er.fstream_unc_path, + er.fstream_class, + er.fstream_stack.join('\n')) + } else { + self.emit('warn', er) + } +} + +Abstract.prototype.info = function (msg, code) { + this.emit('info', msg, code) +} + +Abstract.prototype.error = function (msg, code, th) { + var er = decorate(msg, code, this) + if (th) throw er + else this.emit('error', er) +} + +function decorate (er, code, self) { + if (!(er instanceof Error)) er = new Error(er) + er.code = er.code || code + er.path = er.path || self.path + er.fstream_type = er.fstream_type || self.type + er.fstream_path = er.fstream_path || self.path + if (self._path !== self.path) { + er.fstream_unc_path = er.fstream_unc_path || self._path + } + if (self.linkpath) { + er.fstream_linkpath = er.fstream_linkpath || self.linkpath + } + er.fstream_class = er.fstream_class || self.constructor.name + er.fstream_stack = er.fstream_stack || + new Error().stack.split(/\n/).slice(3).map(function (s) { + return s.replace(/^ {4}at /, '') + }) + + return er +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/collect.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/collect.js new file mode 100644 index 0000000..6245e6c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/collect.js @@ -0,0 +1,68 @@ +module.exports = collect + +function collect (stream) { + if (stream._collected) return + + stream._collected = true + stream.pause() + + stream.on('data', save) + stream.on('end', save) + var buf = [] + function save (b) { + if (typeof b === 'string') b = new Buffer(b) + if (Buffer.isBuffer(b) && !b.length) return + buf.push(b) + } + + stream.on('entry', saveEntry) + var entryBuffer = [] + function saveEntry (e) { + collect(e) + entryBuffer.push(e) + } + + stream.on('proxy', proxyPause) + function proxyPause (p) { + p.pause() + } + + // replace the pipe method with a new version that will + // unlock the buffered stuff. if you just call .pipe() + // without a destination, then it'll re-play the events. + stream.pipe = (function (orig) { + return function (dest) { + // console.error(' === open the pipes', dest && dest.path) + + // let the entries flow through one at a time. + // Once they're all done, then we can resume completely. + var e = 0 + ;(function unblockEntry () { + var entry = entryBuffer[e++] + // console.error(" ==== unblock entry", entry && entry.path) + if (!entry) return resume() + entry.on('end', unblockEntry) + if (dest) dest.add(entry) + else stream.emit('entry', entry) + })() + + function resume () { + stream.removeListener('entry', saveEntry) + stream.removeListener('data', save) + stream.removeListener('end', save) + + stream.pipe = orig + if (dest) stream.pipe(dest) + + buf.forEach(function (b) { + if (b) stream.emit('data', b) + else stream.emit('end') + }) + + stream.resume() + } + + return dest + } + })(stream.pipe) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-reader.js new file mode 100644 index 0000000..820cdc8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-reader.js @@ -0,0 +1,252 @@ +// A thing that emits "entry" events with Reader objects +// Pausing it causes it to stop emitting entry events, and also +// pauses the current entry if there is one. + +module.exports = DirReader + +var fs = require('graceful-fs') +var inherits = require('inherits') +var path = require('path') +var Reader = require('./reader.js') +var assert = require('assert').ok + +inherits(DirReader, Reader) + +function DirReader (props) { + var self = this + if (!(self instanceof DirReader)) { + throw new Error('DirReader must be called as constructor.') + } + + // should already be established as a Directory type + if (props.type !== 'Directory' || !props.Directory) { + throw new Error('Non-directory type ' + props.type) + } + + self.entries = null + self._index = -1 + self._paused = false + self._length = -1 + + if (props.sort) { + this.sort = props.sort + } + + Reader.call(this, props) +} + +DirReader.prototype._getEntries = function () { + var self = this + + // race condition. might pause() before calling _getEntries, + // and then resume, and try to get them a second time. + if (self._gotEntries) return + self._gotEntries = true + + fs.readdir(self._path, function (er, entries) { + if (er) return self.error(er) + + self.entries = entries + + self.emit('entries', entries) + if (self._paused) self.once('resume', processEntries) + else processEntries() + + function processEntries () { + self._length = self.entries.length + if (typeof self.sort === 'function') { + self.entries = self.entries.sort(self.sort.bind(self)) + } + self._read() + } + }) +} + +// start walking the dir, and emit an "entry" event for each one. +DirReader.prototype._read = function () { + var self = this + + if (!self.entries) return self._getEntries() + + if (self._paused || self._currentEntry || self._aborted) { + // console.error('DR paused=%j, current=%j, aborted=%j', self._paused, !!self._currentEntry, self._aborted) + return + } + + self._index++ + if (self._index >= self.entries.length) { + if (!self._ended) { + self._ended = true + self.emit('end') + self.emit('close') + } + return + } + + // ok, handle this one, then. + + // save creating a proxy, by stat'ing the thing now. + var p = path.resolve(self._path, self.entries[self._index]) + assert(p !== self._path) + assert(self.entries[self._index]) + + // set this to prevent trying to _read() again in the stat time. + self._currentEntry = p + fs[ self.props.follow ? 'stat' : 'lstat' ](p, function (er, stat) { + if (er) return self.error(er) + + var who = self._proxy || self + + stat.path = p + stat.basename = path.basename(p) + stat.dirname = path.dirname(p) + var childProps = self.getChildProps.call(who, stat) + childProps.path = p + childProps.basename = path.basename(p) + childProps.dirname = path.dirname(p) + + var entry = Reader(childProps, stat) + + // console.error("DR Entry", p, stat.size) + + self._currentEntry = entry + + // "entry" events are for direct entries in a specific dir. + // "child" events are for any and all children at all levels. + // This nomenclature is not completely final. + + entry.on('pause', function (who) { + if (!self._paused && !entry._disowned) { + self.pause(who) + } + }) + + entry.on('resume', function (who) { + if (self._paused && !entry._disowned) { + self.resume(who) + } + }) + + entry.on('stat', function (props) { + self.emit('_entryStat', entry, props) + if (entry._aborted) return + if (entry._paused) { + entry.once('resume', function () { + self.emit('entryStat', entry, props) + }) + } else self.emit('entryStat', entry, props) + }) + + entry.on('ready', function EMITCHILD () { + // console.error("DR emit child", entry._path) + if (self._paused) { + // console.error(" DR emit child - try again later") + // pause the child, and emit the "entry" event once we drain. + // console.error("DR pausing child entry") + entry.pause(self) + return self.once('resume', EMITCHILD) + } + + // skip over sockets. they can't be piped around properly, + // so there's really no sense even acknowledging them. + // if someone really wants to see them, they can listen to + // the "socket" events. + if (entry.type === 'Socket') { + self.emit('socket', entry) + } else { + self.emitEntry(entry) + } + }) + + var ended = false + entry.on('close', onend) + entry.on('disown', onend) + function onend () { + if (ended) return + ended = true + self.emit('childEnd', entry) + self.emit('entryEnd', entry) + self._currentEntry = null + if (!self._paused) { + self._read() + } + } + + // XXX Remove this. Works in node as of 0.6.2 or so. + // Long filenames should not break stuff. + entry.on('error', function (er) { + if (entry._swallowErrors) { + self.warn(er) + entry.emit('end') + entry.emit('close') + } else { + self.emit('error', er) + } + }) + + // proxy up some events. + ;[ + 'child', + 'childEnd', + 'warn' + ].forEach(function (ev) { + entry.on(ev, self.emit.bind(self, ev)) + }) + }) +} + +DirReader.prototype.disown = function (entry) { + entry.emit('beforeDisown') + entry._disowned = true + entry.parent = entry.root = null + if (entry === this._currentEntry) { + this._currentEntry = null + } + entry.emit('disown') +} + +DirReader.prototype.getChildProps = function () { + return { + depth: this.depth + 1, + root: this.root || this, + parent: this, + follow: this.follow, + filter: this.filter, + sort: this.props.sort, + hardlinks: this.props.hardlinks + } +} + +DirReader.prototype.pause = function (who) { + var self = this + if (self._paused) return + who = who || self + self._paused = true + if (self._currentEntry && self._currentEntry.pause) { + self._currentEntry.pause(who) + } + self.emit('pause', who) +} + +DirReader.prototype.resume = function (who) { + var self = this + if (!self._paused) return + who = who || self + + self._paused = false + // console.error('DR Emit Resume', self._path) + self.emit('resume', who) + if (self._paused) { + // console.error('DR Re-paused', self._path) + return + } + + if (self._currentEntry) { + if (self._currentEntry.resume) self._currentEntry.resume(who) + } else self._read() +} + +DirReader.prototype.emitEntry = function (entry) { + this.emit('entry', entry) + this.emit('child', entry) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-writer.js new file mode 100644 index 0000000..aed9e4d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/dir-writer.js @@ -0,0 +1,174 @@ +// It is expected that, when .add() returns false, the consumer +// of the DirWriter will pause until a "drain" event occurs. Note +// that this is *almost always going to be the case*, unless the +// thing being written is some sort of unsupported type, and thus +// skipped over. + +module.exports = DirWriter + +var Writer = require('./writer.js') +var inherits = require('inherits') +var mkdir = require('mkdirp') +var path = require('path') +var collect = require('./collect.js') + +inherits(DirWriter, Writer) + +function DirWriter (props) { + var self = this + if (!(self instanceof DirWriter)) { + self.error('DirWriter must be called as constructor.', null, true) + } + + // should already be established as a Directory type + if (props.type !== 'Directory' || !props.Directory) { + self.error('Non-directory type ' + props.type + ' ' + + JSON.stringify(props), null, true) + } + + Writer.call(this, props) +} + +DirWriter.prototype._create = function () { + var self = this + mkdir(self._path, Writer.dirmode, function (er) { + if (er) return self.error(er) + // ready to start getting entries! + self.ready = true + self.emit('ready') + self._process() + }) +} + +// a DirWriter has an add(entry) method, but its .write() doesn't +// do anything. Why a no-op rather than a throw? Because this +// leaves open the door for writing directory metadata for +// gnu/solaris style dumpdirs. +DirWriter.prototype.write = function () { + return true +} + +DirWriter.prototype.end = function () { + this._ended = true + this._process() +} + +DirWriter.prototype.add = function (entry) { + var self = this + + // console.error('\tadd', entry._path, '->', self._path) + collect(entry) + if (!self.ready || self._currentEntry) { + self._buffer.push(entry) + return false + } + + // create a new writer, and pipe the incoming entry into it. + if (self._ended) { + return self.error('add after end') + } + + self._buffer.push(entry) + self._process() + + return this._buffer.length === 0 +} + +DirWriter.prototype._process = function () { + var self = this + + // console.error('DW Process p=%j', self._processing, self.basename) + + if (self._processing) return + + var entry = self._buffer.shift() + if (!entry) { + // console.error("DW Drain") + self.emit('drain') + if (self._ended) self._finish() + return + } + + self._processing = true + // console.error("DW Entry", entry._path) + + self.emit('entry', entry) + + // ok, add this entry + // + // don't allow recursive copying + var p = entry + var pp + do { + pp = p._path || p.path + if (pp === self.root._path || pp === self._path || + (pp && pp.indexOf(self._path) === 0)) { + // console.error('DW Exit (recursive)', entry.basename, self._path) + self._processing = false + if (entry._collected) entry.pipe() + return self._process() + } + p = p.parent + } while (p) + + // console.error("DW not recursive") + + // chop off the entry's root dir, replace with ours + var props = { + parent: self, + root: self.root || self, + type: entry.type, + depth: self.depth + 1 + } + + pp = entry._path || entry.path || entry.props.path + if (entry.parent) { + pp = pp.substr(entry.parent._path.length + 1) + } + // get rid of any ../../ shenanigans + props.path = path.join(self.path, path.join('/', pp)) + + // if i have a filter, the child should inherit it. + props.filter = self.filter + + // all the rest of the stuff, copy over from the source. + Object.keys(entry.props).forEach(function (k) { + if (!props.hasOwnProperty(k)) { + props[k] = entry.props[k] + } + }) + + // not sure at this point what kind of writer this is. + var child = self._currentChild = new Writer(props) + child.on('ready', function () { + // console.error("DW Child Ready", child.type, child._path) + // console.error(" resuming", entry._path) + entry.pipe(child) + entry.resume() + }) + + // XXX Make this work in node. + // Long filenames should not break stuff. + child.on('error', function (er) { + if (child._swallowErrors) { + self.warn(er) + child.emit('end') + child.emit('close') + } else { + self.emit('error', er) + } + }) + + // we fire _end internally *after* end, so that we don't move on + // until any "end" listeners have had their chance to do stuff. + child.on('close', onend) + var ended = false + function onend () { + if (ended) return + ended = true + // console.error("* DW Child end", child.basename) + self._currentChild = null + self._processing = false + self._process() + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-reader.js new file mode 100644 index 0000000..0757b28 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-reader.js @@ -0,0 +1,150 @@ +// Basically just a wrapper around an fs.ReadStream + +module.exports = FileReader + +var fs = require('graceful-fs') +var inherits = require('inherits') +var Reader = require('./reader.js') +var EOF = {EOF: true} +var CLOSE = {CLOSE: true} + +inherits(FileReader, Reader) + +function FileReader (props) { + // console.error(" FR create", props.path, props.size, new Error().stack) + var self = this + if (!(self instanceof FileReader)) { + throw new Error('FileReader must be called as constructor.') + } + + // should already be established as a File type + // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, + // with a HardLinkReader class. + if (!((props.type === 'Link' && props.Link) || + (props.type === 'File' && props.File))) { + throw new Error('Non-file type ' + props.type) + } + + self._buffer = [] + self._bytesEmitted = 0 + Reader.call(self, props) +} + +FileReader.prototype._getStream = function () { + var self = this + var stream = self._stream = fs.createReadStream(self._path, self.props) + + if (self.props.blksize) { + stream.bufferSize = self.props.blksize + } + + stream.on('open', self.emit.bind(self, 'open')) + + stream.on('data', function (c) { + // console.error('\t\t%d %s', c.length, self.basename) + self._bytesEmitted += c.length + // no point saving empty chunks + if (!c.length) { + return + } else if (self._paused || self._buffer.length) { + self._buffer.push(c) + self._read() + } else self.emit('data', c) + }) + + stream.on('end', function () { + if (self._paused || self._buffer.length) { + // console.error('FR Buffering End', self._path) + self._buffer.push(EOF) + self._read() + } else { + self.emit('end') + } + + if (self._bytesEmitted !== self.props.size) { + self.error("Didn't get expected byte count\n" + + 'expect: ' + self.props.size + '\n' + + 'actual: ' + self._bytesEmitted) + } + }) + + stream.on('close', function () { + if (self._paused || self._buffer.length) { + // console.error('FR Buffering Close', self._path) + self._buffer.push(CLOSE) + self._read() + } else { + // console.error('FR close 1', self._path) + self.emit('close') + } + }) + + stream.on('error', function (e) { + self.emit('error', e) + }) + + self._read() +} + +FileReader.prototype._read = function () { + var self = this + // console.error('FR _read', self._path) + if (self._paused) { + // console.error('FR _read paused', self._path) + return + } + + if (!self._stream) { + // console.error('FR _getStream calling', self._path) + return self._getStream() + } + + // clear out the buffer, if there is one. + if (self._buffer.length) { + // console.error('FR _read has buffer', self._buffer.length, self._path) + var buf = self._buffer + for (var i = 0, l = buf.length; i < l; i++) { + var c = buf[i] + if (c === EOF) { + // console.error('FR Read emitting buffered end', self._path) + self.emit('end') + } else if (c === CLOSE) { + // console.error('FR Read emitting buffered close', self._path) + self.emit('close') + } else { + // console.error('FR Read emitting buffered data', self._path) + self.emit('data', c) + } + + if (self._paused) { + // console.error('FR Read Re-pausing at '+i, self._path) + self._buffer = buf.slice(i) + return + } + } + self._buffer.length = 0 + } + // console.error("FR _read done") + // that's about all there is to it. +} + +FileReader.prototype.pause = function (who) { + var self = this + // console.error('FR Pause', self._path) + if (self._paused) return + who = who || self + self._paused = true + if (self._stream) self._stream.pause() + self.emit('pause', who) +} + +FileReader.prototype.resume = function (who) { + var self = this + // console.error('FR Resume', self._path) + if (!self._paused) return + who = who || self + self.emit('resume', who) + self._paused = false + if (self._stream) self._stream.resume() + self._read() +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-writer.js new file mode 100644 index 0000000..4c803d8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/file-writer.js @@ -0,0 +1,107 @@ +module.exports = FileWriter + +var fs = require('graceful-fs') +var Writer = require('./writer.js') +var inherits = require('inherits') +var EOF = {} + +inherits(FileWriter, Writer) + +function FileWriter (props) { + var self = this + if (!(self instanceof FileWriter)) { + throw new Error('FileWriter must be called as constructor.') + } + + // should already be established as a File type + if (props.type !== 'File' || !props.File) { + throw new Error('Non-file type ' + props.type) + } + + self._buffer = [] + self._bytesWritten = 0 + + Writer.call(this, props) +} + +FileWriter.prototype._create = function () { + var self = this + if (self._stream) return + + var so = {} + if (self.props.flags) so.flags = self.props.flags + so.mode = Writer.filemode + if (self._old && self._old.blksize) so.bufferSize = self._old.blksize + + self._stream = fs.createWriteStream(self._path, so) + + self._stream.on('open', function () { + // console.error("FW open", self._buffer, self._path) + self.ready = true + self._buffer.forEach(function (c) { + if (c === EOF) self._stream.end() + else self._stream.write(c) + }) + self.emit('ready') + // give this a kick just in case it needs it. + self.emit('drain') + }) + + self._stream.on('error', function (er) { self.emit('error', er) }) + + self._stream.on('drain', function () { self.emit('drain') }) + + self._stream.on('close', function () { + // console.error('\n\nFW Stream Close', self._path, self.size) + self._finish() + }) +} + +FileWriter.prototype.write = function (c) { + var self = this + + self._bytesWritten += c.length + + if (!self.ready) { + if (!Buffer.isBuffer(c) && typeof c !== 'string') { + throw new Error('invalid write data') + } + self._buffer.push(c) + return false + } + + var ret = self._stream.write(c) + // console.error('\t-- fw wrote, _stream says', ret, self._stream._queue.length) + + // allow 2 buffered writes, because otherwise there's just too + // much stop and go bs. + if (ret === false && self._stream._queue) { + return self._stream._queue.length <= 2 + } else { + return ret + } +} + +FileWriter.prototype.end = function (c) { + var self = this + + if (c) self.write(c) + + if (!self.ready) { + self._buffer.push(EOF) + return false + } + + return self._stream.end() +} + +FileWriter.prototype._finish = function () { + var self = this + if (typeof self.size === 'number' && self._bytesWritten !== self.size) { + self.error( + 'Did not get expected byte count.\n' + + 'expect: ' + self.size + '\n' + + 'actual: ' + self._bytesWritten) + } + Writer.prototype._finish.call(self) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/get-type.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/get-type.js new file mode 100644 index 0000000..19f6a65 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/get-type.js @@ -0,0 +1,33 @@ +module.exports = getType + +function getType (st) { + var types = [ + 'Directory', + 'File', + 'SymbolicLink', + 'Link', // special for hardlinks from tarballs + 'BlockDevice', + 'CharacterDevice', + 'FIFO', + 'Socket' + ] + var type + + if (st.type && types.indexOf(st.type) !== -1) { + st[st.type] = true + return st.type + } + + for (var i = 0, l = types.length; i < l; i++) { + type = types[i] + var is = st[type] || st['is' + type] + if (typeof is === 'function') is = is.call(st) + if (is) { + st[type] = true + st.type = type + return type + } + } + + return null +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-reader.js new file mode 100644 index 0000000..a44dd39 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-reader.js @@ -0,0 +1,53 @@ +// Basically just a wrapper around an fs.readlink +// +// XXX: Enhance this to support the Link type, by keeping +// a lookup table of {:}, so that hardlinks +// can be preserved in tarballs. + +module.exports = LinkReader + +var fs = require('graceful-fs') +var inherits = require('inherits') +var Reader = require('./reader.js') + +inherits(LinkReader, Reader) + +function LinkReader (props) { + var self = this + if (!(self instanceof LinkReader)) { + throw new Error('LinkReader must be called as constructor.') + } + + if (!((props.type === 'Link' && props.Link) || + (props.type === 'SymbolicLink' && props.SymbolicLink))) { + throw new Error('Non-link type ' + props.type) + } + + Reader.call(self, props) +} + +// When piping a LinkReader into a LinkWriter, we have to +// already have the linkpath property set, so that has to +// happen *before* the "ready" event, which means we need to +// override the _stat method. +LinkReader.prototype._stat = function (currentStat) { + var self = this + fs.readlink(self._path, function (er, linkpath) { + if (er) return self.error(er) + self.linkpath = self.props.linkpath = linkpath + self.emit('linkpath', linkpath) + Reader.prototype._stat.call(self, currentStat) + }) +} + +LinkReader.prototype._read = function () { + var self = this + if (self._paused) return + // basically just a no-op, since we got all the info we need + // from the _stat method + if (!self._ended) { + self.emit('end') + self.emit('close') + self._ended = true + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-writer.js new file mode 100644 index 0000000..07a9abf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/link-writer.js @@ -0,0 +1,95 @@ +module.exports = LinkWriter + +var fs = require('graceful-fs') +var Writer = require('./writer.js') +var inherits = require('inherits') +var path = require('path') +var rimraf = require('rimraf') + +inherits(LinkWriter, Writer) + +function LinkWriter (props) { + var self = this + if (!(self instanceof LinkWriter)) { + throw new Error('LinkWriter must be called as constructor.') + } + + // should already be established as a Link type + if (!((props.type === 'Link' && props.Link) || + (props.type === 'SymbolicLink' && props.SymbolicLink))) { + throw new Error('Non-link type ' + props.type) + } + + if (props.linkpath === '') props.linkpath = '.' + if (!props.linkpath) { + self.error('Need linkpath property to create ' + props.type) + } + + Writer.call(this, props) +} + +LinkWriter.prototype._create = function () { + // console.error(" LW _create") + var self = this + var hard = self.type === 'Link' || process.platform === 'win32' + var link = hard ? 'link' : 'symlink' + var lp = hard ? path.resolve(self.dirname, self.linkpath) : self.linkpath + + // can only change the link path by clobbering + // For hard links, let's just assume that's always the case, since + // there's no good way to read them if we don't already know. + if (hard) return clobber(self, lp, link) + + fs.readlink(self._path, function (er, p) { + // only skip creation if it's exactly the same link + if (p && p === lp) return finish(self) + clobber(self, lp, link) + }) +} + +function clobber (self, lp, link) { + rimraf(self._path, function (er) { + if (er) return self.error(er) + create(self, lp, link) + }) +} + +function create (self, lp, link) { + fs[link](lp, self._path, function (er) { + // if this is a hard link, and we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier in. + // Additionally, an EPERM or EACCES can happen on win32 if it's trying + // to make a link to a directory. Again, just skip it. + // A better solution would be to have fs.symlink be supported on + // windows in some nice fashion. + if (er) { + if ((er.code === 'ENOENT' || + er.code === 'EACCES' || + er.code === 'EPERM') && process.platform === 'win32') { + self.ready = true + self.emit('ready') + self.emit('end') + self.emit('close') + self.end = self._finish = function () {} + } else return self.error(er) + } + finish(self) + }) +} + +function finish (self) { + self.ready = true + self.emit('ready') + if (self._ended && !self._finished) self._finish() +} + +LinkWriter.prototype.end = function () { + // console.error("LW finish in end") + this._ended = true + if (this.ready) { + this._finished = true + this._finish() + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-reader.js new file mode 100644 index 0000000..4f431c9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-reader.js @@ -0,0 +1,95 @@ +// A reader for when we don't yet know what kind of thing +// the thing is. + +module.exports = ProxyReader + +var Reader = require('./reader.js') +var getType = require('./get-type.js') +var inherits = require('inherits') +var fs = require('graceful-fs') + +inherits(ProxyReader, Reader) + +function ProxyReader (props) { + var self = this + if (!(self instanceof ProxyReader)) { + throw new Error('ProxyReader must be called as constructor.') + } + + self.props = props + self._buffer = [] + self.ready = false + + Reader.call(self, props) +} + +ProxyReader.prototype._stat = function () { + var self = this + var props = self.props + // stat the thing to see what the proxy should be. + var stat = props.follow ? 'stat' : 'lstat' + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = 'File' + } else { + type = getType(current) + } + + props[type] = true + props.type = self.type = type + + self._old = current + self._addProxy(Reader(props, current)) + }) +} + +ProxyReader.prototype._addProxy = function (proxy) { + var self = this + if (self._proxyTarget) { + return self.error('proxy already set') + } + + self._proxyTarget = proxy + proxy._proxy = self + + ;[ + 'error', + 'data', + 'end', + 'close', + 'linkpath', + 'entry', + 'entryEnd', + 'child', + 'childEnd', + 'warn', + 'stat' + ].forEach(function (ev) { + // console.error('~~ proxy event', ev, self.path) + proxy.on(ev, self.emit.bind(self, ev)) + }) + + self.emit('proxy', proxy) + + proxy.on('ready', function () { + // console.error("~~ proxy is ready!", self.path) + self.ready = true + self.emit('ready') + }) + + var calls = self._buffer + self._buffer.length = 0 + calls.forEach(function (c) { + proxy[c[0]].apply(proxy, c[1]) + }) +} + +ProxyReader.prototype.pause = function () { + return this._proxyTarget ? this._proxyTarget.pause() : false +} + +ProxyReader.prototype.resume = function () { + return this._proxyTarget ? this._proxyTarget.resume() : false +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-writer.js new file mode 100644 index 0000000..a654462 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/proxy-writer.js @@ -0,0 +1,111 @@ +// A writer for when we don't know what kind of thing +// the thing is. That is, it's not explicitly set, +// so we're going to make it whatever the thing already +// is, or "File" +// +// Until then, collect all events. + +module.exports = ProxyWriter + +var Writer = require('./writer.js') +var getType = require('./get-type.js') +var inherits = require('inherits') +var collect = require('./collect.js') +var fs = require('fs') + +inherits(ProxyWriter, Writer) + +function ProxyWriter (props) { + var self = this + if (!(self instanceof ProxyWriter)) { + throw new Error('ProxyWriter must be called as constructor.') + } + + self.props = props + self._needDrain = false + + Writer.call(self, props) +} + +ProxyWriter.prototype._stat = function () { + var self = this + var props = self.props + // stat the thing to see what the proxy should be. + var stat = props.follow ? 'stat' : 'lstat' + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = 'File' + } else { + type = getType(current) + } + + props[type] = true + props.type = self.type = type + + self._old = current + self._addProxy(Writer(props, current)) + }) +} + +ProxyWriter.prototype._addProxy = function (proxy) { + // console.error("~~ set proxy", this.path) + var self = this + if (self._proxy) { + return self.error('proxy already set') + } + + self._proxy = proxy + ;[ + 'ready', + 'error', + 'close', + 'pipe', + 'drain', + 'warn' + ].forEach(function (ev) { + proxy.on(ev, self.emit.bind(self, ev)) + }) + + self.emit('proxy', proxy) + + var calls = self._buffer + calls.forEach(function (c) { + // console.error("~~ ~~ proxy buffered call", c[0], c[1]) + proxy[c[0]].apply(proxy, c[1]) + }) + self._buffer.length = 0 + if (self._needsDrain) self.emit('drain') +} + +ProxyWriter.prototype.add = function (entry) { + // console.error("~~ proxy add") + collect(entry) + + if (!this._proxy) { + this._buffer.push(['add', [entry]]) + this._needDrain = true + return false + } + return this._proxy.add(entry) +} + +ProxyWriter.prototype.write = function (c) { + // console.error('~~ proxy write') + if (!this._proxy) { + this._buffer.push(['write', [c]]) + this._needDrain = true + return false + } + return this._proxy.write(c) +} + +ProxyWriter.prototype.end = function (c) { + // console.error('~~ proxy end') + if (!this._proxy) { + this._buffer.push(['end', [c]]) + return false + } + return this._proxy.end(c) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/reader.js new file mode 100644 index 0000000..1d007ee --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/reader.js @@ -0,0 +1,255 @@ +module.exports = Reader + +var fs = require('graceful-fs') +var Stream = require('stream').Stream +var inherits = require('inherits') +var path = require('path') +var getType = require('./get-type.js') +var hardLinks = Reader.hardLinks = {} +var Abstract = require('./abstract.js') + +// Must do this *before* loading the child classes +inherits(Reader, Abstract) + +var LinkReader = require('./link-reader.js') + +function Reader (props, currentStat) { + var self = this + if (!(self instanceof Reader)) return new Reader(props, currentStat) + + if (typeof props === 'string') { + props = { path: props } + } + + if (!props.path) { + self.error('Must provide a path', null, true) + } + + // polymorphism. + // call fstream.Reader(dir) to get a DirReader object, etc. + // Note that, unlike in the Writer case, ProxyReader is going + // to be the *normal* state of affairs, since we rarely know + // the type of a file prior to reading it. + + var type + var ClassType + + if (props.type && typeof props.type === 'function') { + type = props.type + ClassType = type + } else { + type = getType(props) + ClassType = Reader + } + + if (currentStat && !type) { + type = getType(currentStat) + props[type] = true + props.type = type + } + + switch (type) { + case 'Directory': + ClassType = require('./dir-reader.js') + break + + case 'Link': + // XXX hard links are just files. + // However, it would be good to keep track of files' dev+inode + // and nlink values, and create a HardLinkReader that emits + // a linkpath value of the original copy, so that the tar + // writer can preserve them. + // ClassType = HardLinkReader + // break + + case 'File': + ClassType = require('./file-reader.js') + break + + case 'SymbolicLink': + ClassType = LinkReader + break + + case 'Socket': + ClassType = require('./socket-reader.js') + break + + case null: + ClassType = require('./proxy-reader.js') + break + } + + if (!(self instanceof ClassType)) { + return new ClassType(props) + } + + Abstract.call(self) + + self.readable = true + self.writable = false + + self.type = type + self.props = props + self.depth = props.depth = props.depth || 0 + self.parent = props.parent || null + self.root = props.root || (props.parent && props.parent.root) || self + + self._path = self.path = path.resolve(props.path) + if (process.platform === 'win32') { + self.path = self._path = self.path.replace(/\?/g, '_') + if (self._path.length >= 260) { + // how DOES one create files on the moon? + // if the path has spaces in it, then UNC will fail. + self._swallowErrors = true + // if (self._path.indexOf(" ") === -1) { + self._path = '\\\\?\\' + self.path.replace(/\//g, '\\') + // } + } + } + self.basename = props.basename = path.basename(self.path) + self.dirname = props.dirname = path.dirname(self.path) + + // these have served their purpose, and are now just noisy clutter + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + self.size = props.size + self.filter = typeof props.filter === 'function' ? props.filter : null + if (props.sort === 'alpha') props.sort = alphasort + + // start the ball rolling. + // this will stat the thing, and then call self._read() + // to start reading whatever it is. + // console.error("calling stat", props.path, currentStat) + self._stat(currentStat) +} + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + +Reader.prototype._stat = function (currentStat) { + var self = this + var props = self.props + var stat = props.follow ? 'stat' : 'lstat' + // console.error("Reader._stat", self._path, currentStat) + if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) + else fs[stat](self._path, statCb) + + function statCb (er, props_) { + // console.error("Reader._stat, statCb", self._path, props_, props_.nlink) + if (er) return self.error(er) + + Object.keys(props_).forEach(function (k) { + props[k] = props_[k] + }) + + // if it's not the expected size, then abort here. + if (undefined !== self.size && props.size !== self.size) { + return self.error('incorrect size') + } + self.size = props.size + + var type = getType(props) + var handleHardlinks = props.hardlinks !== false + + // special little thing for handling hardlinks. + if (handleHardlinks && type !== 'Directory' && props.nlink && props.nlink > 1) { + var k = props.dev + ':' + props.ino + // console.error("Reader has nlink", self._path, k) + if (hardLinks[k] === self._path || !hardLinks[k]) { + hardLinks[k] = self._path + } else { + // switch into hardlink mode. + type = self.type = self.props.type = 'Link' + self.Link = self.props.Link = true + self.linkpath = self.props.linkpath = hardLinks[k] + // console.error("Hardlink detected, switching mode", self._path, self.linkpath) + // Setting __proto__ would arguably be the "correct" + // approach here, but that just seems too wrong. + self._stat = self._read = LinkReader.prototype._read + } + } + + if (self.type && self.type !== type) { + self.error('Unexpected type: ' + type) + } + + // if the filter doesn't pass, then just skip over this one. + // still have to emit end so that dir-walking can move on. + if (self.filter) { + var who = self._proxy || self + // special handling for ProxyReaders + if (!self.filter.call(who, who, props)) { + if (!self._disowned) { + self.abort() + self.emit('end') + self.emit('close') + } + return + } + } + + // last chance to abort or disown before the flow starts! + var events = ['_stat', 'stat', 'ready'] + var e = 0 + ;(function go () { + if (self._aborted) { + self.emit('end') + self.emit('close') + return + } + + if (self._paused && self.type !== 'Directory') { + self.once('resume', go) + return + } + + var ev = events[e++] + if (!ev) { + return self._read() + } + self.emit(ev, props) + go() + })() + } +} + +Reader.prototype.pipe = function (dest) { + var self = this + if (typeof dest.add === 'function') { + // piping to a multi-compatible, and we've got directory entries. + self.on('entry', function (entry) { + var ret = dest.add(entry) + if (ret === false) { + self.pause() + } + }) + } + + // console.error("R Pipe apply Stream Pipe") + return Stream.prototype.pipe.apply(this, arguments) +} + +Reader.prototype.pause = function (who) { + this._paused = true + who = who || this + this.emit('pause', who) + if (this._stream) this._stream.pause(who) +} + +Reader.prototype.resume = function (who) { + this._paused = false + who = who || this + this.emit('resume', who) + if (this._stream) this._stream.resume(who) + this._read() +} + +Reader.prototype._read = function () { + this.error('Cannot read unknown type: ' + this.type) +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/socket-reader.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/socket-reader.js new file mode 100644 index 0000000..e0456ba --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/socket-reader.js @@ -0,0 +1,36 @@ +// Just get the stats, and then don't do anything. +// You can't really "read" from a socket. You "connect" to it. +// Mostly, this is here so that reading a dir with a socket in it +// doesn't blow up. + +module.exports = SocketReader + +var inherits = require('inherits') +var Reader = require('./reader.js') + +inherits(SocketReader, Reader) + +function SocketReader (props) { + var self = this + if (!(self instanceof SocketReader)) { + throw new Error('SocketReader must be called as constructor.') + } + + if (!(props.type === 'Socket' && props.Socket)) { + throw new Error('Non-socket type ' + props.type) + } + + Reader.call(self, props) +} + +SocketReader.prototype._read = function () { + var self = this + if (self._paused) return + // basically just a no-op, since we got all the info we have + // from the _stat method + if (!self._ended) { + self.emit('end') + self.emit('close') + self._ended = true + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/writer.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/writer.js new file mode 100644 index 0000000..25a608d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/lib/writer.js @@ -0,0 +1,390 @@ +module.exports = Writer + +var fs = require('graceful-fs') +var inherits = require('inherits') +var rimraf = require('rimraf') +var mkdir = require('mkdirp') +var path = require('path') +var umask = process.platform === 'win32' ? 0 : process.umask() +var getType = require('./get-type.js') +var Abstract = require('./abstract.js') + +// Must do this *before* loading the child classes +inherits(Writer, Abstract) + +Writer.dirmode = parseInt('0777', 8) & (~umask) +Writer.filemode = parseInt('0666', 8) & (~umask) + +var DirWriter = require('./dir-writer.js') +var LinkWriter = require('./link-writer.js') +var FileWriter = require('./file-writer.js') +var ProxyWriter = require('./proxy-writer.js') + +// props is the desired state. current is optionally the current stat, +// provided here so that subclasses can avoid statting the target +// more than necessary. +function Writer (props, current) { + var self = this + + if (typeof props === 'string') { + props = { path: props } + } + + if (!props.path) self.error('Must provide a path', null, true) + + // polymorphism. + // call fstream.Writer(dir) to get a DirWriter object, etc. + var type = getType(props) + var ClassType = Writer + + switch (type) { + case 'Directory': + ClassType = DirWriter + break + case 'File': + ClassType = FileWriter + break + case 'Link': + case 'SymbolicLink': + ClassType = LinkWriter + break + case null: + default: + // Don't know yet what type to create, so we wrap in a proxy. + ClassType = ProxyWriter + break + } + + if (!(self instanceof ClassType)) return new ClassType(props) + + // now get down to business. + + Abstract.call(self) + + // props is what we want to set. + // set some convenience properties as well. + self.type = props.type + self.props = props + self.depth = props.depth || 0 + self.clobber = props.clobber === false ? props.clobber : true + self.parent = props.parent || null + self.root = props.root || (props.parent && props.parent.root) || self + + self._path = self.path = path.resolve(props.path) + if (process.platform === 'win32') { + self.path = self._path = self.path.replace(/\?/g, '_') + if (self._path.length >= 260) { + self._swallowErrors = true + self._path = '\\\\?\\' + self.path.replace(/\//g, '\\') + } + } + self.basename = path.basename(props.path) + self.dirname = path.dirname(props.path) + self.linkpath = props.linkpath || null + + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + self.size = props.size + + if (typeof props.mode === 'string') { + props.mode = parseInt(props.mode, 8) + } + + self.readable = false + self.writable = true + + // buffer until ready, or while handling another entry + self._buffer = [] + self.ready = false + + self.filter = typeof props.filter === 'function' ? props.filter : null + + // start the ball rolling. + // this checks what's there already, and then calls + // self._create() to call the impl-specific creation stuff. + self._stat(current) +} + +// Calling this means that it's something we can't create. +// Just assert that it's already there, otherwise raise a warning. +Writer.prototype._create = function () { + var self = this + fs[self.props.follow ? 'stat' : 'lstat'](self._path, function (er) { + if (er) { + return self.warn('Cannot create ' + self._path + '\n' + + 'Unsupported type: ' + self.type, 'ENOTSUP') + } + self._finish() + }) +} + +Writer.prototype._stat = function (current) { + var self = this + var props = self.props + var stat = props.follow ? 'stat' : 'lstat' + var who = self._proxy || self + + if (current) statCb(null, current) + else fs[stat](self._path, statCb) + + function statCb (er, current) { + if (self.filter && !self.filter.call(who, who, current)) { + self._aborted = true + self.emit('end') + self.emit('close') + return + } + + // if it's not there, great. We'll just create it. + // if it is there, then we'll need to change whatever differs + if (er || !current) { + return create(self) + } + + self._old = current + var currentType = getType(current) + + // if it's a type change, then we need to clobber or error. + // if it's not a type change, then let the impl take care of it. + if (currentType !== self.type) { + return rimraf(self._path, function (er) { + if (er) return self.error(er) + self._old = null + create(self) + }) + } + + // otherwise, just handle in the app-specific way + // this creates a fs.WriteStream, or mkdir's, or whatever + create(self) + } +} + +function create (self) { + // console.error("W create", self._path, Writer.dirmode) + + // XXX Need to clobber non-dirs that are in the way, + // unless { clobber: false } in the props. + mkdir(path.dirname(self._path), Writer.dirmode, function (er, made) { + // console.error("W created", path.dirname(self._path), er) + if (er) return self.error(er) + + // later on, we have to set the mode and owner for these + self._madeDir = made + return self._create() + }) +} + +function endChmod (self, want, current, path, cb) { + var wantMode = want.mode + var chmod = want.follow || self.type !== 'SymbolicLink' + ? 'chmod' : 'lchmod' + + if (!fs[chmod]) return cb() + if (typeof wantMode !== 'number') return cb() + + var curMode = current.mode & parseInt('0777', 8) + wantMode = wantMode & parseInt('0777', 8) + if (wantMode === curMode) return cb() + + fs[chmod](path, wantMode, cb) +} + +function endChown (self, want, current, path, cb) { + // Don't even try it unless root. Too easy to EPERM. + if (process.platform === 'win32') return cb() + if (!process.getuid || process.getuid() !== 0) return cb() + if (typeof want.uid !== 'number' && + typeof want.gid !== 'number') return cb() + + if (current.uid === want.uid && + current.gid === want.gid) return cb() + + var chown = (self.props.follow || self.type !== 'SymbolicLink') + ? 'chown' : 'lchown' + if (!fs[chown]) return cb() + + if (typeof want.uid !== 'number') want.uid = current.uid + if (typeof want.gid !== 'number') want.gid = current.gid + + fs[chown](path, want.uid, want.gid, cb) +} + +function endUtimes (self, want, current, path, cb) { + if (!fs.utimes || process.platform === 'win32') return cb() + + var utimes = (want.follow || self.type !== 'SymbolicLink') + ? 'utimes' : 'lutimes' + + if (utimes === 'lutimes' && !fs[utimes]) { + utimes = 'utimes' + } + + if (!fs[utimes]) return cb() + + var curA = current.atime + var curM = current.mtime + var meA = want.atime + var meM = want.mtime + + if (meA === undefined) meA = curA + if (meM === undefined) meM = curM + + if (!isDate(meA)) meA = new Date(meA) + if (!isDate(meM)) meA = new Date(meM) + + if (meA.getTime() === curA.getTime() && + meM.getTime() === curM.getTime()) return cb() + + fs[utimes](path, meA, meM, cb) +} + +// XXX This function is beastly. Break it up! +Writer.prototype._finish = function () { + var self = this + + if (self._finishing) return + self._finishing = true + + // console.error(" W Finish", self._path, self.size) + + // set up all the things. + // At this point, we're already done writing whatever we've gotta write, + // adding files to the dir, etc. + var todo = 0 + var errState = null + var done = false + + if (self._old) { + // the times will almost *certainly* have changed. + // adds the utimes syscall, but remove another stat. + self._old.atime = new Date(0) + self._old.mtime = new Date(0) + // console.error(" W Finish Stale Stat", self._path, self.size) + setProps(self._old) + } else { + var stat = self.props.follow ? 'stat' : 'lstat' + // console.error(" W Finish Stating", self._path, self.size) + fs[stat](self._path, function (er, current) { + // console.error(" W Finish Stated", self._path, self.size, current) + if (er) { + // if we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier on. + if (er.code === 'ENOENT' && + (self.type === 'Link' || self.type === 'SymbolicLink') && + process.platform === 'win32') { + self.ready = true + self.emit('ready') + self.emit('end') + self.emit('close') + self.end = self._finish = function () {} + return + } else return self.error(er) + } + setProps(self._old = current) + }) + } + + return + + function setProps (current) { + todo += 3 + endChmod(self, self.props, current, self._path, next('chmod')) + endChown(self, self.props, current, self._path, next('chown')) + endUtimes(self, self.props, current, self._path, next('utimes')) + } + + function next (what) { + return function (er) { + // console.error(" W Finish", what, todo) + if (errState) return + if (er) { + er.fstream_finish_call = what + return self.error(errState = er) + } + if (--todo > 0) return + if (done) return + done = true + + // we may still need to set the mode/etc. on some parent dirs + // that were created previously. delay end/close until then. + if (!self._madeDir) return end() + else endMadeDir(self, self._path, end) + + function end (er) { + if (er) { + er.fstream_finish_call = 'setupMadeDir' + return self.error(er) + } + // all the props have been set, so we're completely done. + self.emit('end') + self.emit('close') + } + } + } +} + +function endMadeDir (self, p, cb) { + var made = self._madeDir + // everything *between* made and path.dirname(self._path) + // needs to be set up. Note that this may just be one dir. + var d = path.dirname(p) + + endMadeDir_(self, d, function (er) { + if (er) return cb(er) + if (d === made) { + return cb() + } + endMadeDir(self, d, cb) + }) +} + +function endMadeDir_ (self, p, cb) { + var dirProps = {} + Object.keys(self.props).forEach(function (k) { + dirProps[k] = self.props[k] + + // only make non-readable dirs if explicitly requested. + if (k === 'mode' && self.type !== 'Directory') { + dirProps[k] = dirProps[k] | parseInt('0111', 8) + } + }) + + var todo = 3 + var errState = null + fs.stat(p, function (er, current) { + if (er) return cb(errState = er) + endChmod(self, dirProps, current, p, next) + endChown(self, dirProps, current, p, next) + endUtimes(self, dirProps, current, p, next) + }) + + function next (er) { + if (errState) return + if (er) return cb(errState = er) + if (--todo === 0) return cb() + } +} + +Writer.prototype.pipe = function () { + this.error("Can't pipe from writable stream") +} + +Writer.prototype.add = function () { + this.error("Can't add to non-Directory type") +} + +Writer.prototype.write = function () { + return true +} + +function objectToString (d) { + return Object.prototype.toString.call(d) +} + +function isDate (d) { + return typeof d === 'object' && objectToString(d) === '[object Date]' +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/.npmignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..13a2e86 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/README.md @@ -0,0 +1,36 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](http://api.nodejs.org/fs.html) + +graceful-fs: + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFileSync('some-file-or-whatever') +``` diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/fs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/fs.js new file mode 100644 index 0000000..64ad980 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/fs.js @@ -0,0 +1,11 @@ +// eeeeeevvvvviiiiiiillllll +// more evil than monkey-patching the native builtin? +// Not sure. + +var mod = require("module") +var pre = '(function (exports, require, module, __filename, __dirname) { ' +var post = '});' +var src = pre + process.binding('natives').fs + post +var vm = require('vm') +var fn = vm.runInThisContext(src) +fn(exports, require, module, __filename, __dirname) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..fb206b8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,158 @@ +// Monkey-patching the fs module. +// It's ugly, but there is simply no other way to do this. +var fs = module.exports = require('./fs.js') + +var assert = require('assert') + +// fix up some busted stuff, mostly on windows and old nodes +require('./polyfills.js') + +var util = require('util') + +function noop () {} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs') +else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS: ' + m.split(/\n/).join('\nGFS: ') + console.error(m) + } + +if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug('fds', fds) + debug(queue) + assert.equal(queue.length, 0) + }) +} + + +var originalOpen = fs.open +fs.open = open + +function open(path, flags, mode, cb) { + if (typeof mode === "function") cb = mode, mode = null + if (typeof cb !== "function") cb = noop + new OpenReq(path, flags, mode, cb) +} + +function OpenReq(path, flags, mode, cb) { + this.path = path + this.flags = flags + this.mode = mode + this.cb = cb + Req.call(this) +} + +util.inherits(OpenReq, Req) + +OpenReq.prototype.process = function() { + originalOpen.call(fs, this.path, this.flags, this.mode, this.done) +} + +var fds = {} +OpenReq.prototype.done = function(er, fd) { + debug('open done', er, fd) + if (fd) + fds['fd' + fd] = this.path + Req.prototype.done.call(this, er, fd) +} + + +var originalReaddir = fs.readdir +fs.readdir = readdir + +function readdir(path, cb) { + if (typeof cb !== "function") cb = noop + new ReaddirReq(path, cb) +} + +function ReaddirReq(path, cb) { + this.path = path + this.cb = cb + Req.call(this) +} + +util.inherits(ReaddirReq, Req) + +ReaddirReq.prototype.process = function() { + originalReaddir.call(fs, this.path, this.done) +} + +ReaddirReq.prototype.done = function(er, files) { + if (files && files.sort) + files = files.sort() + Req.prototype.done.call(this, er, files) + onclose() +} + + +var originalClose = fs.close +fs.close = close + +function close (fd, cb) { + debug('close', fd) + if (typeof cb !== "function") cb = noop + delete fds['fd' + fd] + originalClose.call(fs, fd, function(er) { + onclose() + cb(er) + }) +} + + +var originalCloseSync = fs.closeSync +fs.closeSync = closeSync + +function closeSync (fd) { + try { + return originalCloseSync(fd) + } finally { + onclose() + } +} + + +// Req class +function Req () { + // start processing + this.done = this.done.bind(this) + this.failures = 0 + this.process() +} + +Req.prototype.done = function (er, result) { + var tryAgain = false + if (er) { + var code = er.code + var tryAgain = code === "EMFILE" || code === "ENFILE" + if (process.platform === "win32") + tryAgain = tryAgain || code === "OK" + } + + if (tryAgain) { + this.failures ++ + enqueue(this) + } else { + var cb = this.cb + cb(er, result) + } +} + +var queue = [] + +function enqueue(req) { + queue.push(req) + debug('enqueue %d %s', queue.length, req.constructor.name, req) +} + +function onclose() { + var req = queue.shift() + if (req) { + debug('process', req.constructor.name, req) + req.process() + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..08930cf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/package.json @@ -0,0 +1,71 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "3.0.8", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-graceful-fs.git" + }, + "main": "graceful-fs.js", + "engines": { + "node": ">=0.4.0" + }, + "directories": { + "test": "test" + }, + "scripts": { + "test": "tap test/*.js" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "devDependencies": { + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^1.2.0" + }, + "gitHead": "45c57aa5e323c35a985a525de6f0c9a6ef59e1f8", + "bugs": { + "url": "https://github.com/isaacs/node-graceful-fs/issues" + }, + "homepage": "https://github.com/isaacs/node-graceful-fs#readme", + "_id": "graceful-fs@3.0.8", + "_shasum": "ce813e725fa82f7e6147d51c9a5ca68270551c22", + "_from": "graceful-fs@>=3.0.0 <4.0.0", + "_npmVersion": "2.10.1", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + "dist": { + "shasum": "ce813e725fa82f7e6147d51c9a5ca68270551c22", + "tarball": "http://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.8.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "_resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-3.0.8.tgz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/polyfills.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000..4270539 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,255 @@ +var fs = require('./fs.js') +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} + +// (re-)implement some things that are known busted or missing. + +// lchmod, broken prior to 0.6.2 +// back-port the fix here. +if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + fs.lchmod = function (path, mode, callback) { + callback = callback || noop + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var err, err2 + try { + var ret = fs.fchmodSync(fd, mode) + } catch (er) { + err = er + } + try { + fs.closeSync(fd) + } catch (er) { + err2 = er + } + if (err || err2) throw (err || err2) + return ret + } +} + + +// lutimes implementation, or no-op +if (!fs.lutimes) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + cb = cb || noop + if (er) return cb(er) + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + return cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + , err + , err2 + , ret + + try { + var ret = fs.futimesSync(fd, at, mt) + } catch (er) { + err = er + } + try { + fs.closeSync(fd) + } catch (er) { + err2 = er + } + if (err || err2) throw (err || err2) + return ret + } + + } else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) { + // maybe utimensat will be bound soonish? + fs.lutimes = function (path, at, mt, cb) { + fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb) + } + + fs.lutimesSync = function (path, at, mt) { + return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW) + } + + } else { + fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) } + fs.lutimesSync = function () {} + } +} + + +// https://github.com/isaacs/node-graceful-fs/issues/4 +// Chown should not fail on einval or eperm if non-root. +// It should not fail on enosys ever, as this just indicates +// that a fs doesn't support the intended operation. + +fs.chown = chownFix(fs.chown) +fs.fchown = chownFix(fs.fchown) +fs.lchown = chownFix(fs.lchown) + +fs.chmod = chownFix(fs.chmod) +fs.fchmod = chownFix(fs.fchmod) +fs.lchmod = chownFix(fs.lchmod) + +fs.chownSync = chownFixSync(fs.chownSync) +fs.fchownSync = chownFixSync(fs.fchownSync) +fs.lchownSync = chownFixSync(fs.lchownSync) + +fs.chmodSync = chownFix(fs.chmodSync) +fs.fchmodSync = chownFix(fs.fchmodSync) +fs.lchmodSync = chownFix(fs.lchmodSync) + +function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er, res) { + if (chownErOk(er)) er = null + cb(er, res) + }) + } +} + +function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } +} + +// ENOSYS means that the fs doesn't support the op. Just ignore +// that, because it doesn't matter. +// +// if there's no getuid, or if getuid() is something other +// than 0, and the error is EINVAL or EPERM, then just ignore +// it. +// +// This specific case is a silent failure in cp, install, tar, +// and most other unix tools that manage permissions. +// +// When running as root, or if other types of errors are +// encountered, then it's strict. +function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false +} + + +// if lchmod/lchown do not exist, then make them no-ops +if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + process.nextTick(cb) + } + fs.lchmodSync = function () {} +} +if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + process.nextTick(cb) + } + fs.lchownSync = function () {} +} + + + +// on Windows, A/V software can lock the directory, causing this +// to fail with an EACCES or EPERM if the directory contains newly +// created files. Try again on failure, for up to 1 second. +if (process.platform === "win32") { + var rename_ = fs.rename + fs.rename = function rename (from, to, cb) { + var start = Date.now() + rename_(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 1000) { + return rename_(from, to, CB) + } + if(cb) cb(er) + }) + } +} + + +// if read() returns EAGAIN, then just try it again. +var read = fs.read +fs.read = function (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return read.call(fs, fd, buffer, offset, length, position, callback) +} + +var readSync = fs.readSync +fs.readSync = function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } +} + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/max-open.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/max-open.js new file mode 100644 index 0000000..a6b9ba4 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/max-open.js @@ -0,0 +1,69 @@ +var test = require('tap').test +var fs = require('../') + +test('open lots of stuff', function (t) { + // Get around EBADF from libuv by making sure that stderr is opened + // Otherwise Darwin will refuse to give us a FD for stderr! + process.stderr.write('') + + // How many parallel open()'s to do + var n = 1024 + var opens = 0 + var fds = [] + var going = true + var closing = false + var doneCalled = 0 + + for (var i = 0; i < n; i++) { + go() + } + + function go() { + opens++ + fs.open(__filename, 'r', function (er, fd) { + if (er) throw er + fds.push(fd) + if (going) go() + }) + } + + // should hit ulimit pretty fast + setTimeout(function () { + going = false + t.equal(opens - fds.length, n) + done() + }, 100) + + + function done () { + if (closing) return + doneCalled++ + + if (fds.length === 0) { + console.error('done called %d times', doneCalled) + // First because of the timeout + // Then to close the fd's opened afterwards + // Then this time, to complete. + // Might take multiple passes, depending on CPU speed + // and ulimit, but at least 3 in every case. + t.ok(doneCalled >= 2) + return t.end() + } + + closing = true + setTimeout(function () { + // console.error('do closing again') + closing = false + done() + }, 100) + + // console.error('closing time') + var closes = fds.slice(0) + fds.length = 0 + closes.forEach(function (fd) { + fs.close(fd, function (er) { + if (er) throw er + }) + }) + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/open.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/open.js new file mode 100644 index 0000000..85732f2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/open.js @@ -0,0 +1,39 @@ +var test = require('tap').test +var fs = require('../graceful-fs.js') + +test('graceful fs is monkeypatched fs', function (t) { + t.equal(fs, require('../fs.js')) + t.end() +}) + +test('open an existing file works', function (t) { + var fd = fs.openSync(__filename, 'r') + fs.closeSync(fd) + fs.open(__filename, 'r', function (er, fd) { + if (er) throw er + fs.close(fd, function (er) { + if (er) throw er + t.pass('works') + t.end() + }) + }) +}) + +test('open a non-existing file throws', function (t) { + var er + try { + var fd = fs.openSync('this file does not exist', 'r') + } catch (x) { + er = x + } + t.ok(er, 'should throw') + t.notOk(fd, 'should not get an fd') + t.equal(er.code, 'ENOENT') + + fs.open('neither does this file', 'r', function (er, fd) { + t.ok(er, 'should throw') + t.notOk(fd, 'should not get an fd') + t.equal(er.code, 'ENOENT') + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js new file mode 100644 index 0000000..cb63a68 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/readdir-sort.js @@ -0,0 +1,20 @@ +var test = require("tap").test +var fs = require("../fs.js") + +var readdir = fs.readdir +fs.readdir = function(path, cb) { + process.nextTick(function() { + cb(null, ["b", "z", "a"]) + }) +} + +var g = require("../") + +test("readdir reorder", function (t) { + g.readdir("whatevers", function (er, files) { + if (er) + throw er + t.same(files, [ "a", "b", "z" ]) + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js new file mode 100644 index 0000000..21e4c26 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/node_modules/graceful-fs/test/write-then-read.js @@ -0,0 +1,47 @@ +var fs = require('../'); +var rimraf = require('rimraf'); +var mkdirp = require('mkdirp'); +var test = require('tap').test; +var p = require('path').resolve(__dirname, 'files'); + +process.chdir(__dirname) + +// Make sure to reserve the stderr fd +process.stderr.write(''); + +var num = 4097; +var paths = new Array(num); + +test('make files', function (t) { + rimraf.sync(p); + mkdirp.sync(p); + + for (var i = 0; i < num; ++i) { + paths[i] = 'files/file-' + i; + fs.writeFileSync(paths[i], 'content'); + } + + t.end(); +}) + +test('read files', function (t) { + // now read them + var done = 0; + for (var i = 0; i < num; ++i) { + fs.readFile(paths[i], function(err, data) { + if (err) + throw err; + + ++done; + if (done === num) { + t.pass('success'); + t.end() + } + }); + } +}); + +test('cleanup', function (t) { + rimraf.sync(p); + t.end(); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/package.json new file mode 100644 index 0000000..8daf559 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/fstream/package.json @@ -0,0 +1,42 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "fstream", + "description": "Advanced file system stream things", + "version": "1.0.6", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/fstream.git" + }, + "main": "fstream.js", + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "graceful-fs": "3", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "devDependencies": { + "tap": "0", + "standard": "^2.3.2" + }, + "scripts": { + "test": "standard && tap examples/*.js" + }, + "license": "ISC", + "readme": "Like FS streams, but with stat on them, and supporting directories and\nsymbolic links, as well as normal files. Also, you can use this to set\nthe stats on a file, even if you don't change its contents, or to create\na symlink, etc.\n\nSo, for example, you can \"write\" a directory, and it'll call `mkdir`. You\ncan specify a uid and gid, and it'll call `chown`. You can specify a\n`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink\nand provide a `linkpath` and it'll call `symlink`.\n\nNote that it won't automatically resolve symbolic links. So, if you\ncall `fstream.Reader('/some/symlink')` then you'll get an object\nthat stats and then ends immediately (since it has no data). To follow\nsymbolic links, do this: `fstream.Reader({path:'/some/symlink', follow:\ntrue })`.\n\nThere are various checks to make sure that the bytes emitted are the\nsame as the intended size, if the size is set.\n\n## Examples\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n })\n .write(\"hello\\n\")\n .end()\n```\n\nThis will create the directories if they're missing, and then write\n`hello\\n` into the file, chmod it to 0755, and assert that 6 bytes have\nbeen written when it's done.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n , flags: \"a\"\n })\n .write(\"hello\\n\")\n .end()\n```\n\nYou can pass flags in, if you want to append to a file.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/symlink\"\n , linkpath: \"./file\"\n , SymbolicLink: true\n , mode: \"0755\" // octal strings supported\n })\n .end()\n```\n\nIf isSymbolicLink is a function, it'll be called, and if it returns\ntrue, then it'll treat it as a symlink. If it's not a function, then\nany truish value will make a symlink, or you can set `type:\n'SymbolicLink'`, which does the same thing.\n\nNote that the linkpath is relative to the symbolic link location, not\nthe parent dir or cwd.\n\n```javascript\nfstream\n .Reader(\"path/to/dir\")\n .pipe(fstream.Writer(\"path/to/other/dir\"))\n```\n\nThis will do like `cp -Rp path/to/dir path/to/other/dir`. If the other\ndir exists and isn't a directory, then it'll emit an error. It'll also\nset the uid, gid, mode, etc. to be identical. In this way, it's more\nlike `rsync -a` than simply a copy.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/fstream/issues" + }, + "homepage": "https://github.com/isaacs/fstream#readme", + "_id": "fstream@1.0.6", + "_shasum": "817e50312fb4ed90da865c8eb5ecd1d1d7aed0ec", + "_resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.6.tgz", + "_from": "fstream@>=1.0.2 <2.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/package.json new file mode 100644 index 0000000..8c08a43 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.0 <3.0.0" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/package.json new file mode 100644 index 0000000..72a0e07 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/package.json @@ -0,0 +1,61 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "tar", + "description": "tar for node", + "version": "2.1.1", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-tar.git" + }, + "main": "tar.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "block-stream": "*", + "fstream": "^1.0.2", + "inherits": "2" + }, + "devDependencies": { + "graceful-fs": "^3.0.2", + "rimraf": "1.x", + "tap": "0.x", + "mkdirp": "^0.5.0" + }, + "license": "ISC", + "gitHead": "2cbe6c805fc5d87ce099183ed13c43faba962224", + "bugs": { + "url": "https://github.com/isaacs/node-tar/issues" + }, + "homepage": "https://github.com/isaacs/node-tar#readme", + "_id": "tar@2.1.1", + "_shasum": "ac0649e135fa4546e430c7698514e1da2e8a7cc4", + "_from": "tar@>=2.1.0 <2.2.0", + "_npmVersion": "2.9.1", + "_nodeVersion": "1.8.1", + "_npmUser": { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + }, + "dist": { + "shasum": "ac0649e135fa4546e430c7698514e1da2e8a7cc4", + "tarball": "http://registry.npmjs.org/tar/-/tar-2.1.1.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + }, + { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/tar/-/tar-2.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/tar.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/tar.js new file mode 100644 index 0000000..a81298b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/tar.js @@ -0,0 +1,173 @@ +// field paths that every tar file must have. +// header is padded to 512 bytes. +var f = 0 + , fields = {} + , path = fields.path = f++ + , mode = fields.mode = f++ + , uid = fields.uid = f++ + , gid = fields.gid = f++ + , size = fields.size = f++ + , mtime = fields.mtime = f++ + , cksum = fields.cksum = f++ + , type = fields.type = f++ + , linkpath = fields.linkpath = f++ + , headerSize = 512 + , blockSize = 512 + , fieldSize = [] + +fieldSize[path] = 100 +fieldSize[mode] = 8 +fieldSize[uid] = 8 +fieldSize[gid] = 8 +fieldSize[size] = 12 +fieldSize[mtime] = 12 +fieldSize[cksum] = 8 +fieldSize[type] = 1 +fieldSize[linkpath] = 100 + +// "ustar\0" may introduce another bunch of headers. +// these are optional, and will be nulled out if not present. + +var ustar = fields.ustar = f++ + , ustarver = fields.ustarver = f++ + , uname = fields.uname = f++ + , gname = fields.gname = f++ + , devmaj = fields.devmaj = f++ + , devmin = fields.devmin = f++ + , prefix = fields.prefix = f++ + , fill = fields.fill = f++ + +// terminate fields. +fields[f] = null + +fieldSize[ustar] = 6 +fieldSize[ustarver] = 2 +fieldSize[uname] = 32 +fieldSize[gname] = 32 +fieldSize[devmaj] = 8 +fieldSize[devmin] = 8 +fieldSize[prefix] = 155 +fieldSize[fill] = 12 + +// nb: prefix field may in fact be 130 bytes of prefix, +// a null char, 12 bytes for atime, 12 bytes for ctime. +// +// To recognize this format: +// 1. prefix[130] === ' ' or '\0' +// 2. atime and ctime are octal numeric values +// 3. atime and ctime have ' ' in their last byte + +var fieldEnds = {} + , fieldOffs = {} + , fe = 0 +for (var i = 0; i < f; i ++) { + fieldOffs[i] = fe + fieldEnds[i] = (fe += fieldSize[i]) +} + +// build a translation table of field paths. +Object.keys(fields).forEach(function (f) { + if (fields[f] !== null) fields[fields[f]] = f +}) + +// different values of the 'type' field +// paths match the values of Stats.isX() functions, where appropriate +var types = + { 0: "File" + , "\0": "OldFile" // like 0 + , "": "OldFile" + , 1: "Link" + , 2: "SymbolicLink" + , 3: "CharacterDevice" + , 4: "BlockDevice" + , 5: "Directory" + , 6: "FIFO" + , 7: "ContiguousFile" // like 0 + // posix headers + , g: "GlobalExtendedHeader" // k=v for the rest of the archive + , x: "ExtendedHeader" // k=v for the next file + // vendor-specific stuff + , A: "SolarisACL" // skip + , D: "GNUDumpDir" // like 5, but with data, which should be skipped + , I: "Inode" // metadata only, skip + , K: "NextFileHasLongLinkpath" // data = link path of next file + , L: "NextFileHasLongPath" // data = path of next file + , M: "ContinuationFile" // skip + , N: "OldGnuLongPath" // like L + , S: "SparseFile" // skip + , V: "TapeVolumeHeader" // skip + , X: "OldExtendedHeader" // like x + } + +Object.keys(types).forEach(function (t) { + types[types[t]] = types[types[t]] || t +}) + +// values for the mode field +var modes = + { suid: 04000 // set uid on extraction + , sgid: 02000 // set gid on extraction + , svtx: 01000 // set restricted deletion flag on dirs on extraction + , uread: 0400 + , uwrite: 0200 + , uexec: 0100 + , gread: 040 + , gwrite: 020 + , gexec: 010 + , oread: 4 + , owrite: 2 + , oexec: 1 + , all: 07777 + } + +var numeric = + { mode: true + , uid: true + , gid: true + , size: true + , mtime: true + , devmaj: true + , devmin: true + , cksum: true + , atime: true + , ctime: true + , dev: true + , ino: true + , nlink: true + } + +Object.keys(modes).forEach(function (t) { + modes[modes[t]] = modes[modes[t]] || t +}) + +var knownExtended = + { atime: true + , charset: true + , comment: true + , ctime: true + , gid: true + , gname: true + , linkpath: true + , mtime: true + , path: true + , realtime: true + , security: true + , size: true + , uid: true + , uname: true } + + +exports.fields = fields +exports.fieldSize = fieldSize +exports.fieldOffs = fieldOffs +exports.fieldEnds = fieldEnds +exports.types = types +exports.modes = modes +exports.numeric = numeric +exports.headerSize = headerSize +exports.blockSize = blockSize +exports.knownExtended = knownExtended + +exports.Pack = require("./lib/pack.js") +exports.Parse = require("./lib/parse.js") +exports.Extract = require("./lib/extract.js") diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/00-setup-fixtures.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/00-setup-fixtures.js new file mode 100644 index 0000000..1524ff7 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/00-setup-fixtures.js @@ -0,0 +1,53 @@ +// the fixtures have some weird stuff that is painful +// to include directly in the repo for various reasons. +// +// So, unpack the fixtures with the system tar first. +// +// This means, of course, that it'll only work if you +// already have a tar implementation, and some of them +// will not properly unpack the fixtures anyway. +// +// But, since usually those tests will fail on Windows +// and other systems with less capable filesystems anyway, +// at least this way we don't cause inconveniences by +// merely cloning the repo or installing the package. + +var tap = require("tap") +, child_process = require("child_process") +, rimraf = require("rimraf") +, test = tap.test +, path = require("path") + +test("clean fixtures", function (t) { + rimraf(path.resolve(__dirname, "fixtures"), function (er) { + t.ifError(er, "rimraf ./fixtures/") + t.end() + }) +}) + +test("clean tmp", function (t) { + rimraf(path.resolve(__dirname, "tmp"), function (er) { + t.ifError(er, "rimraf ./tmp/") + t.end() + }) +}) + +test("extract fixtures", function (t) { + var c = child_process.spawn("tar" + ,["xzvf", "fixtures.tgz"] + ,{ cwd: __dirname }) + + c.stdout.on("data", errwrite) + c.stderr.on("data", errwrite) + function errwrite (chunk) { + process.stderr.write(chunk) + } + + c.on("exit", function (code) { + t.equal(code, 0, "extract fixtures should exit with 0") + if (code) { + t.comment("Note, all tests from here on out will fail because of this.") + } + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/cb-never-called-1.0.1.tgz b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/cb-never-called-1.0.1.tgz new file mode 100644 index 0000000000000000000000000000000000000000..9e7014d85abe48a54cb6b4e1ec032df9a2073034 GIT binary patch literal 4096 zcmV+b5dZHViwFP!000001MOI6Sd-h91_Y5NO{$a-kt&eT2}P;Wl@<^X2_bX>Bta4B zh*T+|m(YrHJ$@AVon$2K1bnGjnI=&)j>@+~+y(pY`qa?su)7oxJON zp18u`jxbwz}afxwcd{NMW^{~g@X7#QmGDF4?wzdj4#-{Zds9+3k8KqSl=0fYd6a4R7s;ywZ; z1cx~}A*_Md&dAd>+TI0u#)E}H!r)(7YXlmOvUkP&#{5b;!|Z>q?2*<8kJF#huk5dl z=u_gX*=YiUKx59fA>ei{0CS)!3gv==0FW+#GXj8iMZoQC>=D-HKmZR90O4Ve0f2$0 zO7EZ5VD1<@7u0|Bbh3vdkm#Ss*Dz29l6#Z?*;o26h2MNHa(4Bn-`GE-$C>{nCI3hN zONfJh_rHXsn55{b|3y!q{__7n1NUJl!08151prE$InmxD|dP>VO0+d3I@mgOu8WXfCwZ8^$>UsU~^jIY!>k$ z_#csz!CjDO7bk?UlZ!1MP*vAZ{|*Fr4I%6b!`Pkn@cvzUHh2D$7WFsc(>Pp<* zcMDHUmM`*lommz%IhEqIpfC(=?vs+JU}a`0(8(cZ#l?4UNw^kaK7i7>l&;d3kbSUc z5W{Go@P?7%HAZH~5~c3xN(v5b(G($OtjFj=^vA~TMW6C0!h!JPICEtnsZ6Wk>+-4?xyI*FY5P*X7b18* zQ#;)wb!KCta{=d#O`e1}nLA{Bz1-#8=O3ZjB$@bOMLE^qS1N+M{DYsVde<-Ax~PI-9sxr3cjUIH?G_6g(t%feuXw9=AAUxMz3LTVO`c!x z-iK8l+1Ea?1$Wfgc+0XLF6wk8{@~z1deC>fmDu@4>z_50m}cVFp60T@BtE9^ zfLC2p<{wc@E=|>fqTKrK&iDqRt|E7RVi|W1sI{d;%2R@=n@UQyDr(1$H)e+0S28sF zj3@-0|uGPWd$n3h~PH2NKF@Iz64wvvwt7qD#B9 zL;y087W(|OBp+r4J||c&>IA&o@^tRJl~|CyVsKA6E%55ZgHHv?)N=PqL;~#3HxH7N z%g0mSV%s4Rmtr`E(U{7xO&xq(Ki_KQaemjmzNp6jP5PBrV;c4*lr37?eL+8hTy3pF zgu}X^WYUcErNvyjGsvM)^^nd>wt|^~DZR-vJI3yUsOD6SDcBN#4lfTN{Albmt-Ep; zu2L>OHxl^DXwhbweyPlTTQ#7NW*XJyvcw#f(NNWay0oB`JTEvD)n408ADCBm7->Ed z$BtC$t>ta+@!)TnVO1-p}HQbjOFzFcaR@JepTP4?y_@6wC8ULj@kUBM2wb^(mdCpGI^ zyYScO5bw6=gbT{^Q}bp}yLDM#(1idUtkhn^r`{mLXadG7C*Zs%tZnna^>8Bd>%2%L zrE5#_Bl1ERR|q~N*XuYAKGuIImui6<0I@k?@!(s`*e6Td+@VJGx1cW6hb0FMdux5S zwCmD2FHDjj-kr&jZr#`HY)x4koye0E{dQd|7u)73CLqK#$Q`vCP-)ioKt>~lzg6$) zqrR{PkJ6{v<-_iEJnCW|DJHNwh>Otz(~WxvejNmw`{R7y2OxTG&cK~ZR%##>T4usq zZo;Ls+mrkFrF_|pxCJwJBJ4#-yzmauIvYgatKC$$f1Eo=)h?(rHgsx^lgEvId)bV9 z32wVg|Bi5`+``1ow}-l~E-MWvRqP-P!IJS%3XO^nJ;smQWi$8Zy|YUtq|i6Wd=F(h zZ!*C;faYZA?@;uyJHgt)uyg58OTIEMw5*V=#dlA1TgwqITi#xvFbD+`UYW#g>EPVn zMbjp1`bqoqaGi7?yw&!Vmyn8-8SkapO%pZ9CxxGgEo;=gBPl*cgmZDVBt8Eoam{-y z)oskabX+^4=US=$3zTy=MKkC~dIZ0H2@(`s7)X6*8g@@u(<1#zyl5<&)9vUQ7UMUf zbLK@OjL>H5>5}#t1egUoD+)`Q@8G4e6O*WD7I0> z+U0SSp%YPwkxaVG5zLYHeALwZW^7>Z!sz&de!0I?oJ+4&3T>lyNT6Joi}(f^^-G#> zKna44%!2d#9U=-fu5?8gt_s;TOgk|~e=M z(haQdGr5=iTH8)nZXH;?u09#Rz+BrXZCbX1J_FzZ&qAQk9c)lKpP_OPIw=^k(M^Gp*dN^34MCzJl$h3Ui?QeGHsaDBf>&F zqwOuqj`uz9``CKo1H*CUef*-$lqTa6g}S-qAwocs+buTNG{q4LW!zdhZgnFu=iW@$#^D zf0!8E&1jN3HHCmZht^t6Q-p~0<_c{(bLj{Xt5i1hdRGraD|^yyDcY4!d-o$4l02VE z&+arc1Yff^@DZkNrO)5*jC&(eiO!G7h}0e!#Om+Qbf#XE?uQKfdXXd!NvX90NzW5; zt0SHXPbjk2s*xuh7Gn=nL@SaPm8ttxo;2z(tVa^e5jIi1!uc^cy}rw0Q*RMCuh3JnYF?qDv`?-IL0QE&DEbmYE~jLk>}h4zB57 z;6oAJH5tLx?sA+!XARU`KFDFukndYzpGW#J_Qi*UiSH8(tD0#Wrs>09LpoR{^L1ID zMPm&z6|Y@Q^-Z9FJZwD-W&e_C!5(&}l!&3t3|pI<_Bmbdt145s!Jsv>o(=t0QI7v+ zGnB)5``uQH%0Vr)a+OoQUfv?pORr*xjAvv5OmwCT+}s%9aG%X%s?T~S!@M{xw@kVb zZgt7*U1xOCXa6LlnDf@|LOEtnY zzEqI5I?^(M0wbC{FSeDM2-nc-o1E;!9@>}mJ~k4_5%AW2OFy2J5?aC!ba|GrUzh(P zH;-Q}UT$e?iP2ahx_SRHUmJWzK~H0=sYo(Sv;CoFNKS0`?pnw}6L2@0kuoY~0C3b+ z_k!U@)uxiwmc=_>0=RarSRrwE57V$m7v)j9VoIa}Zbcd7XOT_%a<|WLoHcHNG0?yM z0&xIkXbv*X;f<&-J~D0ktzl=)Yh^sN#>=}bAWq2yb+@UUp2fJT!Ms(AOcv7K{%ni+$8 zz$=z&nRh69i)q$1V{6|q#WA)wJ;}m$P;M~_q`Ws!oTG@tIASTaFohN0jW(4Wys~dW zv&H&%2xFyaB|l$KkInQmtnQ4u`O#-zba;D>Vp=+{xYhDo1^<}hIhg?y&L$wKx5*C{ zr4WXy0_Fj9J&8~<%+@{Iv0Z*4CAy*GNz-&=oj>&+=tc898+nvWmPMdINsE-cTouy4 zrK^}eind7L7z`S$TTlVooa}3NM2i-<(%k1T#!a(%EAXdr^|qP}<;il0R}=Hj2KoC1 zh^$(!w~U(47zn-L%(^TYAW-!HoVUq_!kOEjr1Q#9Y^;WS*xbU2i}zF3R?hPoDqT2M z^F~d2X;*s_sL%kd;)BWDdAPRxOXp@M_rHu-J&Q;Rs+i|c66vVN-lcvKrVz805jc+O z!f2?HlA-C?r?f5BwAZHUjm4-Eld?r|f~HYf>-`IYq4Uo4oTMeT)ZwV8sl#gA_q{Tz znWptaRUdk8Q?>g;VAAoh4TtOif7Nyp4(E%<#;@gbrTlQR`GRJ!F2!+j$9a|u>aS%8 zkNlwTdaGySDF-|K<}yunncD&gsvRKudg_NN+cm@R>WQpYsvyRGeRvo}&)Y$ZS2TTV z!?DaM#u?#pYqR<(OWy0Pt-|^RR?9I;uO5NIZrtvT&4dsS%kPtw}<6))- yt=kRJt4#0W>hFnshu(4QecAmmIH4odAf{v@=5VI8kvw%kgq3P?0(H++;E@y9-yRnL literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.js new file mode 100644 index 0000000..9719c42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.js @@ -0,0 +1,177 @@ +// Set the umask, so that it works the same everywhere. +process.umask(parseInt('22', 8)) + +var fs = require('fs') +var path = require('path') + +var fstream = require('fstream') +var test = require('tap').test + +var tar = require('../tar.js') +var file = path.resolve(__dirname, 'dir-normalization.tar') +var target = path.resolve(__dirname, 'tmp/dir-normalization-test') +var ee = 0 + +var expectEntries = [ + { path: 'fixtures/', + mode: '755', + type: '5', + linkpath: '' + }, + { path: 'fixtures/a/', + mode: '755', + type: '5', + linkpath: '' + }, + { path: 'fixtures/the-chumbler', + mode: '755', + type: '2', + linkpath: path.resolve(target, 'a/b/c/d/the-chumbler'), + }, + { path: 'fixtures/a/b/', + mode: '755', + type: '5', + linkpath: '' + }, + { path: 'fixtures/a/x', + mode: '644', + type: '0', + linkpath: '' + }, + { path: 'fixtures/a/b/c/', + mode: '755', + type: '5', + linkpath: '' + }, + { path: 'fixtures/a/b/c/y', + mode: '755', + type: '2', + linkpath: '../../x', + } +] + +var ef = 0 +var expectFiles = [ + { path: '', + mode: '40755', + type: 'Directory', + depth: 0, + linkpath: undefined + }, + { path: '/fixtures', + mode: '40755', + type: 'Directory', + depth: 1, + linkpath: undefined + }, + { path: '/fixtures/a', + mode: '40755', + type: 'Directory', + depth: 2, + linkpath: undefined + }, + { path: '/fixtures/a/b', + mode: '40755', + type: 'Directory', + depth: 3, + linkpath: undefined + }, + { path: '/fixtures/a/b/c', + mode: '40755', + type: 'Directory', + depth: 4, + linkpath: undefined + }, + { path: '/fixtures/a/b/c/y', + mode: '120755', + type: 'SymbolicLink', + depth: 5, + linkpath: '../../x' + }, + { path: '/fixtures/a/x', + mode: '100644', + type: 'File', + depth: 3, + linkpath: undefined + }, + { path: '/fixtures/the-chumbler', + mode: '120755', + type: 'SymbolicLink', + depth: 2, + linkpath: path.resolve(target, 'a/b/c/d/the-chumbler') + } +] + +test('preclean', function (t) { + require('rimraf').sync(path.join(__dirname, '/tmp/dir-normalization-test')) + t.pass('cleaned!') + t.end() +}) + +test('extract test', function (t) { + var extract = tar.Extract(target) + var inp = fs.createReadStream(file) + + inp.pipe(extract) + + extract.on('end', function () { + t.equal(ee, expectEntries.length, 'should see ' + expectEntries.length + ' entries') + + // should get no more entries after end + extract.removeAllListeners('entry') + extract.on('entry', function (e) { + t.fail('Should not get entries after end!') + }) + + next() + }) + + extract.on('entry', function (entry) { + var mode = entry.props.mode & (~parseInt('22', 8)) + var found = { + path: entry.path, + mode: mode.toString(8), + type: entry.props.type, + linkpath: entry.props.linkpath, + } + + var wanted = expectEntries[ee++] + t.equivalent(found, wanted, 'tar entry ' + ee + ' ' + (wanted && wanted.path)) + }) + + function next () { + var r = fstream.Reader({ + path: target, + type: 'Directory', + sort: 'alpha' + }) + + r.on('ready', function () { + foundEntry(r) + }) + + r.on('end', finish) + + function foundEntry (entry) { + var p = entry.path.substr(target.length) + var mode = entry.props.mode & (~parseInt('22', 8)) + var found = { + path: p, + mode: mode.toString(8), + type: entry.props.type, + depth: entry.props.depth, + linkpath: entry.props.linkpath + } + + var wanted = expectFiles[ef++] + t.equivalent(found, wanted, 'unpacked file ' + ef + ' ' + (wanted && wanted.path)) + + entry.on('entry', foundEntry) + } + + function finish () { + t.equal(ef, expectFiles.length, 'should have ' + ef + ' items') + t.end() + } + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.tar b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/dir-normalization.tar new file mode 100644 index 0000000000000000000000000000000000000000..3c4845356cecb20939b415830a5fa9717fb91341 GIT binary patch literal 4608 zcmeHJS&qUm4DC^J0f_Cy&3Qtn6-dKR7m2w&PN6j7t4Me>Xkt~0n?~MVp55+r8K=G- zY^5gv5SUE`972tqikXFmnFvea&It?*4!@B>h$+50` z-pt$IGqpQZU1J+8}SF0 zCIB7{5IUmDkd5|W8~bGygDd>M_5W1rH{-sT+lc?%|G~}t525gXDWB^4;D59iEk}ZX z?bE#9F#qrUKRCf3v;xZQ7XGjNZ*)4qOZ=A~MLp$ne2HwSHsX(c~XH?({YrM8z literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/error-on-broken.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/error-on-broken.js new file mode 100644 index 0000000..e484920 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/error-on-broken.js @@ -0,0 +1,33 @@ +var fs = require('fs') +var path = require('path') +var zlib = require('zlib') + +var tap = require('tap') + +var tar = require('../tar.js') + +var file = path.join(__dirname, 'cb-never-called-1.0.1.tgz') +var target = path.join(__dirname, 'tmp/extract-test') + +tap.test('preclean', function (t) { + require('rimraf').sync(__dirname + '/tmp/extract-test') + t.pass('cleaned!') + t.end() +}) + +tap.test('extract test', function (t) { + var extract = tar.Extract(target) + var inp = fs.createReadStream(file) + + inp.pipe(zlib.createGunzip()).pipe(extract) + + extract.on('error', function (er) { + t.equal(er.message, 'unexpected eof', 'error noticed') + t.end() + }) + + extract.on('end', function () { + t.fail('shouldn\'t reach this point due to errors') + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract-move.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract-move.js new file mode 100644 index 0000000..45400cd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract-move.js @@ -0,0 +1,132 @@ +// Set the umask, so that it works the same everywhere. +process.umask(parseInt('22', 8)) + +var tap = require("tap") + , tar = require("../tar.js") + , fs = require("fs") + , gfs = require("graceful-fs") + , path = require("path") + , file = path.resolve(__dirname, "fixtures/dir.tar") + , target = path.resolve(__dirname, "tmp/extract-test") + , index = 0 + , fstream = require("fstream") + , rimraf = require("rimraf") + , mkdirp = require("mkdirp") + + , ee = 0 + , expectEntries = [ + { + "path" : "dir/", + "mode" : "750", + "type" : "5", + "depth" : undefined, + "size" : 0, + "linkpath" : "", + "nlink" : undefined, + "dev" : undefined, + "ino" : undefined + }, + { + "path" : "dir/sub/", + "mode" : "750", + "type" : "5", + "depth" : undefined, + "size" : 0, + "linkpath" : "", + "nlink" : undefined, + "dev" : undefined, + "ino" : undefined + } ] + +function slow (fs, method, t1, t2) { + var orig = fs[method] + if (!orig) return null + fs[method] = function () { + var args = [].slice.call(arguments) + console.error("slow", method, args[0]) + var cb = args.pop() + + setTimeout(function () { + orig.apply(fs, args.concat(function(er, data) { + setTimeout(function() { + cb(er, data) + }, t2) + })) + }, t1) + } +} + +// Make sure we get the graceful-fs that fstream is using. +var gfs2 +try { + gfs2 = require("fstream/node_modules/graceful-fs") +} catch (er) {} + +var slowMethods = ["chown", "chmod", "utimes", "lutimes"] +slowMethods.forEach(function (method) { + var t1 = 500 + var t2 = 0 + slow(fs, method, t1, t2) + slow(gfs, method, t1, t2) + if (gfs2) { + slow(gfs2, method, t1, t2) + } +}) + + + +// The extract class basically just pipes the input +// to a Reader, and then to a fstream.DirWriter + +// So, this is as much a test of fstream.Reader and fstream.Writer +// as it is of tar.Extract, but it sort of makes sense. + +tap.test("preclean", function (t) { + rimraf.sync(target) + /mkdirp.sync(target) + t.pass("cleaned!") + t.end() +}) + +tap.test("extract test", function (t) { + var extract = tar.Extract(target) + var inp = fs.createReadStream(file) + + // give it a weird buffer size to try to break in odd places + inp.bufferSize = 1234 + + inp.pipe(extract) + + extract.on("end", function () { + rimraf.sync(target) + + t.equal(ee, expectEntries.length, "should see "+ee+" entries") + + // should get no more entries after end + extract.removeAllListeners("entry") + extract.on("entry", function (e) { + t.fail("Should not get entries after end!") + }) + + t.end() + }) + + + extract.on("entry", function (entry) { + var found = + { path: entry.path + , mode: entry.props.mode.toString(8) + , type: entry.props.type + , depth: entry.props.depth + , size: entry.props.size + , linkpath: entry.props.linkpath + , nlink: entry.props.nlink + , dev: entry.props.dev + , ino: entry.props.ino + } + + var wanted = expectEntries[ee ++] + + t.equivalent(found, wanted, "tar entry " + ee + " " + wanted.path) + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract.js new file mode 100644 index 0000000..eca4e7c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/extract.js @@ -0,0 +1,367 @@ +// Set the umask, so that it works the same everywhere. +process.umask(parseInt('22', 8)) + +var tap = require("tap") + , tar = require("../tar.js") + , fs = require("fs") + , path = require("path") + , file = path.resolve(__dirname, "fixtures/c.tar") + , target = path.resolve(__dirname, "tmp/extract-test") + , index = 0 + , fstream = require("fstream") + + , ee = 0 + , expectEntries = +[ { path: 'c.txt', + mode: '644', + type: '0', + depth: undefined, + size: 513, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'cc.txt', + mode: '644', + type: '0', + depth: undefined, + size: 513, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '0', + depth: undefined, + size: 100, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'Ω.txt', + mode: '644', + type: '0', + depth: undefined, + size: 2, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: 'Ω.txt', + mode: '644', + type: '0', + depth: undefined, + size: 2, + linkpath: '', + nlink: 1, + dev: 234881026, + ino: 51693379 }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '0', + depth: undefined, + size: 200, + linkpath: '', + nlink: 1, + dev: 234881026, + ino: 51681874 }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '0', + depth: undefined, + size: 201, + linkpath: '', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', + mode: '777', + type: '2', + depth: undefined, + size: 0, + linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + nlink: undefined, + dev: undefined, + ino: undefined }, + { path: '200-hard', + mode: '644', + type: '0', + depth: undefined, + size: 200, + linkpath: '', + nlink: 2, + dev: 234881026, + ino: 51681874 }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '644', + type: '1', + depth: undefined, + size: 0, + linkpath: path.resolve(target, '200-hard'), + nlink: 2, + dev: 234881026, + ino: 51681874 } ] + + , ef = 0 + , expectFiles = +[ { path: '', + mode: '40755', + type: 'Directory', + depth: 0, + linkpath: undefined }, + { path: '/200-hard', + mode: '100644', + type: 'File', + depth: 1, + size: 200, + linkpath: undefined, + nlink: 2 }, + { path: '/200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', + mode: '120777', + type: 'SymbolicLink', + depth: 1, + size: 200, + linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + nlink: 1 }, + { path: '/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '100644', + type: 'Link', + depth: 1, + size: 200, + linkpath: path.join(target, '200-hard'), + nlink: 2 }, + { path: '/c.txt', + mode: '100644', + type: 'File', + depth: 1, + size: 513, + linkpath: undefined, + nlink: 1 }, + { path: '/cc.txt', + mode: '100644', + type: 'File', + depth: 1, + size: 513, + linkpath: undefined, + nlink: 1 }, + { path: '/r', + mode: '40755', + type: 'Directory', + depth: 1, + linkpath: undefined }, + { path: '/r/e', + mode: '40755', + type: 'Directory', + depth: 2, + linkpath: undefined }, + { path: '/r/e/a', + mode: '40755', + type: 'Directory', + depth: 3, + linkpath: undefined }, + { path: '/r/e/a/l', + mode: '40755', + type: 'Directory', + depth: 4, + linkpath: undefined }, + { path: '/r/e/a/l/l', + mode: '40755', + type: 'Directory', + depth: 5, + linkpath: undefined }, + { path: '/r/e/a/l/l/y', + mode: '40755', + type: 'Directory', + depth: 6, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-', + mode: '40755', + type: 'Directory', + depth: 7, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d', + mode: '40755', + type: 'Directory', + depth: 8, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e', + mode: '40755', + type: 'Directory', + depth: 9, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e', + mode: '40755', + type: 'Directory', + depth: 10, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p', + mode: '40755', + type: 'Directory', + depth: 11, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-', + mode: '40755', + type: 'Directory', + depth: 12, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f', + mode: '40755', + type: 'Directory', + depth: 13, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o', + mode: '40755', + type: 'Directory', + depth: 14, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l', + mode: '40755', + type: 'Directory', + depth: 15, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d', + mode: '40755', + type: 'Directory', + depth: 16, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e', + mode: '40755', + type: 'Directory', + depth: 17, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r', + mode: '40755', + type: 'Directory', + depth: 18, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-', + mode: '40755', + type: 'Directory', + depth: 19, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p', + mode: '40755', + type: 'Directory', + depth: 20, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a', + mode: '40755', + type: 'Directory', + depth: 21, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t', + mode: '40755', + type: 'Directory', + depth: 22, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h', + mode: '40755', + type: 'Directory', + depth: 23, + linkpath: undefined }, + { path: '/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: '100644', + type: 'File', + depth: 24, + size: 100, + linkpath: undefined, + nlink: 1 }, + { path: '/Ω.txt', + mode: '100644', + type: 'File', + depth: 1, + size: 2, + linkpath: undefined, + nlink: 1 } ] + + + +// The extract class basically just pipes the input +// to a Reader, and then to a fstream.DirWriter + +// So, this is as much a test of fstream.Reader and fstream.Writer +// as it is of tar.Extract, but it sort of makes sense. + +tap.test("preclean", function (t) { + require("rimraf").sync(__dirname + "/tmp/extract-test") + t.pass("cleaned!") + t.end() +}) + +tap.test("extract test", function (t) { + var extract = tar.Extract(target) + var inp = fs.createReadStream(file) + + // give it a weird buffer size to try to break in odd places + inp.bufferSize = 1234 + + inp.pipe(extract) + + extract.on("end", function () { + t.equal(ee, expectEntries.length, "should see "+ee+" entries") + + // should get no more entries after end + extract.removeAllListeners("entry") + extract.on("entry", function (e) { + t.fail("Should not get entries after end!") + }) + + next() + }) + + extract.on("entry", function (entry) { + var found = + { path: entry.path + , mode: entry.props.mode.toString(8) + , type: entry.props.type + , depth: entry.props.depth + , size: entry.props.size + , linkpath: entry.props.linkpath + , nlink: entry.props.nlink + , dev: entry.props.dev + , ino: entry.props.ino + } + + var wanted = expectEntries[ee ++] + + t.equivalent(found, wanted, "tar entry " + ee + " " + wanted.path) + }) + + function next () { + var r = fstream.Reader({ path: target + , type: "Directory" + // this is just to encourage consistency + , sort: "alpha" }) + + r.on("ready", function () { + foundEntry(r) + }) + + r.on("end", finish) + + function foundEntry (entry) { + var p = entry.path.substr(target.length) + var found = + { path: p + , mode: entry.props.mode.toString(8) + , type: entry.props.type + , depth: entry.props.depth + , size: entry.props.size + , linkpath: entry.props.linkpath + , nlink: entry.props.nlink + } + + var wanted = expectFiles[ef ++] + + t.has(found, wanted, "unpacked file " + ef + " " + wanted.path) + + entry.on("entry", foundEntry) + } + + function finish () { + t.equal(ef, expectFiles.length, "should have "+ef+" items") + t.end() + } + } +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/fixtures.tgz b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/fixtures.tgz new file mode 100644 index 0000000000000000000000000000000000000000..f1676023afa2bba2aa18b5508c92f03e1d0816c6 GIT binary patch literal 19352 zcmdS9Wm8?>6E%oKa0>)?hoHgXLLj)iOK^9Wixb@4-2;JO!GpWILvVM$XZZb}7gIGe zUtnIH+O<#h+1^?)mpt7>+4-uRLlz3qxI~Dff#Gk#6 z`g-rTn_<`NkGgSqh`9%iyIO+RJMIEk@Q^cjEPzS$QFJLbkvahQFp1Gi?M1xtX z_d_3jPIjl>+%+o^H;key?OVfX3E8v2FgIk&q5@J)^5h?H8?w4%1l*k;@LW8A*KOPe z2m})_YIt^yV27?Sb9o}&8YLHw}wmBaI#s5;w$~1gL}Yl8$kSfR+T&Wf?T=;vdl4$nrcnE0Smw^kG$rI+igCu zLr{XYa&G{kKrnW&uV)Zm056SzBh^q4DFok3neK>2dnOF*v9)P(VIXSxruX3R_(6<} zOZDyM+Urp`x)%;WHfqw~UlV|((9x}_0fV6Gd7)s-8b8Iyj6dV=FE|k7SbKGn(HT^^ z)#XFd>jGa=?AGFLS4E*@QNW1Z$Q|ykv(g=BFX*Wsx?zg(0`LaBgj=IE_Wi($#wNW= zsOzqY_94)b9n`KM(7@!i*G@qTGS7a5nPO`&8Hxx?HJ_Gs!6KRIcU9CIXw9oVS zaHGn2ODfpk4(T4xmN)?#5wf70ksW$_I+pa)A=&N+ErhZ;zaOTE3v1zIS}$30$99_@ zb#iRJNa!r%r72#Uo2unZQ3}G@roGZvMz_6UPggT$oZ&9C#MNJTEnx0o>7^3(ga*-0 z&|(RQ5v%!l@f?}!_P4aUe|2XDn?Mi3*r3P46Qlh9V>}CRA zNt_D6UCg|6b#Tv={{aM$OtzmQ$i&Yf7iIx&i#I_l@h5^OhV5nYfI{AjKXEfz1ce5@z7!Ei78)mBhq_n%2+n=ux$t?fCf*hcr8^+}NV~}t0I|P;l~Dfy z!P1AX08Kyxu($y+Y>8+@)w&bh(9{}u_Nj(4Ujc>yYM_@la&?%B6_turyY$u2@C7Ki z>{{J++UgDrJ_)=BW)`g6JJY#8KLD>o53tw3D;snh2o7LH?m=^eY+@U^sAij6@eoCg zkH_?3)Vt4Z*h_A7gvEms*^r9@fY@H{SLyQhOQ~PLr_8c^m+W6 zlrdDj_DAr1kbw4f7X2lu)tdOTJ+eBX@l1;u?E88w$R9$A)^86lIoi1RR&Q1rArGd{eH6$HSpvF zphwMqYsS@TeAefy_J-C#%>?2!(}CsK(bvhQe_#uM6`q@?pN%Z91eOzx%h4)7d56K} z)Y>XP9eIg+MkFab6~VjxnM+BoY1%4Zx=r3HKSCDP%_@HsDh**J8G*6><~JvS-j5}W zzN>y}rrh9r%-$m-a*1~eCCjaY{4WI0Chrb*X9B!|^Ez45U3nMx9@%|hqVgKF`s-r!h3v08+ywa|;0oDPc?XrN()H-=WDK=y zYaai@>}TjqOax|hLM@tiXH#C5pD3I`W*?@g?R}KHX+&_+UXGkWX;7aZlAJxXSl*cx zS*GW$`UZnO^uK)BKz6l^dSx}sl1Qpa^#+1uSF~LmnY(|A(wN?|1xcWw5zz3P!XGbX!q*-V*b{#S=Ws@+bDjMqk5mR zjb|;MQs=`KY3kmnTUYzAgWsv)(G8PGVimd8_qS2d+csIGooYB7qs$E z8qKum8fe9z76`L9-#PvjK?QY-b|}l)`zd|C4?)Yy-$!6Y;d`A+A@xA{o}Vktxsgwy zoqqc4KkmMe6m5e2jhguA|+(eH*iS?hzyIMn+ z*2>F;9VRY<+KhECR6w;$kdWCzOCC^eK?4a7Uxwsj*i2qfYtIB9Ji+y%+tD{y;QP1e z`|!*1-wv?f5AXS?iz0#SV`herWGe_@YUeXDa_PUs2~Rq~;?TQPYo3Kf3i zz<-779Bf06Qb8L<@Y$qZ9>^Q%l>Ue4G>6=*i}+H@LkU9n%wtq2r4 z&#xwgbmf|^$iYsa7@p&r=mtL$WkG}?rn(krh*giCv#S|G{h4&`XCJoOfL<32oY8zO zQlQ29&yX7?JdBB2^7R5-gfm$|)W%Ck|I|qwjDe&U21RC{5t3J}t$P|NmVocL+8ZvX z@9;*5@cyf>rQ9^-5z1!?ZOk|`D=IEEySb!I_CoH@KUfDyXp$Gk+r;Rra`-! zj0UZ?_`V$-(;BbcvphCA{EylZO-QQovUdy|4w*%v^%Nm=LAB>D*I!)3##;t#V zcQ1#fZS3oy&zBIV+ORF3FXyeVT?^mfJ%lTndN~%rZbdF^7%edU-&fNIfy*>DMkS=5 zB2JS}KyEh((s@kEt3{)RqWQTnruDh&O#P7zMN=62AnH)=<3cv@ruC`+=v~dLMa^zo z%Sa1g^ap9J&UN(pNxev6GfRK3Kx;9=fZr_ixV z(x3w`A`sma*0_xyvpxGm3S4%GwwrjDz(NP{m-A>O{M5bxY7Pzaiyj2SuXY45KD`E| z!eE4+X$r+XeEdHucqp6>k^Cp#T$t&NHUI;>gt0=sE1&ED2uMo_%uEi!-|vGfHc@{01*RPWf;3OmcKDu@q4D`r~G_ z(cEfdB8)Dxe8|Rcw$&nDOk;}!Y+gW~kii^451AKm=;+x4SMvd&f3I;Fc=G>fCJHGY zv93XawV43cpe67!%BJw191>o~x=y17u+AJ`0N-_20YniO;WGecsI%O=*cuEYTNie# z)1u!4c5u7z{(%;Nh{C2QfCXNI1x);os8>UWsq3y)G6$A&v^7Xv2j5j5l!KIP5H-cq zh2#bm)_D|wCx&uy_%g7I zhQO3;_N&K#5-&8U3GnvX;2+0JbarZeLmcoY-vt@N#Pv-;bSZ7^BaMZHWf6}{AIHbh zrg}Px@lB<@8%BSEaa-=tE+27*iMCAsoaCGXVZdb&_Ul5p2ej^zzZOq-5!>U1tbIo( z%H{qV6h^G^=)*3(+=_v~wQl;y|9YjlvvG?FVRnAF zx-snu-~?f$))jXqriYcbVp;Lai=f z7LWwI%QDBh-25|8bwe;s6!)8egGnwV?GC_ZjizE1c_TyYYy+$qE|o_7|EJmKo7;AG|CH~k3w3D?x9E0F z3KI8Ac*p&BPG3Zxxbzx&kO7^nM^H6MWAo~CbWI!?x_!>;g-Ky^%Ijv>rl8D&<}ko+ ze8>LO)zPs7y@`dSoEow>+JpZ~@!z;KL@Q%HAB? z?p;$|4`WPDlLU^H;3-~PzR?twcq6r^GPayPVaXZ$5P@VzCtq7SNSZ`Cc~VsD;f+V> zOHgm8(cKe^_Z*r}tA1;a;}YuSPG$y=-cZ0R3-J1qy@k-WBn9{O5N}cx2lw^#^7FRy z#udOhocCr;-VyfG&bsQU~7jK=$3BDXX#V z5|YBb^8=U__EqasEAjr`GGkhAyP)o#v)+}CZOW)}8{VqNcL-u&zmwmGn@2K8;KI=-m!&T{tS+)ga26y*a5X?0&iWY?>yGgvkxeHcLrci?Y$}zH1+|a zNVc1$H+j;h=U^S=z2`+mk-33|yeD9{a zci$n8{f>Xx%33GVpxAqN1`_N&_y=%wFN06eKoby*W$>@GzII^u7Em#|hhS7f?qi!( zzaXv%i2AC#bSt`l_3X)j1u?(!zJO?faD&x(us$;H+eLREEaJ%reu#jKfFYeW`|_U` zZb3m@vdLQD5HaCG(iC`+zLo0p*i7NCZiOtKfDF3-%C_u04?^$z(SBF~N07DM86q6s z85)rr<-U=5sskV^#Ls{W1JsEKq^mSohn)PnsmRm9Vvq+GTC|-+Li)D}@9QU|fKZ#> z89U7#DC4<%_a>puerSK*^6HnbD=nP>S)=~j=3c-JutPA}tNxfe~;2BRqT5#}dMsM5r|8?n=XVw51`#Q*3`Pl-PV5$y+?;#JpXb66s zuK`r@o!+m~ssC*o6aRTX^OzQJuCMZ+sexC+W=K?c#tArlW9x1abQRQH18{65-gR*z zxAZ(CChP(w-6bcWKScj62Xj{eUF0!sK;RdgLmedIoy-yUe}XUWaUI|89DE{@0NFsM zYOufVe=mmz{>Sw{e?yw1KWrGi^+3CxbfLb7ZBRI>lvChz(hz%ElDPlU_Lv*j78+RLYcK15!Fyrw!z6z$$w`>R-O&B|%F{bhq5hog z04W$UeDp7_!8Q?HhwhEE{c7|;=n()KS{df@p@eSH46p|Amudq35H+=@vU2kn+SwAj zE4&0p(S<%bw>)UKKizKko)0#Me;01|d^_&{=?QpU9Hhlz#JPiHKYPC-1D=E=fVxNa642WUvph;I>V8~GfQLR^emR^tS?_)0nWH#e zJ-4_!dFfbh_IYNtk-Ah)aEl-7bK)NA8l8w#)jG2sTS8oJwpBXvTDCcDn!kX8iyN8< zocN=i#-6Qm7hJgE=a1vl_^>*?G1%b*{vPnxuUjB^`K^`kijzO)i$u0(*`|!G0Pr z{1+;^@g$>2+9CXSyFa;Ob&5DCe!xXimh+*Su=-fIX0p^2T8maoCPJMOt`v_g?lvNz zdE!}22fk4I@Gm*2=bRHkYhb*+xx$-?RT=!b?_t*eVD9+spO5`5ruV?7SXSD#TlU|a zotQvYjLQztfs3i+QOAQn1lqNQD}`p|xTS4840q&&uczdt4VrVdh8i8X*z1)GSOSfH zL>smDyHHd(LSwi}`6&V?=ND}22{YM!ka0|6(mhdt5P(oh#Xf9YI8hob4Th7yvGmFp z;kkYNxfAaE%MlG_{$sJ_90OJMqqKjbC}`j@OR0!f8I==;5s_5%3#~+AeII0jE+MYo zDH0CFMOu}CEEK`;w2QEFX$5SCMk;aXx0cu4;zb(3_}rT$YHo$)OKAhI5;J9}2wNjD z!fpH{j28Gwfw};#;lq&Asq+w|Pz!O8frkgAm^?7L~UGScl-?lo9__q4Y(A47B zpAJ_zT}^kjueFbwSv}rwwo@e;sb53I(QX?yttxn$9@D@(=5-kD!pK~Esfqyuf@=WA zTgZjiJe~j36VFKm??(BTo9)@v;EuTCgtL_g!+TZ$vYvfW06Xw-r%dd}`|S7x>j3e! zY*ZSodqMw~A2et>DqMPpc`KmUC?!Svac8qHsmn_-vy>Qp-uCw4DIsfvNS;<}|UqE1v1L5t(E0Zf+zv7>t?j)BRv`v89t0CVGmO=E&Mli>C zS!nCy<+GeO)r;yZQAR9$MdLo*bp7{^TDt{SskIRzs3OJU;9)CaA-<1q5$^O*7N9Z~lZ(I&w`Y4jg4DnaUm_ zn$q-85%$sxEyk6;y0f3Ta4gU~!;=$JVK8(VV_4*$$V(OYj}?suJhqS6XL1IL zI-f8ImvB!n<;~Vj4~mjA=`OIxavM+~8uu*N$Ct&YzWxY!l-5bOsMRn?*TeTXzf)AM zY6qRo|Xx!Lp#{p33m01t-HZw~2f7we9*ssbILy%RT$N?Devedw-hN zmAF0M#h=c}jS+7K;h|0aK$0?lIFzDXY4G`7He~MslRI*Sn;P6FO+^`bTwZX-S@>qW z0lywtK(O^U8SgmbQ$1A`Nq~eaVxDlPz!D&Zx19vy{1Z2&?SIGBuTA!^4o^!39e%GG znvxQ=39~R*7E_v<)8e={Ex72-5Ht-V{A7f*vYqS|j2Sd6B#HrJs(#f7`np(%MdU8M zjIAil(WHpzV1<<+_lqa=F)e90Z))bt+NgwWc-N`FaI((UFog+~_c=bXFHs;(`tW0q zS#ZdemGSLAO^FcF-i2mgsN61Wkr%pNVm|N>)M%34D;}y>mB?ngt}jE}-%J#hsb8PJ zg<|G?sjO8~m=j+}LWSX>tG`SXl&)KrP!T*F1>uvKuiFF7Hbn{{G}$M&ynuObi4&+1GJ>z4JkX_I5AxKSjk1d= z(9~6Oh;a}{YBrnqPLL5*j#xioG7m9lhMTNhtk8cNY+BuzVoB0 zhir`hasHztJ!ptjHv30W6qZg~lh}H+SOyJE3}$Q-ugoAF!8f7l+8Qep8)3HCn>N(h zsQ@TRDBh9u$+cfnZqIGVe;p-*sBybSI{0JlgNMKF{7M+GB8~$@Ai#3h@yBtcmX!(i8g_ke4V56?ZEzGLR8k1ghRaTHS&5_x?g$ z#Qvk~W|MENd;nYG*JEg>(dfT86(lWQbC|7e!E_-}KRL_#zXYH@+kK9-<>>jacqVtfd~w70vFyopsz0`P^V+|8jqp^S zT~JBkxJG`-F@u&F)f0d0#(4j!y)}qltWbOP@ zAJTksj6=pJv)9d>GYnIo_QE?Ob|d%G`VzROz2|6k z6l-NpVtAXHu_O;7d6z;~o1U7?{}Q;*F^gCK1jjKpZ8aIke{q*s4N|!rkunY*8ut;Z zL$_>4yZ$tXS!(df&}J-bSkhP~nhy|V@9EyOjDKE!Dwe)pC4o!ec^10NdY)mO^OtU< zqu0*o{LU{vA+To}zM|AN+t3iT$w$%ick;^o=7a^ehFmsxM{_d0HSm?60F;IPOxMfF zIbatnUSgUuC6s#)Q3Fq@gu%TIm&6e@So(f%zXtbDXDx#Nbg1L8%rd?Zs7B7*KnN@o zm4$PQ2aP@}vJIoinIc1vt`p^uYlcmHspz3c>9ti~cImcMEoLUrwRW+LaBuz;E_2A( z+(b`>#px%qWK=)t@+`|h_8M|?dZ~)1`$|wYG2D`9OKZFZ1j%Z0V6 z$XWk~^;0mR6hd_Q;PDfHc)!_gX+`erEyKU-|>^{|+m*+&>F2P~+ubElv&U+s; zMOT;j`(EF#-|hcKD5t|pQn3(uDllY-t&_pRD*Rd&>*Wh#IPVs`(jzhK?u++PJ?nFk zsKQxNQAVBF`E9#CVppX=7?%)6hcn3Nhks<5Y|Meq-1I~_mM)aITOCfslr1Q4`k4Vn zo_FL>Mxadlp;a!UHxw!v;2cL@VG&^!Pm++mETuJhL`P_m6a3dfQ=uEg%Z{(Sa>TJ% zH%h(4b>L^vU?r-`;&R~XY?y*lUiHs7_2nWmZq&Cc+5N_o4*hcVpY?V2KUd4pInoBw z*Dv#EGKstlA9Oj1YUTM9qnq@Y`u!w)Hh=#LlF{TVN6{Z9A+jg}4up}QZsY_JKR)L(fx%d$j-tX>- zDaxr;2{IYl$t%Aj+7Yw(wb@-;A3nz*$3%E1E)?9N5FCBDUoX|yY1kr zfWQ{f>0_j8AgNcqau@?YJ<>3bmWCRbAHtBEc%7TAupMYDyhiPwj8m+t>4`~YjtlR_wW9rJw#o-CuSAhgo)2pHC-F*A&z*s{N2g~rsor5|9DN$wLrN^N`zCH{## z0!?mI(KswjWMRQjGM5e)D94iW;~(YPc$$j@sB|^F$EgsP`T4UwX-tfb#bdRV;A$iBXvzM3@=aFWUEX%|J*ygV$I^db3N@n%O(m^UGhrL383yT z`fv;-6G}Tyb0jxdo-VRPD4t6A6~20;OzN{o`~VT_EKfnk*OdTvp(I=Wfd(rJuN0O9 zO!GR!ejfTqa_mEeZsh=hh@cN17>xfY(q1`jc*iLJrU%ZwePcLUG8cuF9c85<0GuNi z3WV88IL`xuI(Lo|b{+i2=;sN%!mtpSZM3E>f84c|fLsfKIyqQKB30N*kg6!{>z%d!r1){}Y= z8j0E&5CNZpIxi^}5Sn1wbAZF_+NJ+Ai-(Ns2gvm9w}n*FUK(2NQqgolH{>4;uS z_{_9R8KALTb#FaqsieTzXtWcGq7xAt6VZ{>xUWac#oNPr_}$r68O4**_s*#OQ)6-p z(V`NGQa4{5iI@16BlsnU>F8v|N7$xtRfv?}?efaczWPd@%d10)C9D|Yc3dLyJ|uoc z9J|^xt&=e}f%E)4AG-vM{O~a=B=V)OLLL#be+<}xKazE+tEionvTi0Yfi9u3BIf^{ z6UXt~)3)y18FhrztLv<*S@cUWB;M{@Z-Wx!2~mVdsl~{bj3CKea9T#?kE(L{2g~@% zhPGsu%JKch+FVb?WNAjl=wwoqp3iJBc?8?Nz7j2El*Z4tiVbv@@b0doV?g8`+VL0u z+va-7wsHNhFK}_OV9ktOs&vX&f_gB=U)A1)3L=vlRPm2#SFPj+ldfpf-w1IBAZ#=B zfq{y4Gm$gYqfaGT0jQdKPum>mN{C4*LhdDmJx&#+ck4+3>6y% z&s8(>scOiSKIas!i}Vn4orh&_(p3a~&ukYeTH~50X}t}L=t085xv}kvOuO#Wel?03W#B+I5zE`mmtNej&8T)u4H zT6JUpm*}aKgs+2W;sM$>81aVq(M%JG6er@Gm^OroJNgB(JvQ1VxDg#hxc*HSjE2-P-IvS38)>j0J~r-4EMVr0D9wX7ONy7J7};c@0ixt4`}QXi9= z69xU^G6hn%YI%~2;0@E2TjF`Mb@c<8@p$gY|tS%CF&IzAJ z0-{;AvH`_1l4np-Nv@u-jYH&c5_fr6DIh}CN>96-f%K)l<59m@70pPTCae-$F1s;X zxgE43SW5K+s$q1Xm|kWUE2_))v5&aL`HDA6&C7Jfq{=tiJY_qJ{Y4gWCo&b>ztQ|} z$Sf6z$Q}1U%rm$kE$@<>tu&Y#76I^Ge>01rPU@%8rr&1hOEiu<16U4L)W^9hh`!-#dYW<& zrTqDTS>G_V_Eptq3WY3gi}=!V)y_isvd=Tr zDmb)dZg9`DDnfRp;TI38hX&NbsK}~V97!Cj!!nMCMAMFu5ggD>34ZkqIb&wGO8~qGk&OP&Czw7>2bj=cw?jRLV2V)~clR z(ql!59qI)^FUt@bPi0PP`7tmP(zQ*gsNS#fTwj-zt{TKtx_(41LWR$Pw#3sjCkd!b z{`2*K@gOi%o~XI-ho2DFV-=`aNYz|Moje#qi*8+rnK<01Q77dNaM>xTNim9B!(eK=HML^A)x3%H+M7O|#ks`KF@1WTf11NaDF#O3w6;G^ zT414+x~Qn&4dg_9D4lZZYTe~mPENYEU1+q$^b$O`-hZSq59z?Z$0ZyTWzsL8mVM4v z6>vIGO-yRshj=1Qi6{g&Lk@9sBeYEksGV+B~^hc#-$OB(9oM6oU=_4G&{z;S#+Flj4tNFw%yhtD;xMtB;UiY z(O^1E$l>b^)S0U*jCPl7u4CrmMz^g_@O+kAb+8;LmMq?jh|W|XM%!txx0;*AGBV=Y zvndnZ%T|-SGJeHnjI7Z5iHol>8~*5M=;Hvbd2MoL`kYF8g^ZP%c`!&F2A>vgnjp-! z?`|<*(sieWAeKpOre}>;NjhBKKkCe;0$Za=nVu724r(}L2M!e$>%=_MZ{%cq4qc-z z9eapX^OQJ>KlvMfL*qU-qb^noJeT%K(f1l-Z92>^2oXZxIMTH$h9r_dxb5|LhG_4| zPPcPkm5CADQ~et+oIc$t*!M3ASwwvh%?SI*XM-Xbz2o;<*fBaY7EY^1wD+uv;0@N2 zQ&Lp=>!XUQ;z6wmlVYj$y#d>-xSDg^=5tEKQNEP}rHiC2PGY37DuduZ)cGFYcJ$jQ2T$qFN1R~j)R z*iow<%zeGs<^w?{7lp(@+zMtvT%#(pt3@^284;4y?pKWPxxW8gJ9OckTf7!WBFpG) zL`EtPu1!Tv(G+7RR%Y_uj!jnP922WVWxg}$U$5JzVbidm`wR!&6!6A}x6JCvpy;nF zBEXAMh?j;Zx*V>N25d0w^a~-lT{p&S^TARz|Ds6eQ-5)&|3OWX9he%|pitR-HxkNa zCh6B?X~fT79b7n$i`->hV5GjsG$Ibd7sxyC(b7l&w@fYLZr3b6R=^M*Z)2ydA;{(}^Sj*9>93*Q8ZbBv;x=vvVu& zA8wL+z#>vR&1B@;G`rtwWey2z$`Pm03V9%zMT=OKXO>S;BkttPc4$ktYPg1!P9E!T z-Pz%dkfem`VJta|_72Y94Ywr8VvLwfu=?}kuFMTKljaTKru`u-hE|31{MC8ftK%<> zYVm15tMl`J{%QH!f?MqFg7PtUfg1HO!}D`acJp42-~h94K|S<^S8`X?c9*a7wK$$< zptP4Hkqx7vkK*9O)5QZnIE(#y)=d1oCN^fw`s7wxTW%j2ZLH5%r}vcITqNk1NGK-D z->TSsmeub1zfYhiO{>}hJ~k4ErNU~H$&!JpG#52If>jcHGub?UjV_rWWjj5rRf@f4 z!^rctY(p ze*P>EP=@pF709C>gwG1JKCWI~xm>XZ59hH_#eRoff@U7B0;Tf&n-eZO`*v3$Zoh%? z{h5_v;G#hRK;<1>6X0YOGe+fTR$2~C%2tqbjzu6i!1f`iN>^i(GUH*W7mdU4&M`NG zgGDLtVV$3)7$9dr>6OwL^h3}lj6|nPSP%Q$<>xl#=}Uaa6BT54}ucX2MhdqzujElZsA9FIEh=8R(FK2=V%N(UAJk}LCzOY?5d?N_riEKjCCJM@nPrcJ z2$eXoJ0&9$vo*1P(A8)NU?|*;NxxbN)bv`@)KE72_Bhfn6XSLi!?Ls@ugdb$(lSz* zV6kRZQzH=0CYS$MAo#OWR-JW%ZlFYKU-nYL2WPUk^jq2H;1R_6_GbTHv4nt@Wl_hQ z<>PTdBgM@b#v8G|AE!_%U0~lZFUj}hDo|@(P3XYe*Q3268(z6^FWA_63s-qrZmUBg z(%)<(t$xL-L@)!RLg^(bZY40ClRB zFUny;U6kwYsS3@ma9Dh#Z7zk3bJET!p*3EVHy6jmRgs43O$Req!^w)u56iqtFe3QU zygRPEDe!vnWrh*DnSN4kv27o5HE2*mJY@!#(NHTV0{FhV7u&c@qGhaU*Qftu;~$v7 z|By({5usl35jMvC-Y3}xC7T4HKsuq7!0EGWxak2sEQ)D~e{5U_x)8n;&rmfb|)$&Jai0u(|?f#W{ zgJe{6m2JP`p0}no=bLWhAMCV^9;;C8FTGZpWpG9z&9_+uvw1Lwjd<#GRw| z3=;4DXsmH~l?y74_kP!vA8vpE*D-EphDMoXT&+AOQFqTZFJFI=w^rWGYJdAis7)~- zvxVQEhRvJEIf6|sbBNSXEnSsaVRS25VPWPr8(R@Mv*VoXhdDSK(c#B2flysH@`-8h za8H29Np(PTzO)nfP6aJ*`O|vT~?fQr_ zCnil$`PU9^*_=C~>PJ_ziAI zgjUL`!Y`O9>U{J8(hNBiR&{IjIYy_f(;FX^4R5v^ZrdK)YGy_U+Us*e>^tS+OA00f(%Zcd*t*9co@s+l$UqLf} z{ru;)QBWS&03mET>Q@}r98Z0HL$j8}+4NSau8EM-*xB6kw(sP462tHcjc)>vO?v#aFEqkcDk=pTb%S3V~!g#GMlXtQ_M`r}yarJjf8 zt4O0e{1NVXu#t%;@wF*oGs(S8!;W{qU9T+qp`q|@Oh@apt!OwtTx5STa!wt#MWrh9 z&&2Oc=9{*$K9$zTDXSJ@TEvl5cT4KO(Pxx=aeA|^@uUS+1Mv>7cmZTqKp}<1l>0cT zO9%_lK0~%ANlCFD^*iHmIpigC&C@nM)Y&w|hJU-AeSCRxc}DZ(e6wozg5X4R-NO*C zx?J(VeuJILgoHQ<9T?Ji2?q>IR)eqv4A3UEb$s`JDrG`{UlZIc|8XWmQRrH3Sy?QW zD;0PQ=KZC(r2I|y4^B)!NlEghlgj5d36CEm<%}qA2kwp%8h!+hb)Pb9T@oEqV|wW& zsD4(<9;h+^8!}ZgT_tbO_VB{^e}0cE>BPI5XgRHr4GTM`PJ2XuQg7!}@-bwoXw*%2 zZ!R?<(Mg4qFEe#A<$66DI@L-_KTrFppw@ZcCrn1A%e6<^_|`7>E9n5Eg;PuOcQC4F zc1212(Lr-laGEz+j(3IHE^p&e^)cpNv@&JOpVjYN6Y{;#4Kyej=3?j}%TQ**&cyL} z(D3>VRddzHOx4s~6*^y^MW#`uEuspvA(^&&_V7Qgn$~y%nO^+quorP#Rjlm^Rc_iP zkk;+*YZ72Cb>J{_LY+YLFKvuX)?0_N9D^>Br4c#?vg6WjzWb5AR`vQOn^o8VTffc` z*aFRuhX-%0-XRfPPPd-R+%+?gwDM=ga8_AzjYf3c=d3;UlH?uh}ewaGIN>366b9ET0w?`)3c#{le=nU5?~9w@2$&l0T$YQA?}G zmXM}qPYYN5L^tdU7E{ZL7-uqZxRgV&i=tAW;xM)nyQ3GjiR8H>wXTb@{a*U1u`<)Z zLA$JZ)-)?*?NN>)TFOX@A@~V-N-Bn0M)>xs~vpA7LY5wvp&AT>RzCjOU zMLRxIA_d|eSHUM4-_Y>y;o_cx&Kpv98$5B}>}%>Qp7$UrQf%^JDpK5TNtvb_)XDU< zz0n^$+=Yy?C$3B8EwFS|uDY0zFpVx^94J*#L&3r(2KhO+%M=q<6fYnoR>;KalL{!9 zD;fm|*g4F-ggKq>C?b9Fb?%KEz_xh z!`sU9S7ah=9S z0XRmaZ_Tr^rrxSgq&nJq1D477zF%N8g-rRzoQL#~7?L`fl4u16g~U-Kjh^igaVq|} zCZ*A!R~E%*oG0BDxAXj@@cmX+H`4yFt7le^bEu4qH?Dl-R@ow^$#a-*l7Pk`3>mJL zLG(iQ`#hK2;T+ua&$%j>A>44J{r-7?Y;bn(n;maLso>x`g1(xD*;kJjA(z~}H+|FU zw?+Fey}zAPlj00Upl(YyBbPD9mT#Ji;Eq!asmY(YomCVjKO^Ml3dNOxXm>(irQn|kxMx4Yi*B&k(r zCPQe}@~1Ej%`WMOle=x*^C?jcms-bF3EW=L&?*jvlZxy9% z7J;oor9fV#d%tVBOrLd*^1Z26SEmSjy?%`k9jxxujk`xWP*QkCWyr6o=pzJBTr1XmtA9*a zdwav9s^QQ7468(C)Y>`F?4C+9Ph*TMtt=eYZiNXe^mQ8jQ@76@z6-z9 z)xFahF*Y|Mb&t^uk4s=^$+NiP95sEPS^y%YFB@)jkHg2W*)guIBYaVGRgeIC5yL-C zKX|C^ir)B`I+?1`%V)EjZGq;FxNMX#Fly9kwKT`HSfbWef~za?u`PP(?4ONz&+dQS zbMTDm%4ThX4yjdtnZ2q++ z;e>r0Daoz8m7<|GpDto%bIOQ)OvM-@?EDDlo)VEcL0i)9md$;1iefcmwQl$0e&J(z zxLWyKez6GC@h>i;eMF`4A}U7H)?2jJ?N`ff%AioOk`e23dV1DE1siZrHquS$ip<+j zGHb@aTh^)x58mTtELR!VvVJMHajK!8nb6J2D{((htC}uWSK}cyFhN%P|4v0b8VNh3 zHL56TcUqLHxDGKVe7mU_BTdz&0%B@2zX+&281y62xjXArEZ_AiH+ylE%Rj&TZU zl3(f)(TsMv4O4Tr-um?_SCLrny!6zxiO*5oJNW&4SaH27^3y5D)+tPl#*wZ^+x2X3 zr|KK?t0viD&Jp+&S+nZ=a+o5BUEEUOZ4;(r^;$F0xkrCLTKB7FIWty>06XqPUU@ER z=VmZbe+sR<{9t9Ze)#v3u2({~;5uaY7ZFkd!FJGbX;6Z<1wG_1_Wu>?2^IEHc0u=< ztyE(Lc*9(SQX|-{-amIyl2y(618p^9d%%oWlh~%1qD)t>n$$>MKwR3cH)M1(?%72m zDZ%ryK4XbyYG{|MHS;-#r%eT)pGo~S%QdYOsg`qpj>lK@(M0Pw4Xb*v2%W^{a z;tq=M@`__Bg`FC&j_c}9;$&H|PcAB3-e^sUoBgxC9qQqtz@nV{7iGO6Rq7VdtAUm0 z!SR5X>6*}evqD``Q;m|-Cw#^Wt*VRX%vCdV$qWLMGpMpe$JrTHT|+|crQbNc#w6Iu zc#1XCVaYkwrP?D7it2OiYK$g%fPQH{KltR`6T0N*iU$ep=&rd;cC9<(+$0W?ZqT4p zMQY91b$D{}L>45&(_1so5*7{T2SK0DP)H3CY^DfZb&6xj#?JWdO~B>f7^H@&_mj#) zB+b*r*Djx$Ws3+nMo&bf0`vYz#actah^P<&s;t;hmZ)>?2L`+;d0;YOl(>U%*X z|9EDK{TY)e>Iahf&dc&L*P-D;L6fo}UD1`V;HX`N%g=Dq9Xm@zKa9k*!u@?Nht_J(i}@4PiS z8+=!rxhG*u$u!}E%`Q0h*KD?1MQqjy5I6?L%9y3CLQGe{+v5}?k} zR_^QlVW%lm%Z_M zDIy&PVCs?A&v5<1DPBQf23ROC!UtH3VLE~(25KCqWy(W7tZc2r({^6>+00etbnKfg ztR;r*X*3Ij$c%5|pYrk?b68xC{Aar=0$!Vnm!NjdN7YSrGL1>1Hd-?+d0E<@AG$Q_ zgUKZww5T|8HW=}h>SdX8IznYfih37Xb(Xu=%E%bJ@4W zRLBRTAmH!aIRR14E;GAN-h?J=pw6b}DGJ1I+2GE5L|6?UygYJ;d4=%6TSUc=F)J5m zU^~?IgXEn6m`Geq%4@R9(|TS@;^G#)8G0WJJaD!jNe}xa-+a{c0i|>$X4I8$Q%(#9 zVpDg{;z_i;14BgHci6FyC}6TYMJ(l%c#U%)g2ncMx}ZiY+c#6)bXg&F)*@}Vema#2 z-Q9BPC~k3)PslmB z(i-+FSLqt5jr2XIK^daixLVsdCRAB8vaeBR1Lg8DXkeDC`jYkN2-saF7t9>BpFD4JkrKp$KA zAL@2H+T7=td2fHniTr5BwPpvVCMvwr99iMeii$Xu81{Q=%fuK83Ql;>8VHJl^6Di6 zgXC9gTW)iu(+NC1;Zq!F;2}a;0!js>P0lSt(?5I^=bFJVp1g$yBn^6zPK{Q8ij1;J zE&M7U)lFBkhp=D%55F2SV`}D>*@rI&NBiQ}PX}KDL z@n)2OSK9)#-C5m?+XI9Lho1~2=GPxT9qk>?`0n+WceB3Q{c`jktEiS=-cmaRo`L@} z{BQT|+s}K4hp#q1q{FBFGrU%DG$rTo8<%^cE#eocI0d8O<>S-IWc1V4*7xtyvZ}3r{Jk|fpWMC;&-0Qf5|6yN z-A;Ugf8)j~{Y$_5zVQ7d@j@>S!ccgD7l+X!aen)z=L6kR4PEIMY1%1fKL?NXdY9ng zp$Pr&Jpq_*ys6-2oep^QHv&)4eIhUY$lH$Mot+&YKTG+uFo?IqD2aA9f>4#s>t^3x z`boRp4*YH7CgH?j&|89T0Re*`KfHr_1+Oc;T|9ip@!giD-L6RiE|4};x{*M>X oml~`&|2uHtz<~n?4jede;J|?c2M!!Kc-Zj&1MZ2imH?Oo0D?ENMF0Q* literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/header.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/header.js new file mode 100644 index 0000000..8ea6f79 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/header.js @@ -0,0 +1,183 @@ +var tap = require("tap") +var TarHeader = require("../lib/header.js") +var tar = require("../tar.js") +var fs = require("fs") + + +var headers = + { "a.txt file header": + [ "612e747874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303430312031313635313336303333332030313234353100203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + , { cksumValid: true + , path: 'a.txt' + , mode: 420 + , uid: 24561 + , gid: 20 + , size: 257 + , mtime: 1319493851 + , cksum: 5417 + , type: '0' + , linkpath: '' + , ustar: 'ustar\0' + , ustarver: '00' + , uname: 'isaacs' + , gname: 'staff' + , devmaj: 0 + , devmin: 0 + , fill: '' } + ] + + , "omega pax": // the extended header from omega tar. + [ "5061784865616465722fcea92e74787400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303137302031313534333731303631312030313530353100207800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + , { cksumValid: true + , path: 'PaxHeader/Ω.txt' + , mode: 420 + , uid: 24561 + , gid: 20 + , size: 120 + , mtime: 1301254537 + , cksum: 6697 + , type: 'x' + , linkpath: '' + , ustar: 'ustar\0' + , ustarver: '00' + , uname: 'isaacs' + , gname: 'staff' + , devmaj: 0 + , devmin: 0 + , fill: '' } ] + + , "omega file header": + [ "cea92e7478740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303030322031313534333731303631312030313330373200203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + , { cksumValid: true + , path: 'Ω.txt' + , mode: 420 + , uid: 24561 + , gid: 20 + , size: 2 + , mtime: 1301254537 + , cksum: 5690 + , type: '0' + , linkpath: '' + , ustar: 'ustar\0' + , ustarver: '00' + , uname: 'isaacs' + , gname: 'staff' + , devmaj: 0 + , devmin: 0 + , fill: '' } ] + + , "foo.js file header": + [ "666f6f2e6a730000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030303030342031313534333637303734312030313236313700203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + , { cksumValid: true + , path: 'foo.js' + , mode: 420 + , uid: 24561 + , gid: 20 + , size: 4 + , mtime: 1301246433 + , cksum: 5519 + , type: '0' + , linkpath: '' + , ustar: 'ustar\0' + , ustarver: '00' + , uname: 'isaacs' + , gname: 'staff' + , devmaj: 0 + , devmin: 0 + , fill: '' } + ] + + , "b.txt file header": + [ "622e747874000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030303036343420003035373736312000303030303234200030303030303030313030302031313635313336303637372030313234363100203000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000757374617200303069736161637300000000000000000000000000000000000000000000000000007374616666000000000000000000000000000000000000000000000000000000303030303030200030303030303020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + , { cksumValid: true + , path: 'b.txt' + , mode: 420 + , uid: 24561 + , gid: 20 + , size: 512 + , mtime: 1319494079 + , cksum: 5425 + , type: '0' + , linkpath: '' + , ustar: 'ustar\0' + , ustarver: '00' + , uname: 'isaacs' + , gname: 'staff' + , devmaj: 0 + , devmin: 0 + , fill: '' } + ] + + , "deep nested file": + [ "636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363633030303634342000303537373631200030303030323420003030303030303030313434203131363532313531353333203034333331340020300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000075737461720030306973616163730000000000000000000000000000000000000000000000000000737461666600000000000000000000000000000000000000000000000000000030303030303020003030303030302000722f652f612f6c2f6c2f792f2d2f642f652f652f702f2d2f662f6f2f6c2f642f652f722f2d2f702f612f742f680000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + , { cksumValid: true, + path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' + , mode: 420 + , uid: 24561 + , gid: 20 + , size: 100 + , mtime: 1319687003 + , cksum: 18124 + , type: '0' + , linkpath: '' + , ustar: 'ustar\0' + , ustarver: '00' + , uname: 'isaacs' + , gname: 'staff' + , devmaj: 0 + , devmin: 0 + , fill: '' } + ] + } + +tap.test("parsing", function (t) { + Object.keys(headers).forEach(function (name) { + var h = headers[name] + , header = new Buffer(h[0], "hex") + , expect = h[1] + , parsed = new TarHeader(header) + + // console.error(parsed) + t.has(parsed, expect, "parse " + name) + }) + t.end() +}) + +tap.test("encoding", function (t) { + Object.keys(headers).forEach(function (name) { + var h = headers[name] + , expect = new Buffer(h[0], "hex") + , encoded = TarHeader.encode(h[1]) + + // might have slightly different bytes, since the standard + // isn't very strict, but should have the same semantics + // checkSum will be different, but cksumValid will be true + + var th = new TarHeader(encoded) + delete h[1].block + delete h[1].needExtended + delete h[1].cksum + t.has(th, h[1], "fields "+name) + }) + t.end() +}) + +// test these manually. they're a bit rare to find in the wild +tap.test("parseNumeric tests", function (t) { + var parseNumeric = TarHeader.parseNumeric + , numbers = + { "303737373737373700": 2097151 + , "30373737373737373737373700": 8589934591 + , "303030303036343400": 420 + , "800000ffffffffffff": 281474976710655 + , "ffffff000000000001": -281474976710654 + , "ffffff000000000000": -281474976710655 + , "800000000000200000": 2097152 + , "8000000000001544c5": 1393861 + , "ffffffffffff1544c5": -15383354 } + Object.keys(numbers).forEach(function (n) { + var b = new Buffer(n, "hex") + t.equal(parseNumeric(b), numbers[n], n + " === " + numbers[n]) + }) + t.end() +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack-no-proprietary.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack-no-proprietary.js new file mode 100644 index 0000000..d4b03a1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack-no-proprietary.js @@ -0,0 +1,886 @@ +// This is exactly like test/pack.js, except that it's excluding +// any proprietary headers. +// +// This loses some information about the filesystem, but creates +// tarballs that are supported by more versions of tar, especially +// old non-spec-compliant copies of gnutar. + +// the symlink file is excluded from git, because it makes +// windows freak the hell out. +var fs = require("fs") + , path = require("path") + , symlink = path.resolve(__dirname, "fixtures/symlink") +try { fs.unlinkSync(symlink) } catch (e) {} +fs.symlinkSync("./hardlink-1", symlink) +process.on("exit", function () { + fs.unlinkSync(symlink) +}) + +var tap = require("tap") + , tar = require("../tar.js") + , pkg = require("../package.json") + , Pack = tar.Pack + , fstream = require("fstream") + , Reader = fstream.Reader + , Writer = fstream.Writer + , input = path.resolve(__dirname, "fixtures/") + , target = path.resolve(__dirname, "tmp/pack.tar") + , uid = process.getuid ? process.getuid() : 0 + , gid = process.getgid ? process.getgid() : 0 + + , entries = + + // the global header and root fixtures/ dir are going to get + // a different date each time, so omit that bit. + // Also, dev/ino values differ across machines, so that's not + // included. + [ [ 'entry', + { path: 'fixtures/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/200cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + uid: uid, + gid: gid, + size: 200 } ] + + , [ 'entry', + { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + size: 200, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/a.txt', + mode: 420, + uid: uid, + gid: gid, + size: 257, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/b.txt', + mode: 420, + uid: uid, + gid: gid, + size: 512, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/c.txt', + mode: 420, + uid: uid, + gid: gid, + size: 513, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/cc.txt', + mode: 420, + uid: uid, + gid: gid, + size: 513, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/dir/', + mode: 488, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/dir/sub/', + mode: 488, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/foo.js', + mode: 420, + uid: uid, + gid: gid, + size: 4, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/hardlink-1', + mode: 420, + uid: uid, + gid: gid, + size: 200, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/hardlink-2', + mode: 420, + uid: uid, + gid: gid, + size: 0, + type: '1', + linkpath: 'fixtures/hardlink-1', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/omega.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/omega.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/star.4.html', + mode: 420, + uid: uid, + gid: gid, + size: 54081, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/packtest/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'fixtures/packtest/Ω.txt', + uid: uid, + gid: gid, + size: 2 } ] + + , [ 'entry', + { path: 'fixtures/packtest/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + size: 100, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/symlink', + uid: uid, + gid: gid, + size: 0, + type: '2', + linkpath: 'hardlink-1', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: "fixtures/Ω.txt" + , uid: uid + , gid: gid + , size: 2 } ] + + , [ 'entry', + { path: 'fixtures/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + ] + + +// first, make sure that the hardlinks are actually hardlinks, or this +// won't work. Git has a way of replacing them with a copy. +var hard1 = path.resolve(__dirname, "fixtures/hardlink-1") + , hard2 = path.resolve(__dirname, "fixtures/hardlink-2") + , fs = require("fs") + +try { fs.unlinkSync(hard2) } catch (e) {} +fs.linkSync(hard1, hard2) + +tap.test("with global header", { timeout: 10000 }, function (t) { + runTest(t, true) +}) + +tap.test("without global header", { timeout: 10000 }, function (t) { + runTest(t, false) +}) + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + + +function runTest (t, doGH) { + var reader = Reader({ path: input + , filter: function () { + return !this.path.match(/\.(tar|hex)$/) + } + , sort: alphasort + }) + + var props = doGH ? pkg : {} + props.noProprietary = true + var pack = Pack(props) + var writer = Writer(target) + + // global header should be skipped regardless, since it has no content. + var entry = 0 + + t.ok(reader, "reader ok") + t.ok(pack, "pack ok") + t.ok(writer, "writer ok") + + pack.pipe(writer) + + var parse = tar.Parse() + t.ok(parse, "parser should be ok") + + pack.on("data", function (c) { + // console.error("PACK DATA") + if (c.length !== 512) { + // this one is too noisy, only assert if it'll be relevant + t.equal(c.length, 512, "parser should emit data in 512byte blocks") + } + parse.write(c) + }) + + pack.on("end", function () { + // console.error("PACK END") + t.pass("parser ends") + parse.end() + }) + + pack.on("error", function (er) { + t.fail("pack error", er) + }) + + parse.on("error", function (er) { + t.fail("parse error", er) + }) + + writer.on("error", function (er) { + t.fail("writer error", er) + }) + + reader.on("error", function (er) { + t.fail("reader error", er) + }) + + parse.on("*", function (ev, e) { + var wanted = entries[entry++] + if (!wanted) { + t.fail("unexpected event: "+ev) + return + } + t.equal(ev, wanted[0], "event type should be "+wanted[0]) + + if (ev !== wanted[0] || e.path !== wanted[1].path) { + console.error("wanted", wanted) + console.error([ev, e.props]) + e.on("end", function () { + console.error(e.fields) + throw "break" + }) + } + + t.has(e.props, wanted[1], "properties "+wanted[1].path) + if (wanted[2]) { + e.on("end", function () { + if (!e.fields) { + t.ok(e.fields, "should get fields") + } else { + t.has(e.fields, wanted[2], "should get expected fields") + } + }) + } + }) + + reader.pipe(pack) + + writer.on("close", function () { + t.equal(entry, entries.length, "should get all expected entries") + t.pass("it finished") + t.end() + }) + +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack.js new file mode 100644 index 0000000..0f16c07 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/pack.js @@ -0,0 +1,952 @@ + +// the symlink file is excluded from git, because it makes +// windows freak the hell out. +var fs = require("fs") + , path = require("path") + , symlink = path.resolve(__dirname, "fixtures/symlink") +try { fs.unlinkSync(symlink) } catch (e) {} +fs.symlinkSync("./hardlink-1", symlink) +process.on("exit", function () { + fs.unlinkSync(symlink) +}) + + +var tap = require("tap") + , tar = require("../tar.js") + , pkg = require("../package.json") + , Pack = tar.Pack + , fstream = require("fstream") + , Reader = fstream.Reader + , Writer = fstream.Writer + , input = path.resolve(__dirname, "fixtures/") + , target = path.resolve(__dirname, "tmp/pack.tar") + , uid = process.getuid ? process.getuid() : 0 + , gid = process.getgid ? process.getgid() : 0 + + , entries = + + // the global header and root fixtures/ dir are going to get + // a different date each time, so omit that bit. + // Also, dev/ino values differ across machines, so that's not + // included. + [ [ 'globalExtendedHeader', + { path: 'PaxHeader/', + mode: 438, + uid: 0, + gid: 0, + type: 'g', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { "NODETAR.author": pkg.author, + "NODETAR.name": pkg.name, + "NODETAR.description": pkg.description, + "NODETAR.version": pkg.version, + "NODETAR.repository.type": pkg.repository.type, + "NODETAR.repository.url": pkg.repository.url, + "NODETAR.main": pkg.main, + "NODETAR.scripts.test": pkg.scripts.test } ] + + , [ 'entry', + { path: 'fixtures/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/200cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + 'NODETAR.depth': '1', + 'NODETAR.type': 'File', + nlink: 1, + uid: uid, + gid: gid, + size: 200, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + size: 200, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '', + 'NODETAR.depth': '1', + 'NODETAR.type': 'File', + nlink: 1, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/a.txt', + mode: 420, + uid: uid, + gid: gid, + size: 257, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/b.txt', + mode: 420, + uid: uid, + gid: gid, + size: 512, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/c.txt', + mode: 420, + uid: uid, + gid: gid, + size: 513, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/cc.txt', + mode: 420, + uid: uid, + gid: gid, + size: 513, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/dir/', + mode: 488, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/dir/sub/', + mode: 488, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + + , [ 'entry', + { path: 'fixtures/foo.js', + mode: 420, + uid: uid, + gid: gid, + size: 4, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/hardlink-1', + mode: 420, + uid: uid, + gid: gid, + size: 200, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/hardlink-2', + mode: 420, + uid: uid, + gid: gid, + size: 0, + type: '1', + linkpath: 'fixtures/hardlink-1', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/omega.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/omega.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/packtest/star.4.html', + mode: 420, + uid: uid, + gid: gid, + size: 54081, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/packtest/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'fixtures/packtest/Ω.txt', + 'NODETAR.depth': '2', + 'NODETAR.type': 'File', + nlink: 1, + uid: uid, + gid: gid, + size: 2, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/packtest/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '', + 'NODETAR.depth': '2', + 'NODETAR.type': 'File', + nlink: 1, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + + , [ 'entry', + { path: 'fixtures/r/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/', + mode: 493, + uid: uid, + gid: gid, + size: 0, + type: '5', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: uid, + gid: gid, + size: 100, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'entry', + { path: 'fixtures/symlink', + uid: uid, + gid: gid, + size: 0, + type: '2', + linkpath: 'hardlink-1', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' } ] + + , [ 'extendedHeader', + { path: 'PaxHeader/fixtures/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + type: 'x', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: "fixtures/Ω.txt" + , "NODETAR.depth": "1" + , "NODETAR.type": "File" + , nlink: 1 + , uid: uid + , gid: gid + , size: 2 + , "NODETAR.blksize": "4096" + , "NODETAR.blocks": "8" } ] + + , [ 'entry', + { path: 'fixtures/Ω.txt', + mode: 420, + uid: uid, + gid: gid, + size: 2, + type: '0', + linkpath: '', + ustar: 'ustar\u0000', + ustarver: '00', + uname: '', + gname: '', + devmaj: 0, + devmin: 0, + fill: '', + 'NODETAR.depth': '1', + 'NODETAR.type': 'File', + nlink: 1, + 'NODETAR.blksize': '4096', + 'NODETAR.blocks': '8' } ] + ] + + +// first, make sure that the hardlinks are actually hardlinks, or this +// won't work. Git has a way of replacing them with a copy. +var hard1 = path.resolve(__dirname, "fixtures/hardlink-1") + , hard2 = path.resolve(__dirname, "fixtures/hardlink-2") + , fs = require("fs") + +try { fs.unlinkSync(hard2) } catch (e) {} +fs.linkSync(hard1, hard2) + +tap.test("with global header", { timeout: 10000 }, function (t) { + runTest(t, true) +}) + +tap.test("without global header", { timeout: 10000 }, function (t) { + runTest(t, false) +}) + +tap.test("with from base", { timeout: 10000 }, function (t) { + runTest(t, true, true) +}) + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + + +function runTest (t, doGH, doFromBase) { + var reader = Reader({ path: input + , filter: function () { + return !this.path.match(/\.(tar|hex)$/) + } + , sort: alphasort + }) + + var props = doGH ? pkg : {} + if(doFromBase) props.fromBase = true; + + var pack = Pack(props) + var writer = Writer(target) + + // skip the global header if we're not doing that. + var entry = doGH ? 0 : 1 + + t.ok(reader, "reader ok") + t.ok(pack, "pack ok") + t.ok(writer, "writer ok") + + pack.pipe(writer) + + var parse = tar.Parse() + t.ok(parse, "parser should be ok") + + pack.on("data", function (c) { + // console.error("PACK DATA") + if (c.length !== 512) { + // this one is too noisy, only assert if it'll be relevant + t.equal(c.length, 512, "parser should emit data in 512byte blocks") + } + parse.write(c) + }) + + pack.on("end", function () { + // console.error("PACK END") + t.pass("parser ends") + parse.end() + }) + + pack.on("error", function (er) { + t.fail("pack error", er) + }) + + parse.on("error", function (er) { + t.fail("parse error", er) + }) + + writer.on("error", function (er) { + t.fail("writer error", er) + }) + + reader.on("error", function (er) { + t.fail("reader error", er) + }) + + parse.on("*", function (ev, e) { + var wanted = entries[entry++] + if (!wanted) { + t.fail("unexpected event: "+ev) + return + } + t.equal(ev, wanted[0], "event type should be "+wanted[0]) + + if(doFromBase) { + if(wanted[1].path.indexOf('fixtures/') && wanted[1].path.length == 100) + wanted[1].path = wanted[1].path.replace('fixtures/', '') + 'ccccccccc' + + if(wanted[1]) wanted[1].path = wanted[1].path.replace('fixtures/', '').replace('//', '/') + if(wanted[1].path == '') wanted[1].path = '/' + if(wanted[2] && wanted[2].path) wanted[2].path = wanted[2].path.replace('fixtures', '').replace(/^\//, '') + + wanted[1].linkpath = wanted[1].linkpath.replace('fixtures/', '') + } + + if (ev !== wanted[0] || e.path !== wanted[1].path) { + console.error("wanted", wanted) + console.error([ev, e.props]) + e.on("end", function () { + console.error(e.fields) + throw "break" + }) + } + + + t.has(e.props, wanted[1], "properties "+wanted[1].path) + if (wanted[2]) { + e.on("end", function () { + if (!e.fields) { + t.ok(e.fields, "should get fields") + } else { + t.has(e.fields, wanted[2], "should get expected fields") + } + }) + } + }) + + reader.pipe(pack) + + writer.on("close", function () { + t.equal(entry, entries.length, "should get all expected entries") + t.pass("it finished") + t.end() + }) + +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/parse.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/parse.js new file mode 100644 index 0000000..f765a50 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/parse.js @@ -0,0 +1,359 @@ +var tap = require("tap") + , tar = require("../tar.js") + , fs = require("fs") + , path = require("path") + , file = path.resolve(__dirname, "fixtures/c.tar") + , index = 0 + + , expect = +[ [ 'entry', + { path: 'c.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 513, + mtime: new Date('Wed, 26 Oct 2011 01:10:58 GMT'), + cksum: 5422, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'entry', + { path: 'cc.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 513, + mtime: new Date('Wed, 26 Oct 2011 01:11:02 GMT'), + cksum: 5525, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'entry', + { path: 'r/e/a/l/l/y/-/d/e/e/p/-/f/o/l/d/e/r/-/p/a/t/h/cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 100, + mtime: new Date('Thu, 27 Oct 2011 03:43:23 GMT'), + cksum: 18124, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'entry', + { path: 'Ω.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 2, + mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + cksum: 5695, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/Ω.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 120, + mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + cksum: 6702, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: 'Ω.txt', + ctime: 1319737909, + atime: 1319739061, + dev: 234881026, + ino: 51693379, + nlink: 1 } ], + [ 'entry', + { path: 'Ω.txt', + mode: 420, + uid: 24561, + gid: 20, + size: 2, + mtime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + cksum: 5695, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Thu, 27 Oct 2011 17:51:49 GMT'), + atime: new Date('Thu, 27 Oct 2011 18:11:01 GMT'), + dev: 234881026, + ino: 51693379, + nlink: 1 }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 353, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 14488, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + ctime: 1319686868, + atime: 1319741254, + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 1 } ], + [ 'entry', + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 200, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 14570, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + atime: new Date('Thu, 27 Oct 2011 18:47:34 GMT'), + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 1 }, + undefined ], + [ 'longPath', + { path: '././@LongLink', + mode: 0, + uid: 0, + gid: 0, + size: 201, + mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), + cksum: 4976, + type: 'L', + linkpath: '', + ustar: false }, + '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ], + [ 'entry', + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 1000, + gid: 1000, + size: 201, + mtime: new Date('Thu, 27 Oct 2011 22:21:50 GMT'), + cksum: 14086, + type: '0', + linkpath: '', + ustar: false }, + undefined ], + [ 'longLinkpath', + { path: '././@LongLink', + mode: 0, + uid: 0, + gid: 0, + size: 201, + mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), + cksum: 4975, + type: 'K', + linkpath: '', + ustar: false }, + '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc' ], + [ 'longPath', + { path: '././@LongLink', + mode: 0, + uid: 0, + gid: 0, + size: 201, + mtime: new Date('Thu, 01 Jan 1970 00:00:00 GMT'), + cksum: 4976, + type: 'L', + linkpath: '', + ustar: false }, + '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL' ], + [ 'entry', + { path: '200LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL', + mode: 511, + uid: 1000, + gid: 1000, + size: 0, + mtime: new Date('Fri, 28 Oct 2011 23:05:17 GMT'), + cksum: 21603, + type: '2', + linkpath: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + ustar: false }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/200-hard', + mode: 420, + uid: 24561, + gid: 20, + size: 143, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 6533, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { ctime: 1320617144, + atime: 1320617232, + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 } ], + [ 'entry', + { path: '200-hard', + mode: 420, + uid: 24561, + gid: 20, + size: 200, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 5526, + type: '0', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'), + atime: new Date('Sun, 06 Nov 2011 22:07:12 GMT'), + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 }, + undefined ], + [ 'extendedHeader', + { path: 'PaxHeader/200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 353, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 14488, + type: 'x', + linkpath: '', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '' }, + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + ctime: 1320617144, + atime: 1320617406, + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 } ], + [ 'entry', + { path: '200ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', + mode: 420, + uid: 24561, + gid: 20, + size: 0, + mtime: new Date('Thu, 27 Oct 2011 03:41:08 GMT'), + cksum: 15173, + type: '1', + linkpath: '200-hard', + ustar: 'ustar\0', + ustarver: '00', + uname: 'isaacs', + gname: 'staff', + devmaj: 0, + devmin: 0, + fill: '', + ctime: new Date('Sun, 06 Nov 2011 22:05:44 GMT'), + atime: new Date('Sun, 06 Nov 2011 22:10:06 GMT'), + 'LIBARCHIVE.creationtime': '1319686852', + dev: 234881026, + ino: 51681874, + nlink: 2 }, + undefined ] ] + + +tap.test("parser test", function (t) { + var parser = tar.Parse() + + parser.on("end", function () { + t.equal(index, expect.length, "saw all expected events") + t.end() + }) + + fs.createReadStream(file) + .pipe(parser) + .on("*", function (ev, entry) { + var wanted = expect[index] + if (!wanted) { + return t.fail("Unexpected event: " + ev) + } + var result = [ev, entry.props] + entry.on("end", function () { + result.push(entry.fields || entry.body) + + t.equal(ev, wanted[0], index + " event type") + t.equivalent(entry.props, wanted[1], wanted[1].path + " entry properties") + if (wanted[2]) { + t.equivalent(result[2], wanted[2], "metadata values") + } + index ++ + }) + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/zz-cleanup.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/zz-cleanup.js new file mode 100644 index 0000000..a00ff7f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/node_modules/tar/test/zz-cleanup.js @@ -0,0 +1,20 @@ +// clean up the fixtures + +var tap = require("tap") +, rimraf = require("rimraf") +, test = tap.test +, path = require("path") + +test("clean fixtures", function (t) { + rimraf(path.resolve(__dirname, "fixtures"), function (er) { + t.ifError(er, "rimraf ./fixtures/") + t.end() + }) +}) + +test("clean tmp", function (t) { + rimraf(path.resolve(__dirname, "tmp"), function (er) { + t.ifError(er, "rimraf ./tmp/") + t.end() + }) +}) diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/package.json new file mode 100644 index 0000000..46e0642 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/package.json @@ -0,0 +1,80 @@ +{ + "name": "node-pre-gyp", + "description": "Node.js native addon binary install tool", + "version": "0.6.4", + "keywords": [ + "native", + "addon", + "module", + "c", + "c++", + "bindings", + "binary" + ], + "license": "BSD", + "author": { + "name": "Dane Springmeyer", + "email": "dane@mapbox.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/mapbox/node-pre-gyp.git" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp.js" + }, + "main": "./lib/node-pre-gyp.js", + "dependencies": { + "mkdirp": "~0.5.0", + "nopt": "~3.0.1", + "npmlog": "~1.2.0", + "rc": "~1.0.1", + "request": "2.x", + "rimraf": "~2.3.2", + "semver": "~4.3.3", + "tar": "~2.1.0", + "tar-pack": "~2.0.0" + }, + "devDependencies": { + "aws-sdk": "*", + "mocha": "2.x", + "jshint": "^2.7.0" + }, + "jshintConfig": { + "node": true, + "globalstrict": true, + "undef": true, + "unused": true, + "noarg": true, + "mocha": true + }, + "engineStrict": true, + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "update-crosswalk": "node scripts/abi_crosswalk.js", + "test": "jshint lib lib/util scripts bin/node-pre-gyp.js && mocha" + }, + "readme": "# node-pre-gyp\n\n#### node-pre-gyp makes it easy to publish and install Node.js C++ addons from binaries\n\n[![NPM](https://nodei.co/npm/node-pre-gyp.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-pre-gyp/)\n\n[![Build Status](https://api.travis-ci.org/mapbox/node-pre-gyp.svg)](https://travis-ci.org/mapbox/node-pre-gyp)\n[![Build status](https://ci.appveyor.com/api/projects/status/3nxewb425y83c0gv)](https://ci.appveyor.com/project/Mapbox/node-pre-gyp)\n[![Dependencies](https://david-dm.org/mapbox/node-pre-gyp.svg)](https://david-dm.org/mapbox/node-pre-gyp)\n\n`node-pre-gyp` stands between [npm](https://github.com/npm/npm) and [node-gyp](https://github.com/Tootallnate/node-gyp) and offers a cross-platform method of binary deployment.\n\n### Features\n\n - A command line tool called `node-pre-gyp` that can install your package's c++ module from a binary.\n - A variety of developer targeted commands for packaging, testing, and publishing binaries.\n - A Javascript module that can dynamically require your installed binary: `require('node-pre-gyp').find`\n\nFor a hello world example of a module packaged with `node-pre-gyp` see and [the wiki ](https://github.com/mapbox/node-pre-gyp/wiki/Modules-using-node-pre-gyp) for real world examples.\n\n## Credits\n\n - The module is modeled after [node-gyp](https://github.com/Tootallnate/node-gyp) by [@Tootallnate](https://github.com/Tootallnate)\n - Motivation for initial development came from [@ErisDS](https://github.com/ErisDS) and the [Ghost Project](https://github.com/TryGhost/Ghost).\n - Development is sponsored by [Mapbox](https://www.mapbox.com/)\n\n## FAQ\n\nSee the [Frequently Ask Questions](https://github.com/mapbox/node-pre-gyp/wiki/FAQ).\n\n## Depends\n\n - Node.js 0.12.x -> 0.8.x\n\n## Install\n\n`node-pre-gyp` is designed to be installed as a local dependency of your Node.js C++ addon and accessed like:\n\n ./node_modules/.bin/node-pre-gyp --help\n\nBut you can also install it globally:\n\n npm install node-pre-gyp -g\n\n## Usage\n\n### Commands\n\nView all possible commands:\n\n node-pre-gyp --help\n\n- clean - Remove the entire folder containing the compiled .node module\n- install - Install pre-built binary for module\n- reinstall - Run \"clean\" and \"install\" at once\n- build - Compile the module by dispatching to node-gyp or nw-gyp\n- rebuild - Run \"clean\" and \"build\" at once\n- package - Pack binary into tarball\n- testpackage - Test that the staged package is valid\n- publish - Publish pre-built binary\n- unpublish - Unpublish pre-built binary\n- info - Fetch info on published binaries\n\nYou can also chain commands:\n\n node-pre-gyp clean build unpublish publish info\n\n### Options\n\nOptions include:\n\n - `-C/--directory`: run the command in this directory\n - `--build-from-source`: build from source instead of using pre-built binary\n - `--runtime=node-webkit`: customize the runtime: `node` and `node-webkit` are the valid options\n - `--fallback-to-build`: fallback to building from source if pre-built binary is not available\n - `--target=0.10.25`: Pass the target node or node-webkit version to compile against\n - `--target_arch=ia32`: Pass the target arch and override the host `arch`. Valid values are 'ia32','x64', or `arm`.\n - `--target_platform=win32`: Pass the target platform and override the host `platform`. Valid values are `linux`, `darwin`, `win32`, `sunos`, `freebsd`, `openbsd`, and `aix`.\n\nBoth `--build-from-source` and `--fallback-to-build` can be passed alone or they can provide values. You can pass `--fallback-to-build=false` to override the option as declared in package.json. In addition to being able to pass `--build-from-source` you can also pass `--build-from-source=myapp` where `myapp` is the name of your module.\n\nFor example: `npm install --build-from-source=myapp`. This is useful if:\n\n - `myapp` is referenced in the package.json of a larger app and therefore `myapp` is being installed as a dependent with `npm install`.\n - The larger app also depends on other modules installed with `node-pre-gyp`\n - You only want to trigger a source compile for `myapp` and the other modules.\n\n### Configuring\n\nThis is a guide to configuring your module to use node-pre-gyp.\n\n#### 1) Add new entries to your `package.json`\n\n - Add `node-pre-gyp` to `bundledDependencies`\n - Add `aws-sdk` as a `devDependency`\n - Add a custom `install` script\n - Declare a `binary` object\n\nThis looks like:\n\n```js\n \"dependencies\" : {\n \"node-pre-gyp\": \"0.5.x\"\n },\n \"bundledDependencies\":[\"node-pre-gyp\"],\n \"devDependencies\": {\n \"aws-sdk\": \"~2.0.0-rc.15\"\n }\n \"scripts\": {\n \"install\": \"node-pre-gyp install --fallback-to-build\",\n },\n \"binary\": {\n \"module_name\": \"your_module\",\n \"module_path\": \"./lib/binding/\",\n \"host\": \"https://your_module.s3-us-west-1.amazonaws.com\"\n }\n```\n\nFor a full example see [node-addon-examples's package.json](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/package.json#L11-L22).\n\n##### The `binary` object has three required properties\n\n###### module_name\n\nThe name of your native node module. This value must:\n\n - Match the name passed to [the NODE_MODULE macro](http://nodejs.org/api/addons.html#addons_hello_world)\n - Must be a valid C variable name (e.g. it cannot contain `-`)\n - Should not include the `.node` extension.\n\n###### module_path\n\nThe location your native module is placed after a build. This should be an empty directory without other Javascript files. This entire directory will be packaged in the binary tarball. When installing from a remote package this directory will be overwritten with the contents of the tarball.\n\nNote: This property supports variables based on [Versioning](#versioning).\n\n###### host\n\nA url to the remote location where you've published tarball binaries (must be `https` not `http`).\n\nIt is highly recommended that you use Amazon S3. The reasons are:\n\n - Various node-pre-gyp commands like `publish` and `info` only work with an S3 host.\n - S3 is a very solid hosting platform for distributing large files, even [Github recommends using it instead of github](https://help.github.com/articles/distributing-large-binaries).\n - We provide detail documentation for using [S3 hosting](#s3-hosting) with node-pre-gyp.\n\nWhy then not require S3? Because while some applications using node-pre-gyp need to distribute binaries as large as 20-30 MB, others might have very small binaries and might wish to store them in a github repo. This is not recommended, but if an author really wants to host in a non-s3 location then it should be possible.\n\n##### The `binary` object has two optional properties\n\n###### remote_path\n\nIt **is recommended** that you customize this property. This is an extra path to use for publishing and finding remote tarballs. The default value for `remote_path` is `\"\"` meaning that if you do not provide it then all packages will be published at the base of the `host`. It is recommended to provide a value like `./{name}/v{version}` to help organize remote packages in the case that you choose to publish multiple node addons to the same `host`.\n\nNote: This property supports variables based on [Versioning](#versioning).\n\n###### package_name\n\nIt is **not recommended** to override this property unless you are also overriding the `remote_path`. This is the versioned name of the remote tarball containing the binary `.node` module and any supporting files you've placed inside the `module_path` directory. Unless you specify `package_name` in your `package.json` then it defaults to `{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz` which allows your binary to work across node versions, platforms, and architectures. If you are using `remote_path` that is also versioned by `./{module_name}/v{version}` then you could remove these variables from the `package_name` and just use: `{node_abi}-{platform}-{arch}.tar.gz`. Then your remote tarball will be looked up at, for example, `https://example.com/your-module/v0.1.0/node-v11-linux-x64.tar.gz`.\n\nAvoiding the version of your module in the `package_name` and instead only embedding in a directory name can be useful when you want to make a quick tag of your module that does not change any C++ code. In this case you can just copy binaries to the new version behind the scenes like:\n\n```sh\naws s3 sync --acl public-read s3://mapbox-node-binary/sqlite3/v3.0.3/ s3://mapbox-node-binary/sqlite3/v3.0.4/\n```\n\nNote: This property supports variables based on [Versioning](#versioning).\n\n#### 2) Add a new target to binding.gyp\n\n`node-pre-gyp` calls out to `node-gyp` to compile the module and passes variables along like [module_name](#module_name) and [module_path](#module_path).\n\nA new target must be added to `binding.gyp` that moves the compiled `.node` module from `./build/Release/module_name.node` into the directory specified by `module_path`.\n\nAdd a target like this at the end of your `targets` list:\n\n```js\n {\n \"target_name\": \"action_after_build\",\n \"type\": \"none\",\n \"dependencies\": [ \"<(module_name)\" ],\n \"copies\": [\n {\n \"files\": [ \"<(PRODUCT_DIR)/<(module_name).node\" ],\n \"destination\": \"<(module_path)\"\n }\n ]\n }\n```\n\nFor a full example see [node-addon-example's binding.gyp](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/binding.gyp).\n\n#### 3) Dynamically require your `.node`\n\nInside the main js file that requires your addon module you are likely currently doing:\n\n```js\nvar binding = require('../build/Release/binding.node');\n```\n\nor:\n\n```js\nvar bindings = require('./bindings')\n```\n\nChange those lines to:\n\n```js\nvar binary = require('node-pre-gyp');\nvar path = require('path');\nvar binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));\nvar binding = require(binding_path);\n```\n\nFor a full example see [node-addon-example's index.js](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/index.js#L1-L4)\n\n#### 4) Build and package your app\n\nNow build your module from source:\n\n npm install --build-from-source\n\nThe `--build-from-source` tells `node-pre-gyp` to not look for a remote package and instead dispatch to node-gyp to build.\n\nNow `node-pre-gyp` should now also be installed as a local dependency so the command line tool it offers can be found at `./node_modules/.bin/node-pre-gyp`.\n\n#### 5) Test\n\nNow `npm test` should work just as it did before.\n\n#### 6) Publish the tarball\n\nThen package your app:\n\n ./node_modules/.bin/node-pre-gyp package\n\nOnce packaged, now you can publish:\n\n ./node_modules/.bin/node-pre-gyp publish\n\nCurrently the `publish` command pushes your binary to S3. This requires:\n\n - You have installed `aws-sdk` with `npm install aws-sdk`\n - You have created a bucket already.\n - The `host` points to an S3 http or https endpoint.\n - You have configured node-pre-gyp to read your S3 credentials (see [S3 hosting](#s3-hosting) for details).\n\nYou can also host your binaries elsewhere. To do this requires:\n\n - You manually publish the binary created by the `package` command to an `https` endpoint\n - Ensure that the `host` value points to your custom `https` endpoint.\n\n#### 7) Automate builds\n\nNow you need to publish builds for all the platforms and node versions you wish to support. This is best automated.\n\n - See [Appveyor Automation](#appveyor-automation) for how to auto-publish builds on Windows.\n - See [Travis Automation](#travis-automation) for how to auto-publish builds on OS X and Linux.\n\n#### 8) You're done!\n\nNow publish your module to the npm registry. Users will now be able to install your module from a binary. \n\nWhat will happen is this:\n\n1. `npm install ` will pull from the npm registry\n2. npm will run the `install` script which will call out to `node-pre-gyp`\n3. `node-pre-gyp` will fetch the binary `.node` module and unpack in the right place\n4. Assuming that all worked, you are done\n\nIf a a binary was not available for a given platform and `--fallback-to-build` was used then `node-gyp rebuild` will be called to try to source compile the module.\n\n## S3 Hosting\n\nYou can host wherever you choose but S3 is cheap, `node-pre-gyp publish` expects it, and S3 can be integrated well with [travis.ci](http://travis-ci.org) to automate builds for OS X and Ubuntu. Here is an approach to do this:\n\nFirst, get setup locally and test the workflow:\n\n#### 1) Create an S3 bucket\n\nAnd have your **key** and **secret key** ready for writing to the bucket.\n\nIt is recommended to create a IAM user with a policy that only gives permissions to the specific bucket you plan to publish to. This can be done in the [IAM console](https://console.aws.amazon.com/iam/) by: 1) adding a new user, 2) choosing `Attach User Policy`, 3) Using the `Policy Generator`, 4) selecting `Amazon S3` for the service, 5) adding the actions: `DeleteObject`, `GetObject`, `GetObjectAcl`, `ListBucket`, `PutObject`, `PutObjectAcl`, 6) adding an ARN of `arn:aws:s3:::bucket/*` (replacing `bucket` with your bucket name), and finally 7) clicking `Add Statement` and saving the policy. It should generate a policy like:\n\n```js\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"Stmt1394587197000\",\n \"Effect\": \"Allow\",\n \"Action\": [\n \"s3:DeleteObject\",\n \"s3:GetObject\",\n \"s3:GetObjectAcl\",\n \"s3:ListBucket\",\n \"s3:PutObject\",\n \"s3:PutObjectAcl\"\n ],\n \"Resource\": [\n \"arn:aws:s3:::node-pre-gyp-tests/*\"\n ]\n }\n ]\n}\n```\n\n#### 2) Install node-pre-gyp\n\nEither install it globally:\n\n npm install node-pre-gyp -g\n\nOr put the local version on your PATH\n\n export PATH=`pwd`/node_modules/.bin/:$PATH\n\n#### 3) Configure AWS credentials\n\nThere are several ways to do this.\n\nYou can use any of the methods described at http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html.\n\nOr you can create a `~/.node_pre_gyprc`\n\nOr pass options in any way supported by [RC](https://github.com/dominictarr/rc#standards)\n\nA `~/.node_pre_gyprc` looks like:\n\n```js\n{\n \"accessKeyId\": \"xxx\",\n \"secretAccessKey\": \"xxx\"\n}\n```\n\nAnother way is to use your environment:\n\n export node_pre_gyp_accessKeyId=xxx\n export node_pre_gyp_secretAccessKey=xxx\n\nYou may also need to specify the `region` if it is not explicit in the `host` value you use. The `bucket` can also be specified but it is optional because `node-pre-gyp` will detect it from the `host` value.\n\n#### 4) Package and publish your build\n\nInstall the `aws-sdk`:\n\n npm install aws-sdk\n\nThen publish:\n\n node-pre-gyp package publish\n\nNote: if you hit an error like `Hostname/IP doesn't match certificate's altnames` it may mean that you need to provide the `region` option in your config.\n\n## Appveyor Automation\n\n[Appveyor](http://www.appveyor.com/) can build binaries and publish the results per commit and supports:\n\n - Windows Visual Studio 2013 and related compilers\n - Both 64 bit (x64) and 32 bit (x86) build configurations\n - Multiple Node.js versions\n\nFor an example of doing this see [node-sqlite3's appveyor.yml](https://github.com/mapbox/node-sqlite3/blob/master/appveyor.yml).\n\nBelow is a guide to getting set up:\n\n#### 1) Create a free Appveyor account\n\nGo to https://ci.appveyor.com/signup/free and sign in with your github account.\n\n#### 2) Create a new project\n\nGo to https://ci.appveyor.com/projects/new and select the github repo for your module\n\n#### 3) Add appveyor.yml and push it\n\nOnce you have committed an `appveyor.yml` ([appveyor.yml reference](http://www.appveyor.com/docs/appveyor-yml)) to your github repo and pushed it appveyor should automatically start building your project.\n\n#### 4) Create secure variables\n\nEncrypt your S3 AWS keys by going to and hitting the `encrypt` button.\n\nThen paste the result into your `appveyor.yml`\n\n```yml\nenvironment:\n node_pre_gyp_accessKeyId:\n secure: Dn9HKdLNYvDgPdQOzRq/DqZ/MPhjknRHB1o+/lVU8MA=\n node_pre_gyp_secretAccessKey:\n secure: W1rwNoSnOku1r+28gnoufO8UA8iWADmL1LiiwH9IOkIVhDTNGdGPJqAlLjNqwLnL\n```\n\nNOTE: keys are per account but not per repo (this is difference than travis where keys are per repo but not related to the account used to encrypt them).\n\n#### 5) Hook up publishing\n\nJust put `node-pre-gyp package publish` in your `appveyor.yml` after `npm install`.\n\n#### 6) Publish when you want\n\nYou might wish to publish binaries only on a specific commit. To do this you could borrow from the [travis.ci idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`:\n\n SET CM=%APPVEYOR_REPO_COMMIT_MESSAGE%\n if not \"%CM%\" == \"%CM:[publish binary]=%\" node-pre-gyp --msvs_version=2013 publish\n\nIf your commit message contains special characters (e.g. `&`) this method might fail. An alternative is to use PowerShell, which gives you additional possibilities, like ignoring case by using `ToLower()`:\n\n ps: if($env:APPVEYOR_REPO_COMMIT_MESSAGE.ToLower().Contains('[publish binary]')) { node-pre-gyp --msvs_version=2013 publish }\n\nRemember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on travis see http://about.travis-ci.org/docs/user/deployment/npm/\n\n\n## Travis Automation\n\n[Travis](https://travis-ci.org/) can push to S3 after a successful build and supports both:\n\n - Ubuntu Precise and OS X (64 bit)\n - Multiple Node.js versions\n\nFor an example of doing this see [node-add-example's .travis.yml](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/.travis.yml).\n\nNote: if you need 32 bit binaries, this can be done from a 64 bit travis machine. See [the node-sqlite3 scripts for an example of doing this](https://github.com/mapbox/node-sqlite3/blob/bae122aa6a2b8a45f6b717fab24e207740e32b5d/scripts/build_against_node.sh#L54-L74).\n\nBelow is a guide to getting set up:\n\n#### 1) Install the travis gem\n\n gem install travis\n\n#### 2) Create secure variables\n\nMake sure you run this command from within the directory of your module.\n\nUse `travis-encrypt` like:\n\n travis encrypt node_pre_gyp_accessKeyId=${node_pre_gyp_accessKeyId}\n travis encrypt node_pre_gyp_secretAccessKey=${node_pre_gyp_secretAccessKey}\n\nThen put those values in your `.travis.yml` like:\n\n```yaml\nenv:\n global:\n - secure: F+sEL/v56CzHqmCSSES4pEyC9NeQlkoR0Gs/ZuZxX1ytrj8SKtp3MKqBj7zhIclSdXBz4Ev966Da5ctmcTd410p0b240MV6BVOkLUtkjZJyErMBOkeb8n8yVfSoeMx8RiIhBmIvEn+rlQq+bSFis61/JkE9rxsjkGRZi14hHr4M=\n - secure: o2nkUQIiABD139XS6L8pxq3XO5gch27hvm/gOdV+dzNKc/s2KomVPWcOyXNxtJGhtecAkABzaW8KHDDi5QL1kNEFx6BxFVMLO8rjFPsMVaBG9Ks6JiDQkkmrGNcnVdxI/6EKTLHTH5WLsz8+J7caDBzvKbEfTux5EamEhxIWgrI=\n```\n\nMore details on travis encryption at http://about.travis-ci.org/docs/user/encryption-keys/.\n\n#### 3) Hook up publishing\n\nJust put `node-pre-gyp package publish` in your `.travis.yml` after `npm install`.\n\n##### OS X publishing\n\nIf you want binaries for OS X in addition to linux you have two options:\n\n1) [Enabling multi-OS](#enabling-multi-os)\n\n2) [Using `language: objective-c` in a git branch](#using-language-objective-c).\n\n##### Enabling multi-OS\n\nThis requires emailing a request to `support@travis-ci.com` for each repo you wish to have enabled. More details at .\n\nNext you need to tweak the `.travis.yml` to ensure it is cross platform.\n\nUse a configuration like:\n\n```yml\n\nlanguage: cpp\n\nos:\n- linux\n- osx\n\nenv:\n matrix:\n - NODE_VERSION=\"0.10\"\n - NODE_VERSION=\"0.11.14\"\n\nbefore_install:\n- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm\n- source ~/.nvm/nvm.sh\n- nvm install $NODE_VERSION\n- nvm use $NODE_VERSION\n```\n\nSee [Travis OS X Gochas](#travis-os-x-gochas) for why we replace `language: node_js` and `node_js:` sections with `language: cpp` and a custom matrix.\n\n\nAlso create platform specific sections for any deps that need install. For example if you need libpng:\n\n```yml\n- if [ $(uname -s) == 'Linux' ]; then apt-get install libpng-dev; fi;\n- if [ $(uname -s) == 'Darwin' ]; then brew install libpng; fi;\n```\n\nFor detailed multi-OS examples see [node-mapnik](https://github.com/mapnik/node-mapnik/blob/master/.travis.yml) and [node-sqlite3](https://github.com/mapbox/node-sqlite3/blob/master/.travis.yml).\n\n##### Using `language: objective-c`\n\nIf your repo does not have multi-OS enabled, an alternative method for building for OS X is to tweak your `.travis.yml` to use:\n\n```yml\nlanguage: objective-c\n```\n\nKeep that change in a different git branch and sync that when you want binaries published.\n\nNext learn about a few [Travis OS X Gochas](#travis-os-x-gochas).\n\n##### Travis OS X Gochas\n\nFirst, unlike the Travis linux machines the OS X machines do not put `node-pre-gyp` on PATH by default. So to you will need to:\n\n```sh\nexport PATH=$(pwd)/node_modules/.bin:${PATH}\n```\n\nSecond, the OS X machines doe not support using a matrix for installing node.js different versions. So you need to bootstrap the installation of node.js in a cross platform way. \n\nBy doing:\n\n```yml\nenv:\n matrix:\n - NODE_VERSION=\"0.10\"\n - NODE_VERSION=\"0.11.14\"\n\nbefore_install:\n - rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm\n - source ~/.nvm/nvm.sh\n - nvm install $NODE_VERSION\n - nvm use $NODE_VERSION\n```\n\nYou can easily recreate the previous behavior of this matrix:\n\n```yml\nnode_js:\n - \"0.10\"\n - \"0.11.14\"\n```\n\n#### 4) Publish when you want\n\nYou might wish to publish binaries only on a specific commit. To do this you could borrow from the [travis.ci idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`:\n\n COMMIT_MESSAGE=$(git show -s --format=%B $TRAVIS_COMMIT | tr -d '\\n')\n if [[ ${COMMIT_MESSAGE} =~ \"[publish binary]\" ]]; then node-pre-gyp publish; fi;\n\nThen you can trigger new binaries to be built like:\n\n git commit -a -m \"[publish binary]\"\n\nOr, if you don't have any changes to make simply run:\n\n git commit --allow-empty -m \"[publish binary]\"\n\nRemember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on travis see http://about.travis-ci.org/docs/user/deployment/npm/\n\n# Versioning\n\nThe `binary` properties of `module_path`, `remote_path`, and `package_name` support variable substitution. The strings are evaluated by `node-pre-gyp` depending on your system and any custom build flags you passed.\n\n - `node_abi`: The node C++ `ABI` number. This value is available in Javascript as `process.versions.modules` as of [`>= v0.10.4 >= v0.11.7`](https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e) and in C++ as the `NODE_MODULE_VERSION` define much earlier. For versions of Node before this was available we fallback to the V8 major and minor version.\n - `platform` matches node's `process.platform` like `linux`, `darwin`, and `win32` unless the user passed the `--target_platform` option to override.\n - `arch` matches node's `process.arch` like `x64` or `ia32` unless the user passes the `--target_arch` option to override.\n - `configuration` - Either 'Release' or 'Debug' depending on if `--debug` is passed during the build.\n - `module_name` - the `binary.module_name` attribute from `package.json`.\n - `version` - the semver `version` value for your module from `package.json` (NOTE: ignores the `semver.build` property).\n - `major`, `minor`, `patch`, and `prelease` match the individual semver values for your module's `version`\n - `build` - the sevmer `build` value. For example it would be `this.that` if your package.json `version` was `v1.0.0+this.that`\n - `prerelease` - the semver `prerelease` value. For example it would be `alpha.beta` if your package.json `version` was `v1.0.0-alpha.beta`\n\n\nThe options are visible in the code at \n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/mapbox/node-pre-gyp/issues" + }, + "homepage": "https://github.com/mapbox/node-pre-gyp#readme", + "bundleDependencies": [ + "nopt", + "npmlog", + "request", + "semver", + "tar", + "tar-pack", + "mkdirp", + "rc", + "rimraf" + ], + "_id": "node-pre-gyp@0.6.4", + "_shasum": "219d8a1f3cb191a0f3d6cf342a50efba4fbce841", + "_resolved": "https://github.com/mongodb-js/node-pre-gyp/archive/v0.6.5-appveyor.tar.gz", + "_from": "https://github.com/mongodb-js/node-pre-gyp/archive/v0.6.5-appveyor.tar.gz" +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/abi_crosswalk.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/abi_crosswalk.js new file mode 100644 index 0000000..a5a106f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/abi_crosswalk.js @@ -0,0 +1,160 @@ +"use strict"; + +var https = require("https"); +var url = require('url'); +var semver = require('semver'); +var fs = require('fs'); +/* + +usage: + +node scripts/abi_crosswalk.js + +*/ + +var cross = {}; + +var template = 'https://raw.githubusercontent.com/joyent/node/v{VERSION}/src/'; +var v8template = 'https://raw.githubusercontent.com/joyent/node/v{VERSION}/deps/v8/src/version.cc'; + +var sortObjectByKey = function(obj){ + var keys = []; + var sorted_obj = {}; + for(var key in obj){ + if(obj.hasOwnProperty(key)){ + keys.push(key); + } + } + // sort keys + keys.sort(function(a,b) { + if (semver.gt(a, b)) { + return 1; + } + return -1; + }); + var len = keys.length; + + for (i = 0; i < len; i++) + { + key = keys[i]; + sorted_obj[key] = obj[key]; + } + return sorted_obj; +}; + +function get(ver,callback) { + var header = 'node.h'; + if (semver.gt(ver, 'v0.11.4')) { + // https://github.com/joyent/node/commit/44ed42bd971d58b294222d983cfe2908e021fb5d#src/node_version.h + header = 'node_version.h'; + } + var path = template.replace('{VERSION}',ver) + header; + var uri = url.parse(path); + https.get(uri, function(res) { + if (res.statusCode != 200 ) { + throw new Error("server returned " + res.statusCode + ' for: ' + path); + } + res.setEncoding('utf8'); + var body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end',function(err) { + if (err) throw err; + var term = 'define NODE_MODULE_VERSION'; + var idx = body.indexOf(term); + var following = body.slice(idx); + var end = following.indexOf('\n'); + var value = following.slice(term.length,end).trim(); + if (value[0] === '(' && value[value.length-1] == ')') { + value = value.slice(1,value.length-1); + } else if (value.indexOf(' ') > -1) { + value = value.slice(0,value.indexOf(' ')); + } + var int_val = +value; + if (int_val !== undefined) { + // TODO - if val is 1 then we need to get the v8 version from + // https://github.com/joyent/node/blob/master/deps/v8/src/version.cc + var v8path = v8template.replace('{VERSION}',ver); + var v8uri = url.parse(v8path); + https.get(v8uri, function(res) { + if (res.statusCode != 200) { + throw new Error("server returned " + res.statusCode + ' for: ' + path); + } + res.setEncoding('utf8'); + var body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end',function(err) { + if (err) throw err; + var term = 'define MAJOR_VERSION'; + var idx = body.indexOf(term); + var following = body.slice(idx); + var end = following.indexOf('\n'); + var major = following.slice(term.length,end).trim(); + var term1 = 'define MINOR_VERSION'; + var idx1 = body.indexOf(term1); + var following1 = body.slice(idx1); + var end1 = following1.indexOf('\n'); + var minor = following1.slice(term1.length,end1).trim(); + var v8_version = major+'.'+minor; + return callback(null,ver,int_val,v8_version); + }); + }); + } + }); + }); +} + +process.on('exit', function(err) { + if (err) throw err; + fs.writeFileSync('./lib/util/abi_crosswalk.json',JSON.stringify(sortObjectByKey(cross),null,2)); +}); + +// These need to be manually read and updated based on http://nodejs.org/dist +// because I'm not keen to parse the html and in the http://nodejs.org/dist/npm-versions.txt worked well. +// but joyent has stopped updating this https://github.com/joyent/node/issues/7409 +var update_node = true; +if (update_node) { + var lines = []; + for (var i=0;i<=28;++i) { + lines.push('0.8.'+i); + } + for (var i=0;i<=36;++i) { + lines.push('0.10.'+i); + } + for (var i=0;i<=16;++i) { + lines.push('0.11.'+i); + } + for (var i=0;i<=0;++i) { + lines.push('0.12.'+i); + } + lines.forEach(function(ver) { + get(ver,function(err,version,node_abi,v8_version) { + cross[version] = {node_abi:node_abi,v8:v8_version}; + }); + }); +} else { + cross = JSON.parse(fs.readFileSync('./lib/util/abi_crosswalk.json')); +} + +// IO.js +// thanks to rvagg, this is so simple +https.get('https://iojs.org/download//release/index.json', function(res) { + if (res.statusCode != 200 ) { + throw new Error("server returned " + res.statusCode + ' for iojs.org'); + } + res.setEncoding('utf8'); + var body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end',function(err) { + if (err) throw err; + var releases = JSON.parse(body); + releases.forEach(function(release) { + cross[release.version.replace('v','')] = {node_abi:+release.modules,v8:release.v8.split('.').slice(0,2).join('.')}; + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/clear_bucket.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/clear_bucket.js new file mode 100644 index 0000000..3cb9513 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/clear_bucket.js @@ -0,0 +1,35 @@ +"use strict"; + +var fs = require('fs'); +var versioning = require('../lib/util/versioning.js'); +var s3_setup = require('../lib/util/s3_setup.js'); +var config = require('rc')("node_pre_gyp",{acl:"public-read"}); + +if(!config.accessKeyId || !config.secretAccessKey) { + throw new Error("Unknown S3 `accessKeyId` and `secretAccessKey`"); +} else { + var AWS = require("aws-sdk"); + var package_json = JSON.parse(fs.readFileSync('./test/app1/package.json')); + var opts = versioning.evaluate(package_json, {}); + s3_setup.detect(opts.hosted_path,config); + AWS.config.update(config); + var s3 = new AWS.S3(); + var s3_opts = { Bucket: config.bucket, + Prefix: config.prefix + }; + s3.listObjects(s3_opts, function(err, meta){ + if (err) { + throw new Error('['+package_json.name+'] Not found: https://' + s3_opts.Bucket + '.s3.amazonaws.com/'+config.prefix); + } else { + meta.Contents.forEach(function(item) { + var s3_obj_opts = { Bucket: config.bucket, + Key: item.Key + }; + s3.deleteObject(s3_obj_opts, function(err) { + if (err) console.log(err); + console.log('deleted '+ item.Key); + }); + }); + } + }); +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/latest-by-abi.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/latest-by-abi.js new file mode 100644 index 0000000..494aa3c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/latest-by-abi.js @@ -0,0 +1,27 @@ +"use strict"; + +var semver = require('semver'); +var data = require('../lib/util/abi_crosswalk.json'); + +var targets = {}; +Object.keys(data).forEach(function(v) { + var o = data[v]; + var abi; + if (o.node_abi == 1) { + abi = 'v8-'+o.v8; + } else { + abi = 'node-v'+o.node_abi; + } + if (targets[abi] === undefined) { + targets[abi] = v; + } else { + var cur = targets[abi]; + if (semver.gt(v,cur)) { + targets[abi] = v; + } + } +}); + +Object.keys(targets).forEach(function(k) { + console.log(targets[k]); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test-node-webkit.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test-node-webkit.sh new file mode 100755 index 0000000..e2ef3b5 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test-node-webkit.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +set -u + +# put local copy of node-pre-gyp on NODE_PATH/PATH +export NODE_PATH=`pwd`/lib +export PATH=`pwd`/bin:$PATH + +BASE=$(pwd) + +export NODE_WEBKIT_VERSION="0.8.5" + +# TODO - consider using https://github.com/shama/nodewebkit to install node-webkit +if [[ `uname -s` == 'Darwin' ]]; then + if [[ ! -f node-webkit-v${NODE_WEBKIT_VERSION}-osx-ia32.zip ]]; then + wget https://s3.amazonaws.com/node-webkit/v${NODE_WEBKIT_VERSION}/node-webkit-v${NODE_WEBKIT_VERSION}-osx-ia32.zip + fi + if [[ ! -d node-webkit.app ]]; then + unzip node-webkit-v${NODE_WEBKIT_VERSION}-osx-ia32.zip + fi + export PATH=${BASE}/node-webkit.app/Contents/MacOS:${PATH} +else + # assume 64 bit linux + wget https://s3.amazonaws.com/node-webkit/v${NODE_WEBKIT_VERSION}/node-webkit-v${NODE_WEBKIT_VERSION}-linux-x64.tar.gz + tar xf node-webkit-v${NODE_WEBKIT_VERSION}-linux-x64.tar.gz + sudo apt-get install -y xvfb libasound2 libx11-6 libglib2.0-0 libgtk2.0-0 libatk1.0-0 libgdk-pixbuf2.0-0 libcairo2 libfreetype6 libfontconfig1 libxcomposite1 libasound2 libxdamage1 libxext6 libxfixes3 libnss3 libnspr4 libgconf-2-4 libexpat1 libdbus-1-3 libudev0 + # wget https://gist.githubusercontent.com/kez/2028715/raw/86f5084edb5cb0b9cdc1675ff310fad5e7579ee0/xvfb + # sudo mv xvfb /etc/init.d/xvfb + # sudo chmod 755 /etc/init.d/xvfb + # sudo update-rc.d xvfb defaults + # sudo /etc/init.d/xvfb start + export DISPLAY=:99.0; sh -e /etc/init.d/xvfb start; + export PATH=${BASE}/node-webkit-v0.8.5-linux-x64:${PATH} +fi + +# install nw-gyp +npm install nw-gyp +export PATH=${BASE}/node_modules/.bin:${PATH} + +cd test/app1 +node-pre-gyp clean build --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} +node-pre-gyp package --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} +node-pre-gyp clean --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} + +# now test publishing and installing from remote +if [[ "${node_pre_gyp_accessKeyId:-false}" != false ]] || [[ -f $HOME/.node_pre_gyprc ]] ; then + node-pre-gyp publish --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} + node-pre-gyp clean --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} + rm -rf build/ + rm -rf lib/binding/ + npm install --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} + # cleanup + node-pre-gyp unpublish --runtime=node-webkit --target=${NODE_WEBKIT_VERSION} +fi diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.bat b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.bat new file mode 100644 index 0000000..ce28e3e --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.bat @@ -0,0 +1,22 @@ +set BASE=%cd% +set NODE_PATH=%BASE%\lib +@rem put local copy of node-pre-gyp on PATH +set PATH=%BASE%\bin;%PATH% +call node-pre-gyp -C test/app1 clean +call node-pre-gyp -C test/app1 unpublish build package testpackage publish info +call node-pre-gyp -C test/app1 clean install +cd test/app1 +call npm test +cd %BASE% +call node-pre-gyp -C test/app2 unpublish build package testpackage publish info --custom_include_path=%BASE%\test\app2\include +cd test/app2 +call npm test +cd %BASE% +call node-pre-gyp -C test/app3 unpublish build package testpackage publish info +cd test/app3 +call npm test +cd %BASE% +call node-pre-gyp -C test/app4 unpublish build package testpackage publish info +cd test/app4 +call npm test +cd %BASE% \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.sh b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.sh new file mode 100755 index 0000000..7233242 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/scripts/test.sh @@ -0,0 +1,150 @@ +#!/bin/bash + +set -e -u +#set -x + +# put local copy of node-pre-gyp on NODE_PATH/PATH +export NODE_PATH=`pwd`/lib +export PATH=`pwd`/bin:$PATH + +BASE=$(pwd) + +function setup { + if [[ `node -v` =~ 'v0.10' ]] && [[ ! -d "./node_modules/nw-gyp" ]]; then + npm ls + fi + cd ${BASE} +} + +function teardown { + cd ${BASE} +} + +function MARK { + echo + echo "*** $1 ($2) ***" + echo +} + +function build_app { + WD=$( cd $BASE/test/$1 && pwd ) + + OPT_ARG="" + if [[ "${2:-false}" != false ]]; then + OPT_ARG=$2 + fi + + rm -rf ${WD}/lib/binding/* + rm -rf ${WD}/build/* + + MARK "A" $1 + # test install from binary with fallback + # run directly against node-pre-gyp + node-pre-gyp clean -C $WD + if [[ $1 == "app2" ]]; then + node-pre-gyp -C $WD install --fallback-to-build --custom_include_path=$WD/include $OPT_ARG + else + node-pre-gyp -C $WD install --fallback-to-build $OPT_ARG + fi + + # ensure the binary exists in the same spot the reveal command thinks it is + MODULE_PATH_DIR=$(node-pre-gyp -C $WD reveal module_path $OPT_ARG) + if [[ ! -d ${MODULE_PATH_DIR} ]]; then + echo "failed to locate expected module_path directory: $MODULE_PATH_DIR" + false + fi + + MODULE_FILE=$(node-pre-gyp -C $WD reveal module $OPT_ARG) + if [[ ! -f ${MODULE_FILE} ]]; then + echo "failed to locate expected module file: $MODULE_FILE" + false + fi + + # run npm commands from correct directory + cd $WD && npm test && cd $BASE + + if [[ "${AWS_ACCESS_KEY_ID:-false}" != false ]] || [[ "${node_pre_gyp_accessKeyId:-false}" != false ]] || [[ -f $HOME/.node_pre_gyprc ]] ; then + MARK "D" $1 + # it works, so now publish + node-pre-gyp -C $WD package testpackage unpublish publish $OPT_ARG + + # now test listing published binaries + CURRENT_ARCH=$(node -e "console.log(process.arch)") + CURRENT_PLATFORM=$(node -e "console.log(process.platform)") + BINARIES=$(node-pre-gyp -C $WD info --loglevel warn $OPT_ARG) + # now ensure that both the current arch and platform + # show up in the published listing + if test "${BINARIES#*$CURRENT_PLATFORM}" == "$BINARIES"; then + echo "failed to detect published binary for platform $CURRENT_PLATFORM ($BINARIES)" + false + else + echo "detected published $CURRENT_PLATFORM" + fi + if test "${BINARIES#*$CURRENT_ARCH}" == "$BINARIES"; then + echo "failed to detect published binary for arch $CURRENT_ARCH ($BINARIES)" + false + else + echo "detected published $CURRENT_ARCH" + fi + + MARK "E" $1 + # actually move into correct working + # directory now so we don't need -C + cd $WD + # now test installing via remote binary without fallback + node-pre-gyp clean $OPT_ARG + npm install --fallback-to-build=false $OPT_ARG + npm test + # for app1 also test in debug + if [[ $1 == "app2" ]]; then + node-pre-gyp clean $OPT_ARG + fi + else + MARK "B" $1 + echo "skipping publish" + MARK "C" $1 + echo "skipping install from published binary" + fi + + MARK "F" $1 + # actually move into correct working + # directory now so we don't need -C + cd $WD + # sabotage binaries and make sure they are rebuilt + for i in $(find . -name '*.node') ; do + echo 'bogus' > $i; + done + if [[ $1 == "app2" ]]; then + npm install --custom_include_path=$WD/include $OPT_ARG + else + npm install $OPT_ARG + fi + + MARK "G" $1 + npm test + + # cleanup + if [[ "${AWS_ACCESS_KEY_ID:-false}" != false ]] || [[ "${node_pre_gyp_accessKeyId:-false}" != false ]] || [[ -f $HOME/.node_pre_gyprc ]] ; then + node-pre-gyp unpublish $OPT_ARG + fi + node-pre-gyp clean $OPT_ARG + rm -rf $WD/{build,node_modules} + rm -rf $WD/lib/binding/ + cd ${BASE} +} + +setup +# simpliest, least config node c++ addon possible +build_app "app1" +# app with more custom organization and needing a variable passed for custom include path +build_app "app2" +# build app2 in debug mode +build_app "app2" "--debug" +# app that depends on an external static library +build_app "app3" +# app that depends on an external shared library +build_app "app4" +# disabled for now until node v0.11.x churn is over +#cd ${BASE}/test/app5 && npm cache clean || true;rm -rf node_modules/;npm install +#cd ${BASE}/test/app6 && npm cache clean || true;rm -rf node_modules/;npm install +teardown diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/.npmignore new file mode 100644 index 0000000..f6a0503 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/.npmignore @@ -0,0 +1,5 @@ +.DS_Store +build/ +lib/binding/ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/README.md new file mode 100644 index 0000000..65aca42 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/README.md @@ -0,0 +1,3 @@ +# Test app + +Demostrates a simple configuration that uses node-pre-gyp. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/app1.cc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/app1.cc new file mode 100644 index 0000000..dd9970b --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/app1.cc @@ -0,0 +1,38 @@ +// v8 +#include + +// node.js +#include +#include + +#if (NODE_MODULE_VERSION > 0x000B) + + static void get_hello(const v8::FunctionCallbackInfo& args) + { + v8::HandleScope scope(v8::Isolate::GetCurrent()); + args.GetReturnValue().Set(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),"hello")); + } + +#else + + static v8::Handle get_hello(const v8::Arguments& args) + { + v8::HandleScope scope; + return scope.Close(v8::String::New("hello")); + } + +#endif + +extern "C" { + static void start(v8::Handle target) { +#if (NODE_MODULE_VERSION > 0x000B) + v8::HandleScope scope(v8::Isolate::GetCurrent()); +#else + v8::HandleScope scope; +#endif + NODE_SET_METHOD(target, "hello", get_hello); + } +} + +NODE_MODULE(app1, start) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/binding.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/binding.gyp new file mode 100644 index 0000000..26e71b0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/binding.gyp @@ -0,0 +1,19 @@ +{ + "targets": [ + { + "target_name": "<(module_name)", + "sources": [ "<(module_name).cc" ], + }, + { + "target_name": "action_after_build", + "type": "none", + "dependencies": [ "<(module_name)" ], + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], + "destination": "<(module_path)" + } + ] + } + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/index.js new file mode 100644 index 0000000..0eb3990 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/index.js @@ -0,0 +1,7 @@ +var binary = require('../../'); +var path = require('path') +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); + +require('assert').equal(binding.hello(),"hello"); +console.log('hello'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/package.json new file mode 100644 index 0000000..98579ca --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app1/package.json @@ -0,0 +1,19 @@ +{ + "name": "node-pre-gyp-test-app1", + "author": "Dane Springmeyer ", + "description":"node-pre-gyp test", + "repository" : { + "type" : "git", + "url" : "git://github.com/mapbox/node-pre-gyp.git" + }, + "version": "0.1.0", + "main": "./index.js", + "binary": { + "module_name": "app1", + "module_path": "./lib/binding/", + "host":"https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com" + }, + "scripts": { + "install":"node-pre-gyp install --fallback-to-build" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/.npmignore new file mode 100644 index 0000000..f6a0503 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/.npmignore @@ -0,0 +1,5 @@ +.DS_Store +build/ +lib/binding/ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/README.md new file mode 100644 index 0000000..a8b8d0d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/README.md @@ -0,0 +1,3 @@ +# Test app + +Demostrates a very custom situation where an option must be passed to node-gyp in order for the binding.gyp to be properly configured. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/app2.cc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/app2.cc new file mode 100644 index 0000000..3874fa0 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/app2.cc @@ -0,0 +1,42 @@ +// v8 +#include + +// node.js +#include + +#include + +#include + +#if (NODE_MODULE_VERSION > 0x000B) + + static void get_hello(const v8::FunctionCallbackInfo& args) + { + v8::HandleScope scope(v8::Isolate::GetCurrent()); + args.GetReturnValue().Set(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),HELLO_WORLD)); + } + +#else + + static v8::Handle get_hello(const v8::Arguments& args) + { + v8::HandleScope scope; + return scope.Close(v8::String::New(HELLO_WORLD)); + } + +#endif + +extern "C" { + static void start(v8::Handle target) { +#if (NODE_MODULE_VERSION > 0x000B) + v8::HandleScope scope(v8::Isolate::GetCurrent()); +#else + v8::HandleScope scope; +#endif + NODE_SET_METHOD(target, "hello", get_hello); + } +} + + +NODE_MODULE(app2, start) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/binding.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/binding.gyp new file mode 100644 index 0000000..2990c04 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/binding.gyp @@ -0,0 +1,22 @@ +{ + "targets": [ + { + "target_name": "<(module_name)", + "sources": [ "<(module_name).cc" ], + 'include_dirs': [ + '<(custom_include_path)' + ] + }, + { + "target_name": "action_after_build", + "type": "none", + "dependencies": [ "<(module_name)" ], + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], + "destination": "<(module_path)/" + } + ] + } + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/include/foo.hpp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/include/foo.hpp new file mode 100644 index 0000000..047cf13 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/include/foo.hpp @@ -0,0 +1,6 @@ +#ifndef FOO_HPP +#define FOO_HPP + +#define HELLO_WORLD "hello" + +#endif diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/index.js new file mode 100644 index 0000000..259f437 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/index.js @@ -0,0 +1 @@ +require('./lib/index.js') \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/lib/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/lib/index.js new file mode 100644 index 0000000..90107da --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/lib/index.js @@ -0,0 +1,14 @@ +var binary = require('node-pre-gyp'); +var path = require('path') +var package_json_path = path.resolve(path.join(__dirname,'../package.json')); +var binding_release_path = binary.find(package_json_path); +var binding_debug_path = binary.find(package_json_path,{debug:true}); +try { + var binding = require(binding_debug_path); + console.log('Loaded Debug build from',binding_debug_path); +} catch (err) { + var binding = require(binding_release_path); + console.log('Loaded Release build from',binding_release_path); +} + +require('assert').equal(binding.hello(),"hello"); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/package.json new file mode 100644 index 0000000..9f51480 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app2/package.json @@ -0,0 +1,21 @@ +{ + "name": "node-pre-gyp-test-app2", + "author": "Dane Springmeyer ", + "description":"node-pre-gyp test", + "repository" : { + "type" : "git", + "url" : "git://github.com/mapbox/node-pre-gyp.git" + }, + "version": "0.1.0-release1.release2+build1.build2", + "main": "./lib/index.js", + "binary": { + "module_name": "app2", + "module_path": "./lib/binding/{configuration}/{name}", + "remote_path": "./{name}/v{version}/{configuration}/{version}/{toolset}/", + "package_name": "{module_name}-v{major}.{minor}.{patch}-{prerelease}+{build}-{node_abi}-{platform}-{arch}.tar.gz", + "host":"https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com" + }, + "scripts": { + "install":"node-pre-gyp install --fallback-to-build" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/.npmignore new file mode 100644 index 0000000..f6a0503 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/.npmignore @@ -0,0 +1,5 @@ +.DS_Store +build/ +lib/binding/ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/README.md new file mode 100644 index 0000000..65e2788 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/README.md @@ -0,0 +1,7 @@ +# Test app + +Demostrates an example node c++ app that depends on an external static library. + +Because the external `mylib.a` library is statically built and linked it will be available inside the `app3.node` binary. See the `app4` example for how to handle shared libraries. + +Demostrates an example node c++ app that depends on an external library. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/app3.cc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/app3.cc new file mode 100644 index 0000000..141195f --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/app3.cc @@ -0,0 +1,44 @@ +// v8 +#include + +// node.js +#include +#include + +#include + +#if (NODE_MODULE_VERSION > 0x000B) + + static void get_hello(const v8::FunctionCallbackInfo& args) + { + v8::HandleScope scope(v8::Isolate::GetCurrent()); + MyLib::Message msg("hello"); + std::string msg_string = msg.get(); + args.GetReturnValue().Set(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),msg_string.c_str())); + } + +#else + + static v8::Handle get_hello(const v8::Arguments& args) + { + v8::HandleScope scope; + MyLib::Message msg("hello"); + std::string msg_string = msg.get(); + return scope.Close(v8::String::New(msg_string.c_str())); + } + +#endif + +extern "C" { + static void start(v8::Handle target) { +#if (NODE_MODULE_VERSION > 0x000B) + v8::HandleScope scope(v8::Isolate::GetCurrent()); +#else + v8::HandleScope scope; +#endif + NODE_SET_METHOD(target, "hello", get_hello); + } +} + +NODE_MODULE(app3, start) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/binding.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/binding.gyp new file mode 100644 index 0000000..81e45a3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/binding.gyp @@ -0,0 +1,22 @@ +{ + "targets": [ + { + "target_name": "<(module_name)", + "sources": [ "<(module_name).cc" ], + "dependencies": [ + "deps/mylib.gyp:mylib" + ] + }, + { + "target_name": "action_after_build", + "type": "none", + "dependencies": [ "<(module_name)" ], + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], + "destination": "<(module_path)/" + } + ] + } + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/README.md new file mode 100644 index 0000000..d783d76 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/README.md @@ -0,0 +1,4 @@ +# sample c++ libary + +Example based on https://github.com/springmeyer/hello-gyp + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/include/mylib/interface.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/include/mylib/interface.h new file mode 100644 index 0000000..e7aac2c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/include/mylib/interface.h @@ -0,0 +1,19 @@ +#ifndef INCLUDE_MYLIB_INTERFACE_H_ +#define INCLUDE_MYLIB_INTERFACE_H_ + +#include + +namespace MyLib { + +class Message { + public: + explicit Message(std::string const& data); + std::string const& get(); + void set(std::string const& data); + + private: + std::string m_data; +}; +}; + +#endif // INCLUDE_MYLIB_INTERFACE_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/mylib.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/mylib.gyp new file mode 100644 index 0000000..01a65d8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/mylib.gyp @@ -0,0 +1,18 @@ +{ + "targets": [ + { + "target_name": "mylib", + "product_name": "mylib", + "type": "static_library", + "sources": [ + "src/implementation.cc" + ], + "include_dirs": [ + "include" + ], + 'direct_dependent_settings': { + 'include_dirs': [ 'include/' ], + } + } + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/src/implementation.cc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/src/implementation.cc new file mode 100644 index 0000000..4aeeec1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/deps/src/implementation.cc @@ -0,0 +1,16 @@ +#include +#include + +namespace MyLib { + +Message::Message(std::string const& data) + : m_data(data) {} + +std::string const& Message::get() { + return m_data; +} + +void Message::set(std::string const& data) { + m_data = data; +} +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/index.js new file mode 100644 index 0000000..fc15eb2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/index.js @@ -0,0 +1,7 @@ +var binary = require('node-pre-gyp'); +var path = require('path') +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); + +require('assert').equal(binding.hello(),"hello"); +console.log('hello'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/package.json new file mode 100644 index 0000000..ed28158 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app3/package.json @@ -0,0 +1,21 @@ +{ + "name": "node-pre-gyp-test-app3", + "author": "Dane Springmeyer ", + "description":"node-pre-gyp test", + "repository" : { + "type" : "git", + "url" : "git://github.com/mapbox/node-pre-gyp.git" + }, + "version": "0.1.0-dev.4", + "main": "./index.js", + "binary": { + "module_name": "app3", + "module_path": "./lib/binding/{node_abi}-{platform}-{arch}", + "remote_path": "./{module_name}/v{version}", + "package_name": "{node_abi}-{platform}-{arch}.tar.gz", + "host":"https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com" + }, + "scripts": { + "install":"node-pre-gyp install --fallback-to-build" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/.npmignore new file mode 100644 index 0000000..f6a0503 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/.npmignore @@ -0,0 +1,5 @@ +.DS_Store +build/ +lib/binding/ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/README.md new file mode 100644 index 0000000..d6617e8 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/README.md @@ -0,0 +1,7 @@ +# Test app + +Demostrates an example node c++ app that depends on an external shared library. + +See the `app3` example for how to handle static libraries. + +See https://code.google.com/p/gyp/issues/detail?id=315 for gory details about rpath decisions/defaults for gyp on linux. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/app4.cpp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/app4.cpp new file mode 100644 index 0000000..7e8cd2c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/app4.cpp @@ -0,0 +1,44 @@ +// v8 +#include + +// node.js +#include +#include + +#include + +#if (NODE_MODULE_VERSION > 0x000B) + + static void get_hello(const v8::FunctionCallbackInfo& args) + { + v8::HandleScope scope(v8::Isolate::GetCurrent()); + MyLib::Message msg("hello"); + std::string msg_string = msg.get(); + args.GetReturnValue().Set(v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),msg_string.c_str())); + } + +#else + + static v8::Handle get_hello(const v8::Arguments& args) + { + v8::HandleScope scope; + MyLib::Message msg("hello"); + std::string msg_string = msg.get(); + return scope.Close(v8::String::New(msg_string.c_str())); + } + +#endif + +extern "C" { + static void start(v8::Handle target) { +#if (NODE_MODULE_VERSION > 0x000B) + v8::HandleScope scope(v8::Isolate::GetCurrent()); +#else + v8::HandleScope scope; +#endif + NODE_SET_METHOD(target, "hello", get_hello); + } +} + +NODE_MODULE(app4, start) + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/binding.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/binding.gyp new file mode 100644 index 0000000..d4b5180 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/binding.gyp @@ -0,0 +1,42 @@ +{ + "targets": [ + { + "target_name": "<(module_name)", + "sources": [ "<(module_name).cpp" ], + "dependencies": [ + "deps/mylib.gyp:mylib" + ] + }, + { + "target_name": "action_after_build", + "type": "none", + "dependencies": [ "<(module_name)" ], + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], + "destination": "<(module_path)/" + }, + ], + 'conditions': [ + ['OS == "win"', { + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/mylib<(SHARED_LIB_SUFFIX)" ], + "destination": "<(module_path)/" + } + ] + }, { + "copies": [ + { + "files": [ "<(PRODUCT_DIR)/mylib<(SHARED_LIB_SUFFIX)" ], + "destination": "<(module_path)/lib.target/" + } + ] + } + ] + ] + } + ] +} + + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/README.md new file mode 100644 index 0000000..d783d76 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/README.md @@ -0,0 +1,4 @@ +# sample c++ libary + +Example based on https://github.com/springmeyer/hello-gyp + diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/include/mylib/interface.h b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/include/mylib/interface.h new file mode 100644 index 0000000..8ce3f95 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/include/mylib/interface.h @@ -0,0 +1,29 @@ +#ifndef INCLUDE_MYLIB_INTERFACE_H_ +#define INCLUDE_MYLIB_INTERFACE_H_ + +#include + +#ifdef _WIN64 +#define MYLIB_EXPORT __declspec (dllexport) +#elif _WIN32 +#define MYLIB_EXPORT __declspec (dllexport) +#elif __GNUC__ >= 4 +#define MYLIB_EXPORT __attribute__ ((visibility ("default"))) +#else +#define MYLIB_EXPORT +#endif + +namespace MyLib { + +class MYLIB_EXPORT Message { + public: + explicit Message(std::string const& data); + std::string const& get(); + void set(std::string const& data); + + private: + std::string m_data; +}; +}; + +#endif // INCLUDE_MYLIB_INTERFACE_H_ diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/mylib.gyp b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/mylib.gyp new file mode 100644 index 0000000..57c3fe3 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/mylib.gyp @@ -0,0 +1,21 @@ +{ + "targets": [ + { + "target_name": "mylib", + "product_name": "mylib", + "type": "shared_library", + "sources": [ + "src/implementation.cc" + ], + "include_dirs": [ + "include" + ], + 'direct_dependent_settings': { + 'include_dirs': [ 'include/' ], + }, + 'xcode_settings': { + 'DYLIB_INSTALL_NAME_BASE': '@loader_path/lib.target/' + } + } + ] +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/src/implementation.cc b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/src/implementation.cc new file mode 100644 index 0000000..4aeeec1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/deps/src/implementation.cc @@ -0,0 +1,16 @@ +#include +#include + +namespace MyLib { + +Message::Message(std::string const& data) + : m_data(data) {} + +std::string const& Message::get() { + return m_data; +} + +void Message::set(std::string const& data) { + m_data = data; +} +}; diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/index.js new file mode 100644 index 0000000..fc15eb2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/index.js @@ -0,0 +1,7 @@ +var binary = require('node-pre-gyp'); +var path = require('path') +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); + +require('assert').equal(binding.hello(),"hello"); +console.log('hello'); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/package.json new file mode 100644 index 0000000..8da5465 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app4/package.json @@ -0,0 +1,21 @@ +{ + "name": "node-pre-gyp-test-app3", + "author": "Dane Springmeyer ", + "description":"node-pre-gyp test", + "repository" : { + "type" : "git", + "url" : "git://github.com/mapbox/node-pre-gyp.git" + }, + "version": "0.1.0-dev.4", + "main": "./index.js", + "binary": { + "module_name": "app4", + "module_path": "./lib/binding/{node_abi}-{platform}-{arch}", + "remote_path": "./{module_name}/v{version}", + "package_name": "{node_abi}-{platform}-{arch}.tar.gz", + "host":"https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com" + }, + "scripts": { + "install":"node-pre-gyp install --fallback-to-build" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/.npmignore new file mode 100644 index 0000000..f6a0503 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/.npmignore @@ -0,0 +1,5 @@ +.DS_Store +build/ +lib/binding/ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/README.md new file mode 100644 index 0000000..e2e3ac1 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/README.md @@ -0,0 +1,5 @@ +# Test app + +Tests installing a module that depends on node-pre-gyp (arbitrarily) and depends on a module that needs node-pre-gyp at build time. + +This is to test https://github.com/mapbox/node-pre-gyp/issues/61. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/index.js new file mode 100644 index 0000000..084fc58 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/index.js @@ -0,0 +1,6 @@ +var binary = require('node-pre-gyp'); +var path = require('path') +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); + +require('assert').equal(binding.hello(),"hello"); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/package.json new file mode 100644 index 0000000..f91b292 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app5/package.json @@ -0,0 +1,15 @@ +{ + "name": "node-pre-gyp-test-dependents", + "author": "Dane Springmeyer ", + "description":"node-pre-gyp test", + "repository" : { + "type" : "git", + "url" : "git://github.com/mapbox/node-pre-gyp.git" + }, + "version": "0.1.0", + "main": "./index.js", + "dependencies": { + "node-addon-example": "0.1.3", + "node-pre-gyp": "0.5.x" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/.npmignore b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/.npmignore new file mode 100644 index 0000000..f6a0503 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/.npmignore @@ -0,0 +1,5 @@ +.DS_Store +build/ +lib/binding/ +node_modules +npm-debug.log \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/README.md b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/README.md new file mode 100644 index 0000000..ca55f3a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/README.md @@ -0,0 +1,3 @@ +# Test app + +Tests installing a module that depends on two modules that use node-pre-gyp at build time. diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/index.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/index.js new file mode 100644 index 0000000..084fc58 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/index.js @@ -0,0 +1,6 @@ +var binary = require('node-pre-gyp'); +var path = require('path') +var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); +var binding = require(binding_path); + +require('assert').equal(binding.hello(),"hello"); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/package.json new file mode 100644 index 0000000..0ec4e07 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/app6/package.json @@ -0,0 +1,12 @@ +{ + "name": "app6", + "description": "node-pre-gyp fail testcase", + "version": "0.0.0", + "engines": { + "node": "0.10.x" + }, + "dependencies": { + "node-addon-example": "0.1.3", + "node-addon-example2": "0.1.3" + } +} diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/build.test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/build.test.js new file mode 100644 index 0000000..5f3d670 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/build.test.js @@ -0,0 +1,426 @@ +"use strict"; + +var assert = require('assert'); +var cp = require('child_process'); +var path = require('path'); +var existsSync = require('fs').existsSync || require('path').existsSync; +var abi_crosswalk = require('../lib/util/abi_crosswalk.json'); +var os = require('os'); +var fs = require('fs'); +var rm = require('rimraf'); +var semver = require('semver'); +var runtime = semver.parse(process.version).major < 1 ? 'node' : 'iojs'; + +var cmd_path = path.join(__dirname,'../bin/'); +var sep = ':'; +var propertyPrefix = ''; +if (process.platform === 'win32') { + sep = ';'; + propertyPrefix = '/p:'; +} +process.env.PATH = cmd_path + sep + process.env.PATH; +process.env.NODE_PATH = path.join(__dirname,'../lib/'); + +function run(prog,command,args,app,opts,cb) { + if(prog === 'node-pre-gyp'){ + prog = runtime + ' ' + path.resolve(__dirname + '/../bin/node-pre-gyp.js'); + } + var final_cmd = prog + ' ' + command; + if (!opts.cwd) { + opts.cwd = path.join(__dirname,app.name); + } + final_cmd += ' ' + app.args; + final_cmd += ' ' + args; + + cp.exec(final_cmd,opts,function(err,stdout,stderr) { + if (err) { + var error = new Error("Command failed '" + command + "'"); + return cb(error,stdout,stderr); + } + return cb(err,stdout,stderr); + }); +} + +var apps = [ + { + 'name': 'app1', + 'args': '' + }, + { + 'name': 'app2', + 'args': '--custom_include_path=../include --debug' + }, + { + 'name': 'app2', + 'args': '--custom_include_path=../include --toolset=cpp11' + }, + { + 'name': 'app3', + 'args': '' + }, + { + 'name': 'app4', + 'args': '' + } +]; + +function getPreviousVersion(current_version) { + var current_parts = current_version.split('.').map(function(i) { return +i; }); + var major = current_parts[0]; + var minor = current_parts[1]; + var patch = current_parts[2]; + while (patch > 0) { + --patch; + var new_target = '' + major + '.' + minor + '.' + patch; + if (new_target == current_version) { + break; + } + if (abi_crosswalk[new_target]) { + return new_target; + } + } + // failed to find suitable future version that we expect is ABI compatible + return undefined; +} + +function on_error(err,stdout,stderr) { + var msg = err.message; + msg += '\nstdout: ' + stdout; + msg += '\nstderr: ' + stderr; + throw new Error(msg); +} + +var current_version = process.version.replace('v',''); +var previous_version = getPreviousVersion(current_version); +var target_abi; +var testing_crosswalk; +if (previous_version !== undefined && previous_version !== current_version) { + target_abi = {}; + target_abi[previous_version] = abi_crosswalk[previous_version]; + testing_crosswalk = path.join(os.tmpdir(),'fake_abi_crosswalk.json'); + fs.writeFileSync(testing_crosswalk,JSON.stringify(target_abi)); +} + +describe('simple build and test', function() { + + var app = {"name": "app2", "args":'--toolset=cpp11 --custom_include_path="../include"'}; + + before(function(done) { + // clear out entire binding directory + // to ensure no stale builds. This is needed + // because "node-pre-gyp clean" only removes + // the current target and not alternative builds + var binding_directory = path.join(__dirname,app.name,'lib/binding'); + if (fs.existsSync(binding_directory)) { + rm(binding_directory,done); + } else { + done(); + } + }); + + it(app.name + ' rebuilds ' + app.args, function(done) { + run('node-pre-gyp', 'rebuild', '--loglevel=error', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + done(); + }); + }); + + it(app.name + ' passes tests ' + app.args, function(done) { + run(runtime,'index.js','', app, {env : process.env, cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + // we expect app2 to console.log on success + if (app.name == 'app2') { + if (app.args.indexOf('--debug') > -1) { + assert.ok(stdout.indexOf('Loaded Debug build') > -1); + } else { + assert.ok(stdout.indexOf('Loaded Release build') > -1); + } + } else { + // we expect some kind of output... + assert.notEqual(stdout,''); + } + done(); + }); + }); +}); + + +describe('complex builds', function() { + + apps.forEach(function(app) { + + describe(app.name, function() { + + before(function(done) { + // clear out entire binding directory + // to ensure no stale builds. This is needed + // because "node-pre-gyp clean" only removes + // the current target and not alternative builds + var binding_directory = path.join(__dirname,app.name,'lib/binding'); + if (fs.existsSync(binding_directory)) { + rm(binding_directory,done); + } else { + done(); + } + }); + + it(app.name + ' configures ' + app.args, function(done) { + run('node-pre-gyp', 'configure', '--loglevel=error', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + done(); + }); + }); + + it(app.name + ' configures with unparsed options ' + app.args, function(done) { + run('node-pre-gyp', 'configure', '--loglevel=info -- -Dfoo=bar', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.ok(stderr.search(/(gyp info spawn args).*(-Dfoo=bar)/) > -1); + done(); + }); + }); + + it(app.name + ' installs', function(done) { + run('node-pre-gyp', 'install', '--update-binary --fallback-to-build', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.ok(stdout.search(app.name+'.node') > -1); + done(); + }); + }); + + it(app.name + ' builds ' + app.args, function(done) { + run('node-pre-gyp', 'rebuild', '--fallback-to-build --loglevel=error', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.equal(stderr,''); + done(); + }); + }); + + it(app.name + ' is found ' + app.args, function(done) { + run('node-pre-gyp', 'reveal', 'module_path --silent', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + var module_path = stdout.trim(); + assert.ok(module_path.search(app.name) > -1); + assert.ok(existsSync(module_path),'is found '+ module_path); + var module_binary = path.join(module_path,app.name+'.node'); + assert.ok(existsSync(module_binary)); + done(); + }); + }); + + it(app.name + ' passes tests ' + app.args, function(done) { + run(runtime,'index.js','', app, {env : process.env, cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + + // we expect app2 to console.log on success + if (app.name == 'app2') { + if (app.args.indexOf('--debug') > -1) { + assert.ok(stdout.indexOf('Loaded Debug build') > -1); + } else { + assert.ok(stdout.indexOf('Loaded Release build') > -1); + } + } else { + assert.notEqual(stdout,'', 'we expect some kind of output'); + } + done(); + }); + }); + + it(app.name + ' packages ' + app.args, function(done) { + run('node-pre-gyp', 'package', '', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + done(); + }); + }); + + it(app.name + ' package is valid ' + app.args, function(done) { + run('node-pre-gyp', 'testpackage', '', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + done(); + }); + }); + + if (process.env.AWS_ACCESS_KEY_ID || process.env.node_pre_gyp_accessKeyId) { + + it(app.name + ' publishes ' + app.args, function(done) { + run('node-pre-gyp', 'unpublish publish', '', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + done(); + }); + }); + + it(app.name + ' info shows it ' + app.args, function(done) { + run('node-pre-gyp', 'reveal', 'package_name', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + var package_name = stdout.trim(); + run('node-pre-gyp', 'info', '', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.ok(stdout.indexOf(package_name) > -1); + done(); + }); + }); + }); + + it(app.name + ' can be uninstalled ' + app.args, function(done) { + run('node-pre-gyp', 'clean', '', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + done(); + }); + }); + + it(app.name + ' can be installed via remote ' + app.args, function(done) { + run('npm', 'install', '--fallback-to-build=false', app, {env : process.env, cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + done(); + }); + }); + + it(app.name + ' can be reinstalled via remote ' + app.args, function(done) { + run('npm', 'install', '--update-binary --fallback-to-build=false', app, {env : process.env, cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + done(); + }); + }); + + it(app.name + ' via remote passes tests ' + app.args, function(done) { + run('npm', 'install', '', app, {env : process.env, cwd: path.join(__dirname,app.name)}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + done(); + }); + }); + + } else { + it.skip(app.name + ' publishes ' + app.args, function() {}); + } + + it(app.name + ' builds with unparsed options ' + app.args, function(done) { + run('node-pre-gyp', 'clean', '', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + run('node-pre-gyp', 'build', '--loglevel=info -- ' + propertyPrefix + 'FOO=bar', app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.ok(stderr.search(/(gyp info spawn args).*(FOO=bar)/) > -1); + done(); + }); + }); + }); + + // make sure node-gyp options are passed by passing invalid values + // and ensuring the expected errors are returned from node-gyp + //Python executable "foo" + it(app.name + ' passes --nodedir down to node-gyp via node-pre-gyp ' + app.args, function(done) { + run('node-pre-gyp', 'configure', '--nodedir=invalid-value', app, {}, function(err,stdout,stderr) { + assert.ok(err); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.ok(stderr.indexOf('common.gypi not found' > -1)); + done(); + }); + }); + + it(app.name + ' passes --nodedir down to node-gyp via npm' + app.args, function(done) { + run('npm', 'install', '--build-from-source --nodedir=invalid-value', app, {}, function(err,stdout,stderr) { + assert.ok(err); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.ok(stderr.indexOf('common.gypi not found' > -1)); + done(); + }); + }); + + // TODO - for some reason these do not error on windows + if (process.platform !== 'win32') { + it(app.name + ' passes --python down to node-gyp via node-pre-gyp ' + app.args, function(done) { + run('node-pre-gyp', 'configure', '--python=invalid-value', app, {}, function(err,stdout,stderr) { + assert.ok(err); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.ok(stderr.indexOf("Can't find Python executable" > -1)); + done(); + }); + }); + + it(app.name + ' passes --python down to node-gyp via npm ' + app.args, function(done) { + run('node-pre-gyp', 'configure', '--build-from-source --python=invalid-value', app, {}, function(err,stdout,stderr) { + assert.ok(err); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.ok(stderr.indexOf("Can't find Python executable" > -1)); + done(); + }); + }); + } + // note: --ensure=false tells node-gyp to attempt to re-download the node headers + // even if they already exist on disk at ~/.node-gyp/{version} + it(app.name + ' passes --dist-url down to node-gyp via node-pre-gyp ' + app.args, function(done) { + run('node-pre-gyp', 'configure', '--ensure=false --dist-url=invalid-value', app, {}, function(err,stdout,stderr) { + assert.ok(err); + assert.ok(stderr.indexOf('Invalid protocol: null' > -1)); + done(); + }); + }); + + it(app.name + ' passes --dist-url down to node-gyp via npm ' + app.args, function(done) { + run('npm', 'install', '--build-from-source --ensure=false --dist-url=invalid-value', app, {}, function(err,stdout,stderr) { + assert.ok(err); + assert.ok(stderr.indexOf('Invalid protocol: null' > -1)); + done(); + }); + }); + + if (target_abi) { + var new_env = JSON.parse(JSON.stringify(process.env)); + new_env.NODE_PRE_GYP_ABI_CROSSWALK = testing_crosswalk; + var opts = { env : new_env }; + it(app.name + ' builds with custom --target='+previous_version+' that is greater than known version in ABI crosswalk ' + app.args, function(done) { + run('node-pre-gyp', 'rebuild', '--loglevel=error --fallback-to-build --target='+previous_version, app, opts, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.equal(stderr,''); + done(); + }); + }); + + it(app.name + ' cleans up after installing custom --target='+previous_version+' that is greater than known in ABI crosswalk ' + app.args, function(done) { + run('node-pre-gyp', 'clean', '--target='+previous_version, app, opts, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.equal(stderr,''); + assert.notEqual(stdout,''); + done(); + }); + }); + + } else { + it.skip(app.name + ' builds with custom --target that is greater than known in ABI crosswalk ' + app.args, function() {}); + it.skip(app.name + ' builds with custom --target='+previous_version+' that is greater than known in ABI crosswalk ' + app.args, function() {}); + } + + // note: the above test will result in a non-runnable binary, so the below test must succeed otherwise all following tests will fail + + it(app.name + ' builds with custom --target ' + app.args, function(done) { + run('node-pre-gyp', 'rebuild', '--loglevel=error --fallback-to-build --target='+process.versions.node, app, {}, function(err,stdout,stderr) { + if (err) return on_error(err,stdout,stderr); + assert.ok(stdout.search(app.name+'.node') > -1); + assert.equal(stderr,''); + done(); + }); + }); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/mocha.opts b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/mocha.opts new file mode 100644 index 0000000..eddedab --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/mocha.opts @@ -0,0 +1,3 @@ +-R spec +--timeout 500000 +--slow 5000 diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/s3_setup.test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/s3_setup.test.js new file mode 100644 index 0000000..ead945d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/s3_setup.test.js @@ -0,0 +1,22 @@ +"use strict"; + +var s3_setup = require('../lib/util/s3_setup.js'); +var assert = require('assert'); + +describe('s3_setup', function() { + it('should propertly detect s3 bucket and prefix', function() { + var url = "https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com"; + var result = {}; + s3_setup.detect(url, result); + assert.equal(result.prefix,''); + assert.equal(result.bucket,'node-pre-gyp-tests'); + }); + + it('should propertly detect s3 bucket and prefix with dots', function() { + var url = "https://bucket.with.dots.s3.amazonaws.com/prefix"; + var result = {}; + s3_setup.detect(url, result); + assert.equal(result.prefix,'prefix'); + assert.equal(result.bucket,'bucket.with.dots'); + }); +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/versioning.test.js b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/versioning.test.js new file mode 100644 index 0000000..d9f56d2 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/node_modules/node-pre-gyp/test/versioning.test.js @@ -0,0 +1,67 @@ +"use strict"; + +var path = require('path'); +var versioning = require('../lib/util/versioning.js'); +var assert = require('assert'); + +describe('versioning', function() { + it('should normalize double slash', function() { + var mock_package_json = { + "name" : "test", + "main" : "test.js", + "version": "0.1.0", + "binary" : { + "module_name" : "test", + "module_path" : "./lib/binding/{configuration}/{toolset}/{name}", + "remote_path" : "./{name}/v{version}/{configuration}/{version}/{toolset}/", + "package_name": "{module_name}-v{major}.{minor}.{patch}-{prerelease}+{build}-{toolset}-{node_abi}-{platform}-{arch}.tar.gz", + "host" : "https://node-pre-gyp-tests.s3-us-west-1.amazonaws.com" + } + }; + var opts = versioning.evaluate(mock_package_json, {}); + assert.equal(opts.remote_path,"./test/v0.1.0/Release/0.1.0/"); + // Node v0.11.x on windows lowercases C:// when path.join is called + // https://github.com/joyent/node/issues/7031 + assert.equal(path.normalize(opts.module_path),path.join(process.cwd(),"lib/binding/Release/test")); + var opts_toolset = versioning.evaluate(mock_package_json, {toolset:"custom-toolset"}); + assert.equal(opts_toolset.remote_path,"./test/v0.1.0/Release/0.1.0/custom-toolset/"); + }); + + it('should detect abi for node process', function() { + var mock_process_versions = { + node: '0.10.33', + v8: '3.14.5.9', + modules: '11', + }; + var abi = versioning.get_node_abi('node',mock_process_versions); + assert.equal(abi,'node-v11'); + assert.equal(versioning.get_runtime_abi('node',undefined),versioning.get_node_abi('node',process.versions)); + }); + + it('should detect abi for odd node target', function() { + var mock_process_versions = { + node: '0.11.1000000', + modules: 'bogus', + }; + var abi = versioning.get_node_abi('node',mock_process_versions); + assert.equal(abi,'node-v0.11.1000000'); + }); + + it('should detect abi for custom node target', function() { + var mock_process_versions = { + "node": '0.10.0', + "modules": '11', + }; + assert.equal(versioning.get_runtime_abi('node','0.10.0'),versioning.get_node_abi('node',mock_process_versions)); + var mock_process_versions2 = { + "node": '0.8.0', + "v8": "3.11" + }; + assert.equal(versioning.get_runtime_abi('node','0.8.0'),versioning.get_node_abi('node',mock_process_versions2)); + }); + + it('should detect abi for node-webkit runtime', function() { + assert.equal(versioning.get_runtime_abi('node-webkit','0.10.5'),versioning.get_node_webkit_abi('node-webkit','0.10.5')); + }); + +}); diff --git a/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/package.json b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/package.json new file mode 100644 index 0000000..613d079 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/node_modules/bson-ext/package.json @@ -0,0 +1,79 @@ +{ + "name": "bson-ext", + "description": "The C++ bson parser for the node.js mongodb driver.", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "version": "0.1.7", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "contributors": [], + "repository": { + "type": "git", + "url": "git://github.com/christkv/bson-ext.git" + }, + "bugs": { + "url": "https://github.com/christkv/bson-ext/issues" + }, + "dependencies": { + "nan": "~1.8.0", + "node-pre-gyp": "https://github.com/mongodb-js/node-pre-gyp/archive/v0.6.5-appveyor.tar.gz" + }, + "bundledDependecies": [ + "node-pre-gyp" + ], + "devDependencies": { + "nodeunit": "~0.9.0" + }, + "main": "./index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.8.19" + }, + "scripts": { + "install": "(node-pre-gyp install --fallback-to-build) || (node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "nodeunit ./test/node" + }, + "licenses": [ + { + "type": "Apache License, Version 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0" + } + ], + "binary": { + "module_name": "bson", + "module_path": "build/Release", + "host": "https://bin.mongodb.org", + "remote_path": "/js/bson-ext/v{version}", + "bucket": "mongodb-dx-public" + }, + "gitHead": "605485a6a4fda86ea7c6cfb4998036d4e47f2add", + "homepage": "https://github.com/christkv/bson-ext", + "_id": "bson-ext@0.1.7", + "_shasum": "aef2657fc19cd1c970dbe605299b4da9673aef44", + "_from": "bson-ext@>=0.1.0 <0.2.0", + "_npmVersion": "2.9.0", + "_nodeVersion": "2.0.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "aef2657fc19cd1c970dbe605299b4da9673aef44", + "tarball": "http://registry.npmjs.org/bson-ext/-/bson-ext-0.1.7.tgz" + }, + "_resolved": "https://registry.npmjs.org/bson-ext/-/bson-ext-0.1.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/package.json b/node_modules/mongoose/node_modules/bson/package.json new file mode 100644 index 0000000..177654d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/package.json @@ -0,0 +1,80 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "version": "0.3.2", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "contributors": [], + "repository": { + "type": "git", + "url": "git://github.com/mongodb/js-bson.git" + }, + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "devDependencies": { + "nodeunit": "0.9.0", + "gleak": "0.2.3", + "one": "2.X.X" + }, + "optionalDependencies": { + "bson-ext": "~0.1" + }, + "config": { + "native": false + }, + "main": "./lib/bson/index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" + }, + "browser": "lib/bson/bson.js", + "licenses": [ + { + "type": "Apache License, Version 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0" + } + ], + "gitHead": "42c18a3cb68ed5188f4e9653d04e341b06d31d6c", + "homepage": "https://github.com/mongodb/js-bson", + "dependencies": { + "bson-ext": "~0.1" + }, + "_id": "bson@0.3.2", + "_shasum": "56753c5e8d86d0f45744b93a9693e4f60a8bbd6c", + "_from": "bson@>=0.3.0 <0.4.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "octave", + "email": "chinsay@gmail.com" + }, + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "56753c5e8d86d0f45744b93a9693e4f60a8bbd6c", + "tarball": "http://registry.npmjs.org/bson/-/bson-0.3.2.tgz" + }, + "_resolved": "https://registry.npmjs.org/bson/-/bson-0.3.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/bson/tools/gleak.js b/node_modules/mongoose/node_modules/bson/tools/gleak.js new file mode 100644 index 0000000..c707cfc --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/tools/gleak.js @@ -0,0 +1,21 @@ + +var gleak = require('gleak')(); +gleak.ignore('AssertionError'); +gleak.ignore('testFullSpec_param_found'); +gleak.ignore('events'); +gleak.ignore('Uint8Array'); +gleak.ignore('Uint8ClampedArray'); +gleak.ignore('TAP_Global_Harness'); +gleak.ignore('setImmediate'); +gleak.ignore('clearImmediate'); + +gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); +gleak.ignore('DTRACE_NET_STREAM_END'); +gleak.ignore('DTRACE_NET_SOCKET_READ'); +gleak.ignore('DTRACE_NET_SOCKET_WRITE'); +gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); +gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); +gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); +gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); + +module.exports = gleak; diff --git a/node_modules/mongoose/node_modules/hooks-fixed/.npmignore b/node_modules/mongoose/node_modules/hooks-fixed/.npmignore new file mode 100644 index 0000000..96e29a8 --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/.npmignore @@ -0,0 +1,2 @@ +**.swp +node_modules diff --git a/node_modules/mongoose/node_modules/hooks-fixed/Makefile b/node_modules/mongoose/node_modules/hooks-fixed/Makefile new file mode 100644 index 0000000..1db5d65 --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/Makefile @@ -0,0 +1,9 @@ +test: + @NODE_ENV=test ./node_modules/expresso/bin/expresso \ + $(TESTFLAGS) \ + ./test.js + +test-cov: + @TESTFLAGS=--cov $(MAKE) test + +.PHONY: test test-cov diff --git a/node_modules/mongoose/node_modules/hooks-fixed/README.md b/node_modules/mongoose/node_modules/hooks-fixed/README.md new file mode 100644 index 0000000..98fe85b --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/README.md @@ -0,0 +1,369 @@ +hooks +============ + +Add pre and post middleware hooks to your JavaScript methods. + +## Installation + npm install hooks + +## Motivation +Suppose you have a JavaScript object with a `save` method. + +It would be nice to be able to declare code that runs before `save` and after `save`. +For example, you might want to run validation code before every `save`, +and you might want to dispatch a job to a background job queue after `save`. + +One might have an urge to hard code this all into `save`, but that turns out to +couple all these pieces of functionality (validation, save, and job creation) more +tightly than is necessary. For example, what if someone does not want to do background +job creation after the logical save? + +It is nicer to tack on functionality using what we call `pre` and `post` hooks. These +are functions that you define and that you direct to execute before or after particular +methods. + +## Example +We can use `hooks` to add validation and background jobs in the following way: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +// Define a new method that is able to invoke pre and post middleware +Document.hook('save', Document.prototype.save); + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +If you already have defined `Document.prototype` methods for which you want pres and posts, +then you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)` +or `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]` +so that it plays well with `hooks`. An equivalent way to implement the previous example is: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +Document.prototype.save = function () { + // ... +}; + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +## Pres and Posts as Middleware +We structure pres and posts as middleware to give you maximum flexibility: + +1. You can define **multiple** pres (or posts) for a single method. +2. These pres (or posts) are then executed as a chain of methods. +3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid. + +## Defining multiple pres (or posts) +`pre` and `post` are chainable, so you can define multiple via: +```javascript +Document.pre('save', function (next) { + console.log("hello"); + next(); +}).pre('save', function (next) { + console.log("world"); + next(); +}); + +Document.post('save', function (next) { + console.log("hello"); + next(); +}).post('save', function (next) { + console.log("world"); + next(); +}); +``` + +As soon as one pre finishes executing, the next one will be invoked, and so on. + +## Error Handling +You can define a default error handler by passing a 2nd function as the 3rd argument to `hook`: +```javascript +Document.hook('set', function (path, val) { + this[path] = val; +}, function (err) { + // Handler the error here + console.error(err); +}); +``` + +Then, we can pass errors to this handler from a pre or post middleware function: +```javascript +Document.pre('set', function (next, path, val) { + next(new Error()); +}); +``` + +If you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`. + +The default error handler can be over-rided on a per method invocation basis. + +If the main method that you are surrounding with pre and post middleware expects its last argument to be a function +with callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default +error handler you may have set up. + +```javascript +Document.hook('save', function (callback) { + // Save logic goes here + ... +}); + +var doc = new Document(); +doc.save( function (err, saved) { + // We can pass err via `next` in any of our pre or post middleware functions + if (err) console.error(err); + + // Rest of callback logic follows ... +}); +``` + +## Mutating Arguments via Middleware +`pre` and `post` middleware can also accept the intended arguments for the method +they augment. This is useful if you want to mutate the arguments before passing +them along to the next middleware and eventually pass a mutated arguments list to +the main method itself. + +As a simple example, let's define a method `set` that just sets a key, value pair. +If we want to namespace the key, we can do so by adding a `pre` middleware hook +that runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`: + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + next('namespace-' + key, val); +}); +var doc = new Document(); +doc.set('hello', 'world'); +console.log(doc.hello); // undefined +console.log(doc['namespace-hello']); // 'world' +``` + +As you can see above, we pass arguments via `next`. + +If you are not mutating the arguments, then you can pass zero arguments +to `next`, and the next middleware function will still have access +to the arguments. + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + // I have access to key and val here + next(); // We don't need to pass anything to next +}); +Document.pre('set', function (next, key, val) { + // And I still have access to the original key and val here + next(); +}); +``` + +Finally, you can add arguments that downstream middleware can also see: + +```javascript +// Note that in the definition of `set`, there is no 3rd argument, options +Document.hook('set', function (key, val) { + // But... + var options = arguments[2]; // ...I have access to an options argument + // because of pre function pre2 (defined below) + console.log(options); // '{debug: true}' + this[key] = val; +}); +Document.pre('set', function pre1 (next, key, val) { + // I only have access to key and val arguments + console.log(arguments.length); // 3 + next(key, val, {debug: true}); +}); +Document.pre('set', function pre2 (next, key, val, options) { + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); +Document.pre('set', function pre3 (next, key, val, options) { + // I still have access to key, val, AND the options argument introduced via the preceding middleware + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); + +var doc = new Document() +doc.set('hey', 'there'); +``` + +## Post middleware + +Post middleware intercepts the callback originally sent to the asynchronous function you have hooked to. + +This means that the following chain of execution will occur in a typical `save` operation: + +(1) doc.save -> (2) pre --(next)--> (3) save calls back -> (4) post --(next)--> (5) targetFn + +Illustrated below: + +``` +Document.pre('save', function (next) { + this.key = "value"; + next(); +}); +// Post handler occurs before `set` calls back. This is useful if we need to grab something +// async before `set` finishes. +Document.post('set', function (next) { + var me = this; + getSomethingAsync(function(value){ // let's assume it returns "Hello Async" + me.key2 = value; + next(); + }); +}); + +var doc = new Document(); +doc.save(function(err){ + console.log(this.key); // "value" - this value was saved + console.log(this.key2); // "Hello Async" - this value was *not* saved +} + +``` + +Post middleware must call `next()` or execution will stop. + +## Parallel `pre` middleware + +All middleware up to this point has been "serial" middleware -- i.e., middleware whose logic +is executed as a serial chain. + +Some scenarios call for parallel middleware -- i.e., middleware that can wait for several +asynchronous services at once to respond. + +For instance, you may only want to save a Document only after you have checked +that the Document is valid according to two different remote services. + +We accomplish asynchronous middleware by adding a second kind of flow control callback +(the only flow control callback so far has been `next`), called `done`. + +- `next` passes control to the next middleware in the chain +- `done` keeps track of how many parallel middleware have invoked `done` and passes + control to the target method when ALL parallel middleware have invoked `done`. If + you pass an `Error` to `done`, then the error is handled, and the main method that is + wrapped by pres and posts will not get invoked. + +We declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre` +definition method. + +We illustrate via the parallel validation example mentioned above: + +```javascript +Document.hook('save', function targetFn (callback) { + // Save logic goes here + // ... + // This only gets run once the two `done`s are both invoked via preOne and preTwo. +}); + + // true marks this as parallel middleware +Document.pre('save', true, function preOne (next, doneOne, callback) { + remoteServiceOne.validate(this.serialize(), function (err, isValid) { + // The code in here will probably be run after the `next` below this block + // and could possibly be run after the console.log("Hola") in `preTwo + if (err) return doneOne(err); + if (isValid) doneOne(); + }); + next(); // Pass control to the next middleware +}); + +// We will suppose that we need 2 different remote services to validate our document +Document.pre('save', true, function preTwo (next, doneTwo, callback) { + remoteServiceTwo.validate(this.serialize(), function (err, isValid) { + if (err) return doneTwo(err); + if (isValid) doneTwo(); + }); + next(); +}); + +// While preOne and preTwo are parallel, preThree is a serial pre middleware +Document.pre('save', function preThree (next, callback) { + next(); +}); + +var doc = new Document(); +doc.save( function (err, doc) { + // Do stuff with the saved doc here... +}); +``` + +In the above example, flow control may happen in the following way: + +(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn + +So what's happening is that: + +1. You call `doc.save(...)` +2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware. +3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware. +4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services. +5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo. +6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne. +7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic). + +## Removing Pres + +You can remove a particular pre associated with a hook: + + Document.pre('set', someFn); + Document.removePre('set', someFn); + +And you can also remove all pres associated with a hook: + Document.removePre('set'); // Removes all declared `pre`s on the hook 'set' + +## Tests +To run the tests: + make test + +### Contributors +- [Brian Noguchi](https://github.com/bnoguchi) + +### License +MIT License + +--- +### Author +Brian Noguchi diff --git a/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js b/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js new file mode 100644 index 0000000..6ced357 --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js @@ -0,0 +1,134 @@ +/** + * Hooks are useful if we want to add a method that automatically has `pre` and `post` hooks. + * For example, it would be convenient to have `pre` and `post` hooks for `save`. + * _.extend(Model, mixins.hooks); + * Model.hook('save', function () { + * console.log('saving'); + * }); + * Model.pre('save', function (next, done) { + * console.log('about to save'); + * next(); + * }); + * Model.post('save', function (next, done) { + * console.log('saved'); + * next(); + * }); + * + * var m = new Model(); + * m.save(); + * // about to save + * // saving + * // saved + */ + +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, err) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + if (!err) err = fn; + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + function noop () {} + + proto[name] = function () { + var self = this + , pres = this._pres[name] + , posts = this._posts[name] + , numAsyncPres = 0 + , hookArgs = [].slice.call(arguments) + , preChain = pres.map( function (pre, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (numAsyncPres) { + // arguments[1] === asyncComplete + if (arguments.length) + hookArgs = [].slice.call(arguments, 2); + pre.apply(self, + [ preChain[i+1] || allPresInvoked, + asyncComplete + ].concat(hookArgs) + ); + } else { + if (arguments.length) + hookArgs = [].slice.call(arguments); + pre.apply(self, + [ preChain[i+1] || allPresDone ].concat(hookArgs)); + } + }; // end wrapper = function () {... + if (wrapper.isAsync = pre.isAsync) + numAsyncPres++; + return wrapper; + }); // end posts.map(...) + function allPresInvoked () { + if (arguments[0] instanceof Error) + err(arguments[0]); + } + + function allPresDone () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + fn.apply(self, hookArgs); + var postChain = posts.map( function (post, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + post.apply(self, + [ postChain[i+1] || noop].concat(hookArgs)); + }; // end wrapper = function () {... + return wrapper; + }); // end posts.map(...) + if (postChain.length) postChain[0](); + } + + if (numAsyncPres) { + complete = numAsyncPres; + function asyncComplete () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + --complete || allPresDone.call(this); + } + } + (preChain[0] || allPresDone)(); + }; + + return this; + }, + + pre: function (name, fn, isAsync) { + var proto = this.prototype + , pres = proto._pres = proto._pres || {}; + if (fn.isAsync = isAsync) { + this.prototype[name].numAsyncPres++; + } + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, fn, isAsync) { + var proto = this.prototype + , posts = proto._posts = proto._posts || {}; + (posts[name] = posts[name] || []).push(fn); + return this; + } +}; diff --git a/node_modules/mongoose/node_modules/hooks-fixed/hooks.js b/node_modules/mongoose/node_modules/hooks-fixed/hooks.js new file mode 100644 index 0000000..ad43e3b --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/hooks.js @@ -0,0 +1,173 @@ +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, errorCb) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + proto[name] = function () { + var self = this + , hookArgs // arguments eventually passed to the hook - are mutable + , lastArg = arguments[arguments.length-1] + , pres = this._pres[name] + , posts = this._posts[name] + , _total = pres.length + , _current = -1 + , _asyncsLeft = proto[name].numAsyncPres + , _asyncsDone = function(err) { + if (err) { + return handleError(err); + } + --_asyncsLeft || _done.apply(self, hookArgs); + } + , handleError = function(err) { + if ('function' == typeof lastArg) + return lastArg(err); + if (errorCb) return errorCb.call(self, err); + throw err; + } + , _next = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var _args = Array.prototype.slice.call(arguments) + , currPre + , preArgs; + if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) + hookArgs = _args; + if (++_current < _total) { + currPre = pres[_current] + if (currPre.isAsync && currPre.length < 2) + throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); + if (currPre.length < 1) + throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); + preArgs = (currPre.isAsync + ? [once(_next), once(_asyncsDone)] + : [once(_next)]).concat(hookArgs); + return currPre.apply(self, preArgs); + } else if (!_asyncsLeft) { + return _done.apply(self, hookArgs); + } + } + , _done = function () { + var args_ = Array.prototype.slice.call(arguments) + , ret, total_, current_, next_, done_, postArgs; + + if (_current === _total) { + + next_ = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var args_ = Array.prototype.slice.call(arguments, 1) + , currPost + , postArgs; + if (args_.length) hookArgs = args_; + if (++current_ < total_) { + currPost = posts[current_] + if (currPost.length < 1) + throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); + postArgs = [once(next_)].concat(hookArgs); + return currPost.apply(self, postArgs); + } else if (typeof lastArg === 'function'){ + // All post handlers are done, call original callback function + return lastArg.apply(self, arguments); + } + }; + + // We are assuming that if the last argument provided to the wrapped function is a function, it was expecting + // a callback. We trap that callback and wait to call it until all post handlers have finished. + if(typeof lastArg === 'function'){ + args_[args_.length - 1] = once(next_); + } + + total_ = posts.length; + current_ = -1; + ret = fn.apply(self, args_); // Execute wrapped function, post handlers come afterward + + if (total_ && typeof lastArg !== 'function') return next_(); // no callback provided, execute next_() manually + return ret; + } + }; + + return _next.apply(this, arguments); + }; + + proto[name].numAsyncPres = 0; + + return this; + }, + + pre: function (name, isAsync, fn, errorCb) { + if ('boolean' !== typeof arguments[1]) { + errorCb = fn; + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {}; + + this._lazySetupHooks(proto, name, errorCb); + + if (fn.isAsync = isAsync) { + proto[name].numAsyncPres++; + } + + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, isAsync, fn) { + if (arguments.length === 2) { + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , posts = proto._posts = proto._posts || {}; + + this._lazySetupHooks(proto, name); + (posts[name] = posts[name] || []).push(fn); + return this; + }, + removePre: function (name, fnToRemove) { + var proto = this.prototype || this + , pres = proto._pres || (proto._pres || {}); + if (!pres[name]) return this; + if (arguments.length === 1) { + // Remove all pre callbacks for hook `name` + pres[name].length = 0; + } else { + pres[name] = pres[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + _lazySetupHooks: function (proto, methodName, errorCb) { + if ('undefined' === typeof proto[methodName].numAsyncPres) { + this.hook(methodName, proto[methodName], errorCb); + } + } +}; + +function once (fn, scope) { + return function fnWrapper () { + if (fnWrapper.hookCalled) return; + fnWrapper.hookCalled = true; + return fn.apply(scope, arguments); + }; +} diff --git a/node_modules/mongoose/node_modules/hooks-fixed/package.json b/node_modules/mongoose/node_modules/hooks-fixed/package.json new file mode 100644 index 0000000..4b5a325 --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/package.json @@ -0,0 +1,66 @@ +{ + "name": "hooks-fixed", + "description": "Adds pre and post hook functionality to your JavaScript methods.", + "version": "1.0.1", + "keywords": [ + "node", + "hooks", + "middleware", + "pre", + "post" + ], + "homepage": "https://github.com/vkarpov15/hooks-fixed/", + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/hooks-fixed.git" + }, + "author": { + "name": "Brian Noguchi", + "email": "brian.noguchi@gmail.com", + "url": "https://github.com/bnoguchi/" + }, + "main": "./hooks.js", + "directories": { + "lib": "." + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "expresso": ">=0.7.6", + "should": ">=0.2.1", + "underscore": ">=1.1.4" + }, + "engines": { + "node": ">=0.4.0" + }, + "licenses": [ + "MIT" + ], + "optionalDependencies": {}, + "gitHead": "7b4d7cec7a2edf7c5242378dd0495606dc474dd4", + "bugs": { + "url": "https://github.com/vkarpov15/hooks-fixed/issues" + }, + "_id": "hooks-fixed@1.0.1", + "_shasum": "f1f6694a62317fb36c11ffb067708a15947e6f9e", + "_from": "hooks-fixed@1.0.1", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "dist": { + "shasum": "f1f6694a62317fb36c11ffb067708a15947e6f9e", + "tarball": "http://registry.npmjs.org/hooks-fixed/-/hooks-fixed-1.0.1.tgz" + }, + "_resolved": "https://registry.npmjs.org/hooks-fixed/-/hooks-fixed-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/hooks-fixed/test.js b/node_modules/mongoose/node_modules/hooks-fixed/test.js new file mode 100644 index 0000000..0f9e69d --- /dev/null +++ b/node_modules/mongoose/node_modules/hooks-fixed/test.js @@ -0,0 +1,741 @@ +var hooks = require('./hooks') + , should = require('should') + , assert = require('assert') + , _ = require('underscore'); + +// TODO Add in test for making sure all pres get called if pre is defined directly on an instance. +// TODO Test for calling `done` twice or `next` twice in the same function counts only once +module.exports = { + 'should be able to assign multiple hooks at once': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook({ + hook1: function (a) {}, + hook2: function (b) {} + }); + var a = new A(); + assert.equal(typeof a.hook1, 'function'); + assert.equal(typeof a.hook2, 'function'); + }, + 'should run without pres and posts when not present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + 'should run with pres when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + 'should run with posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + 'should run pres and posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + A.post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + a.preValue.should.equal(2); + }, + 'should run posts after pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.override = 100; + next(); + }); + A.post('save', function (next) { + this.override = 200; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.override.should.equal(200); + }, + 'should not run a hook if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function () { + this.value = 1; + }, function (err) { + counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + this.v2 = 2; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + a.v2.should.equal(2); + }, + 'should run multiple pres until a pre fails and not call the hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }, function (err) {}); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + next(new Error()); + }).pre('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + assert.equal(typeof a.v3, 'undefined'); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple posts': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3.14; + next(); + }).post('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + assert.equal(a.value, 3.14); + assert.equal(a.v3, 3); + }, + 'should run only posts up until an error': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }, function (err) {}); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3; + next(new Error()); + }).post('save', function (next) { + this.value = 4; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + }, + "should fall back first to the hook method's last argument as the error handler if it is a function of arity 1 or 2": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + }); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back second to the default error handler if specified': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'fallback default error handler should scope to the object': function () { + var A = function () { + this.counter = 0; + }; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) this.counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + a.counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back last to throwing the error': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (err) { + if (err instanceof Error) return counter++; + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + var didCatch = false; + try { + a.save(); + } catch (e) { + didCatch = true; + e.should.be.an.instanceof(Error); + counter.should.equal(0); + assert.equal(typeof a.value, 'undefined'); + } + didCatch.should.be.true; + }, + "should proceed without mutating arguments if `next(null|undefined)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.prototype.save = function (callback) { + this.value = 1; + callback(); + }; + A.pre('save', function (next) { + next(null); + }); + A.pre('save', function (next) { + next(undefined); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + else counter--; + }); + counter.should.equal(-1); + a.value.should.eql(1); + }, + "should proceed with mutating arguments if `next(null|undefined)` is callback in a serial pre, and the last argument of the target method is not a function": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.set = function (v) { + this.value = v; + }; + A.pre('set', function (next) { + next(undefined); + }); + A.pre('set', function (next) { + next(null); + }); + var a = new A(); + a.set(1); + should.strictEqual(null, a.value); + }, + 'should not run any posts if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 2; + }, function (err) {}); + A.pre('save', function (next) { + this.value = 1; + next(new Error()); + }).post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + + "can pass the hook's arguments verbatim to pres": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.hello.should.equal('world'); + }, +// "can pass the hook's arguments as an array to pres": function () { +// // Great for dynamic arity - e.g., slice(...) +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.pre('set', function (next, hello, world) { +// hello.should.equal('hello'); +// world.should.equal('world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "can pass the hook's arguments verbatim to posts": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.post('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(a.hello, 'world'); + }, +// "can pass the hook's arguments as an array to posts": function () { +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.post('set', function (next, halt, args) { +// assert.equal(args[0], 'hello'); +// assert.equal(args[1], 'world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "pres should be able to modify and pass on a modified version of the hook's arguments": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + assert.equal(arguments[2], 'optional'); + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.pre('set', function (next, path, val) { + assert.equal(path, 'foo'); + assert.equal(val, 'bar'); + next('rock', 'says', 'optional'); + }); + A.pre('set', function (next, path, val, opt) { + assert.equal(path, 'rock'); + assert.equal(val, 'says'); + assert.equal(opt, 'optional'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.rock.should.equal('says'); + }, + 'posts should see the modified version of arguments if the pres modified them': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.post('set', function (next, path, val) { + path.should.equal('foo'); + val.should.equal('bar'); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.foo.should.equal('bar'); + }, + 'should pad missing arguments (relative to expected arguments of the hook) with null': function () { + // Otherwise, with hookFn = function (a, b, next, ), + // if we use hookFn(a), then because the pre functions are of the form + // preFn = function (a, b, next, ), then it actually gets executed with + // preFn(a, next, ), so when we call next() from within preFn, we are actually + // calling () + + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val, opts) { + this[path] = val; + }); + A.pre('set', function (next, path, val, opts) { + next('foo', 'bar'); + assert.equal(typeof opts, 'undefined'); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'should not invoke the target method until all asynchronous middleware have invoked dones': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + counter++; + this[path] = val; + counter.should.equal(7); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 500); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'invoking a method twice should run its async middleware twice': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + if (path === 'hello') counter.should.equal(1); + if (path === 'foo') counter.should.equal(2); + }); + A.pre('set', true, function (next, done, path, val) { + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.set('foo', 'bar'); + }, + + 'calling the same done multiple times should have the effect of only calling it once': function () { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', true, function (next, done) { + next(); + done(); + done(); + }); + A.pre('ack', true, function (next, done) { + next(); + // Notice that done() is not invoked here + }); + var a = new A(); + a.ack(); + setTimeout( function () { + a.acked.should.be.false; + }, 1000); + }, + + 'calling the same next multiple times should have the effect of only calling it once': function (beforeExit) { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', function (next) { + // force a throw to re-exec next() + try { + next(new Error('bam')); + } catch (err) { + next(); + } + }); + A.pre('ack', function (next) { + next(); + }); + var a = new A(); + a.ack(); + beforeExit( function () { + a.acked.should.be.false; + }); + }, + + 'asynchronous middleware should be able to pass an error via `done`, stopping the middleware chain': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val, fn) { + counter++; + this[path] = val; + fn(null); + }); + A.pre('set', true, function (next, done, path, val, fn) { + setTimeout(function () { + counter++; + done(new Error); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world', function (err) { + err.should.be.an.instanceof(Error); + should.strictEqual(undefined, a['hello']); + counter.should.eql(1); + }); + }, + + 'should be able to remove a particular pre': function () { + var A = function () {} + , preTwo; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', preTwo = function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save', preTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValueOne.should.equal(2); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove all pres associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.preValueOne); + should.strictEqual(undefined, a.preValueTwo); + }, + + '#pre should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + + '#pre lazily making a method hookable should be able to provide a default errorHandler as the last argument': function () { + var A = function () {}; + var preValue = ""; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + next(new Error); + }, function (err) { + preValue = 'ERROR'; + }); + var a = new A(); + a.save(); + should.strictEqual(undefined, a.value); + preValue.should.equal('ERROR'); + }, + + '#post should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + + "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function (fn) {}; + A.pre('save', function (next) { + next(new Error("hi there")); + }); + var a = new A(); + a.save( function (err) { + err.should.be.an.instanceof(Error); + }); + }, + + 'should intercept method callbacks for post handlers': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.post('save', function (next) { + assert.equal(a.value, 2); + this.value += 2; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 4); + this.value += 3; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 7); + this.value2 = 3; + setTimeout(next, 10); + }); + var a = new A(); + a.save(2, function(){ + assert.equal(a.value, 7); + assert.equal(a.value2, 3); + }); + }, + + 'should handle parallel followed by serial': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.pre('save', true, function(next, done) { + process.nextTick(function() { + done(); + }); + next(); + }).pre('save', function(done) { + process.nextTick(function() { + done(); + }); + }); + var a = new A(); + a.save(2, function(){ + assert.ok(true); + }); + } +}; diff --git a/node_modules/mongoose/node_modules/kareem/.npmignore b/node_modules/mongoose/node_modules/kareem/.npmignore new file mode 100644 index 0000000..59d842b --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/.npmignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript diff --git a/node_modules/mongoose/node_modules/kareem/.travis.yml b/node_modules/mongoose/node_modules/kareem/.travis.yml new file mode 100644 index 0000000..9aa8222 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.12" + - "0.10" + - "iojs" +script: "npm run-script test-travis" +after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/node_modules/mongoose/node_modules/kareem/LICENSE b/node_modules/mongoose/node_modules/kareem/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/node_modules/mongoose/node_modules/kareem/Makefile b/node_modules/mongoose/node_modules/kareem/Makefile new file mode 100644 index 0000000..f71ba90 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/Makefile @@ -0,0 +1,5 @@ +docs: + node ./docs.js + +coverage: + ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/* diff --git a/node_modules/mongoose/node_modules/kareem/README.md b/node_modules/mongoose/node_modules/kareem/README.md new file mode 100644 index 0000000..7d2dc84 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/README.md @@ -0,0 +1,379 @@ +# kareem + + [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem) + [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem) + +Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, meant to offer additional flexibility in allowing you to execute hooks whenever necessary, as opposed to simply wrapping a single function. + +Named for the NBA's all-time leading scorer Kareem Abdul-Jabbar, known for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook) + + + +# API + +## pre hooks + +Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define +pre and post hooks: pre hooks are called before a given function executes. +Unlike hooks, kareem stores hooks and other internal state in a separate +object, rather than relying on inheritance. Furthermore, kareem exposes +an `execPre()` function that allows you to execute your pre hooks when +appropriate, giving you more fine-grained control over your function hooks. + + +#### It runs without any hooks specified + +```javascript + + hooks.execPre('cook', null, function() { + done(); + }); + +``` + +#### It runs basic serial pre hooks + +pre hook functions take one parameter, a "done" function that you execute +when your pre hook is finished. + + +```javascript + + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + +``` + +#### It can run multipe pre hooks + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It can run fully synchronous pre hooks + +If your pre hook function takes no parameters, its assumed to be +fully synchronous. + + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It properly attaches context to pre hooks + +Pre save hook functions are bound to the second parameter to `execPre()` + + +```javascript + + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + +``` + +#### It can execute parallel (async) pre hooks + +Like the hooks module, you can declare "async" pre hooks - these take two +parameters, the functions `next()` and `done()`. `next()` passes control to +the next pre hook, but the underlying function won't be called until all +async pre hooks have called `done()`. + + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + +``` + +## post hooks + +#### It runs without any hooks specified + +```javascript + + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + +``` + +#### It executes with parameters passed in + +```javascript + + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +#### It can use synchronous post hooks + +```javascript + + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +## wrap() + +#### It wraps pre and post calls into one call + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + +``` + +## createWrapper() + +#### It wraps wrap() into a callable function + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + +``` + +## clone() + +#### It clones a Kareem object + +```javascript + + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + +``` + diff --git a/node_modules/mongoose/node_modules/kareem/docs.js b/node_modules/mongoose/node_modules/kareem/docs.js new file mode 100644 index 0000000..4a8d4c8 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/docs.js @@ -0,0 +1,37 @@ +var acquit = require('acquit'); + +var content = require('fs').readFileSync('./test/examples.test.js').toString(); +var blocks = acquit.parse(content); + +var mdOutput = + '# kareem\n\n' + + ' [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem)\n' + + ' [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem)\n\n' + + 'Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, ' + + 'meant to offer additional flexibility in allowing you to execute hooks ' + + 'whenever necessary, as opposed to simply wrapping a single function.\n\n' + + 'Named for the NBA\'s all-time leading scorer Kareem Abdul-Jabbar, known ' + + 'for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook)\n\n' + + '\n\n' + + '# API\n\n'; + +for (var i = 0; i < blocks.length; ++i) { + var describe = blocks[i]; + mdOutput += '## ' + describe.contents + '\n\n'; + mdOutput += describe.comments[0] ? + acquit.trimEachLine(describe.comments[0]) + '\n\n' : + ''; + + for (var j = 0; j < describe.blocks.length; ++j) { + var it = describe.blocks[j]; + mdOutput += '#### It ' + it.contents + '\n\n'; + mdOutput += it.comments[0] ? + acquit.trimEachLine(it.comments[0]) + '\n\n' : + ''; + mdOutput += '```javascript\n'; + mdOutput += ' ' + it.code + '\n'; + mdOutput += '```\n\n'; + } +} + +require('fs').writeFileSync('README.md', mdOutput); diff --git a/node_modules/mongoose/node_modules/kareem/gulpfile.js b/node_modules/mongoose/node_modules/kareem/gulpfile.js new file mode 100644 index 0000000..635bfc7 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/gulpfile.js @@ -0,0 +1,18 @@ +var gulp = require('gulp'); +var mocha = require('gulp-mocha'); +var config = require('./package.json'); +var jscs = require('gulp-jscs'); + +gulp.task('mocha', function() { + return gulp.src('./test/*'). + pipe(mocha({ reporter: 'dot' })); +}); + +gulp.task('jscs', function() { + return gulp.src('./index.js'). + pipe(jscs(config.jscsConfig)); +}); + +gulp.task('watch', function() { + gulp.watch('./index.js', ['jscs', 'mocha']); +}); diff --git a/node_modules/mongoose/node_modules/kareem/index.js b/node_modules/mongoose/node_modules/kareem/index.js new file mode 100644 index 0000000..b4b071b --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/index.js @@ -0,0 +1,229 @@ +'use strict'; + +function Kareem() { + this._pres = {}; + this._posts = {}; +} + +Kareem.prototype.execPre = function(name, context, callback) { + var pres = this._pres[name] || []; + var numPres = pres.length; + var numAsyncPres = pres.numAsync || 0; + var currentPre = 0; + var asyncPresLeft = numAsyncPres; + var done = false; + + if (!numPres) { + return process.nextTick(function() { + callback(null); + }); + } + + var next = function() { + if (currentPre >= numPres) { + return; + } + var pre = pres[currentPre]; + + if (pre.isAsync) { + pre.fn.call( + context, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + ++currentPre; + next.apply(context, arguments); + }, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (--numAsyncPres === 0) { + return callback(null); + } + }); + } else if (pre.fn.length > 0) { + var args = [function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return callback(null); + } + } + + next.apply(context, arguments); + }]; + if (arguments.length >= 2) { + for (var i = 1; i < arguments.length; ++i) { + args.push(arguments[i]); + } + } + pre.fn.apply(context, args); + } else { + pre.fn.call(context); + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return process.nextTick(function() { + callback(null); + }); + } + } + next(); + } + }; + + next(); +}; + +Kareem.prototype.execPost = function(name, context, args, callback) { + var posts = this._posts[name] || []; + var numPosts = posts.length; + var currentPost = 0; + + if (!numPosts) { + return process.nextTick(function() { + callback.apply(null, [null].concat(args)); + }); + } + + var next = function() { + var post = posts[currentPost]; + + if (post.length > args.length) { + post.apply(context, args.concat(function(error) { + if (error) { + return callback(error); + } + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + })); + } else { + post.apply(context, args); + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + } + }; + + next(); +}; + +Kareem.prototype.wrap = function(name, fn, context, args, useLegacyPost) { + var lastArg = (args.length > 0 ? args[args.length - 1] : null); + var _this = this; + + this.execPre(name, context, function(error) { + if (error) { + if (typeof lastArg === 'function') { + return lastArg(error); + } + return; + } + + var end = (typeof lastArg === 'function' ? args.length - 1 : args.length); + + fn.apply(context, args.slice(0, end).concat(function() { + if (arguments[0]) { + // Assume error + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + if (useLegacyPost && typeof lastArg === 'function') { + lastArg.apply(context, arguments); + } + + var argsWithoutError = Array.prototype.slice.call(arguments, 1); + _this.execPost(name, context, argsWithoutError, function() { + if (arguments[0]) { + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + return typeof lastArg === 'function' && !useLegacyPost ? + lastArg.apply(context, arguments) : + undefined; + }); + })); + }); +}; + +Kareem.prototype.createWrapper = function(name, fn, context) { + var _this = this; + return function() { + var args = Array.prototype.slice.call(arguments); + _this.wrap(name, fn, context, args); + }; +}; + +Kareem.prototype.pre = function(name, isAsync, fn, error) { + if (typeof arguments[1] !== 'boolean') { + error = fn; + fn = isAsync; + isAsync = false; + } + + this._pres[name] = this._pres[name] || []; + var pres = this._pres[name]; + + if (isAsync) { + pres.numAsync = pres.numAsync || 0; + ++pres.numAsync; + } + + pres.push({ fn: fn, isAsync: isAsync }); + + return this; +}; + +Kareem.prototype.post = function(name, fn) { + (this._posts[name] = this._posts[name] || []).push(fn); + return this; +}; + +Kareem.prototype.clone = function() { + var n = new Kareem(); + for (var key in this._pres) { + n._pres[key] = this._pres[key].slice(); + } + for (var key in this._posts) { + n._posts[key] = this._posts[key].slice(); + } + + return n; +}; + +module.exports = Kareem; diff --git a/node_modules/mongoose/node_modules/kareem/package.json b/node_modules/mongoose/node_modules/kareem/package.json new file mode 100644 index 0000000..302be1b --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/package.json @@ -0,0 +1,60 @@ +{ + "name": "kareem", + "version": "1.0.1", + "description": "Next-generation take on pre/post function hooks", + "main": "index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha ./test/*", + "test-travis": "./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/*" + }, + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/kareem.git" + }, + "devDependencies": { + "acquit": "0.0.3", + "gulp": "3.8.10", + "gulp-mocha": "2.0.0", + "gulp-jscs": "1.4.0", + "istanbul": "0.3.5", + "jscs": "1.9.0", + "mocha": "2.0.0" + }, + "jscsConfig": { + "preset": "airbnb", + "requireMultipleVarDecl": null, + "disallowMultipleVarDecl": true + }, + "author": { + "name": "Valeri Karpov", + "email": "val@karpov.io" + }, + "license": "Apache 2.0", + "gitHead": "69710887f85dee09afac690df770dd2febde7268", + "bugs": { + "url": "https://github.com/vkarpov15/kareem/issues" + }, + "homepage": "https://github.com/vkarpov15/kareem", + "_id": "kareem@1.0.1", + "_shasum": "7805d215bb53214ec3af969a1d0b1f17e3e7b95c", + "_from": "kareem@1.0.1", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "dist": { + "shasum": "7805d215bb53214ec3af969a1d0b1f17e3e7b95c", + "tarball": "http://registry.npmjs.org/kareem/-/kareem-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/kareem/-/kareem-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/kareem/test/examples.test.js b/node_modules/mongoose/node_modules/kareem/test/examples.test.js new file mode 100644 index 0000000..96d2fb8 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/test/examples.test.js @@ -0,0 +1,339 @@ +var assert = require('assert'); +var Kareem = require('../'); + +/* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define + * pre and post hooks: pre hooks are called before a given function executes. + * Unlike hooks, kareem stores hooks and other internal state in a separate + * object, rather than relying on inheritance. Furthermore, kareem exposes + * an `execPre()` function that allows you to execute your pre hooks when + * appropriate, giving you more fine-grained control over your function hooks. + */ +describe('pre hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPre('cook', null, function() { + done(); + }); + }); + + /* pre hook functions take one parameter, a "done" function that you execute + * when your pre hook is finished. + */ + it('runs basic serial pre hooks', function(done) { + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + }); + + it('can run multipe pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* If your pre hook function takes no parameters, its assumed to be + * fully synchronous. + */ + it('can run fully synchronous pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* Pre save hook functions are bound to the second parameter to `execPre()` + */ + it('properly attaches context to pre hooks', function(done) { + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + }); + + /* Like the hooks module, you can declare "async" pre hooks - these take two + * parameters, the functions `next()` and `done()`. `next()` passes control to + * the next pre hook, but the underlying function won't be called until all + * async pre hooks have called `done()`. + */ + it('can execute parallel (async) pre hooks', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + }); +}); + +describe('post hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + }); + + it('executes with parameters passed in', function(done) { + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); + + it('can use synchronous post hooks', function(done) { + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); +}); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps pre and post calls into one call', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + }); +}); + +describe('createWrapper()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps wrap() into a callable function', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + }); +}); + +describe('clone()', function() { + it('clones a Kareem object', function() { + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + }); +}); diff --git a/node_modules/mongoose/node_modules/kareem/test/post.test.js b/node_modules/mongoose/node_modules/kareem/test/post.test.js new file mode 100644 index 0000000..3df0ec5 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/test/post.test.js @@ -0,0 +1,46 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPost', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors', function(done) { + hooks.post('cook', function(eggs, callback) { + callback('error!'); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.equal('error!', error); + assert.ok(!eggs); + done(); + }); + }); + + it('multiple posts', function(done) { + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ifError(error); + assert.equal(4, eggs); + done(); + }); + }); +}); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/kareem/test/pre.test.js b/node_modules/mongoose/node_modules/kareem/test/pre.test.js new file mode 100644 index 0000000..4c1a212 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/test/pre.test.js @@ -0,0 +1,226 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPre', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors with multiple pres', function(done) { + var execed = {}; + + hooks.pre('cook', function(done) { + execed.first = true; + done(); + }); + + hooks.pre('cook', function(done) { + execed.second = true; + done('error!'); + }); + + hooks.pre('cook', function(done) { + execed.third = true; + done(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + done('other error!'); + }, + 10); + + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next()', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 15); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 5); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next() when already done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 25); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('returns correct error when async pre errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', function(next) { + execed.second = true; + setTimeout( + function() { + next('error!'); + }, + 15); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('lets async pres run when fully sync pres are done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('allows passing arguments to the next pre', function(done) { + var execed = {}; + + hooks.pre('cook', function(next) { + execed.first = true; + next(null, 'test'); + }); + + hooks.pre('cook', function(next, p) { + execed.second = true; + assert.equal(p, 'test'); + next(); + }); + + hooks.pre('cook', function(next, p) { + execed.third = true; + assert.ok(!p); + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(3, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.ok(execed.third); + done(); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/kareem/test/wrap.test.js b/node_modules/mongoose/node_modules/kareem/test/wrap.test.js new file mode 100644 index 0000000..3303961 --- /dev/null +++ b/node_modules/mongoose/node_modules/kareem/test/wrap.test.js @@ -0,0 +1,277 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles pre errors', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + }); + + it('handles pre errors when no callback defined', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + + setTimeout( + function() { + done(); + }, + 25); + }); + + it('handles errors in wrapped function', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback('error!'); + }, + obj, + args); + }); + + it('handles errors in post', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj, callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal('no', obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback(null, o); + }, + obj, + args); + }); + + it('works with no args', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('handles pre errors with no args', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles wrapped function errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback('error!'); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles post errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('can use legacy post behavior', function(done) { + var called = 0; + hooks.post('cook', function(callback) { + ++called; + callback(); + }); + + var args = [function(error) { + assert.equal(called, 0); + + setTimeout(function() { + assert.equal(called, 1); + done(); + }, 0); + }]; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + null, + args, + true); + }); +}); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/.travis.yml b/node_modules/mongoose/node_modules/mongodb/.travis.yml new file mode 100644 index 0000000..1b47243 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - 0.10 + - 0.12 +sudo: false +env: + - MONGODB_VERSION=2.2.x + - MONGODB_VERSION=2.4.x + - MONGODB_VERSION=2.6.x + - MONGODB_VERSION=3.0.x diff --git a/node_modules/mongoose/node_modules/mongodb/HISTORY.md b/node_modules/mongoose/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..0281389 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/HISTORY.md @@ -0,0 +1,1142 @@ +2.0.33 05-20-2015 +----------------- +- Bumped mongodb-core to 1.1.32. + +2.0.32 05-19-2015 +----------------- +- NODE-463 db.close immediately executes its callback. +- Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +- NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 05-08-2015 +----------------- +- NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 05-07-2015 +----------------- +- NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 05-07-2015 +----------------- +- NODE-444 Possible memory leak, too many listeners added. +- NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +- Bumped mongodb-core to 1.1.26. + +2.0.28 04-24-2015 +----------------- +- Bumped mongodb-core to 1.1.25 +- Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +- NODE-430 Cursor.count() opts argument masked by var opts = {} +- NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +- NODE-438 replaceOne is not returning the result.ops property as described in the docs. +- NODE-433 _read, pipe and write all open gridstore automatically if not open. +- NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +- NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +- Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +- Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 04-07-2015 +----------------- +- NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 04-07-2015 +----------------- +- Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +- NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 03-26-2015 +----------------- +- Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 03-24-2015 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +- Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +- NODE-380 Correctly return MongoError from toError method. +- Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +- NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +- Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +- Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +- Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +- Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +- NODE-376 Fixes issue - Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +- NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +- Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +- Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +- NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +- Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +- listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +- Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +- Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +- Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +- Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +- NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +- Added ~1.0 mongodb-tools module for test running. +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +- Fixed some MongoClient.connect options pass through issues and added test coverage. +- Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +- Bumped mongodb-core to 1.1.8. +- Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +- Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +- listCollections filters out index namespaces on < 2.8 correctly +- Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +- NODE-328 fixed db.open return when no callback available issue and added test. +- NODE-327 Refactored listCollections to return cursor to support 2.8. +- NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +- NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +- Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +- Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +- Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +- All classes are now strict (Issue #1233) +- NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +- Fixed recursion issues in debug logging due to JSON.stringify() +- Documentation fixes (Issue #1232, https://github.com/wsmoak) +- Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +- NODE-322 Finished up prototype refactoring of Db class. +- NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +- Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +- NODE-318 collection.update error while setting a function with serializeFunctions option. +- Documentation fixes. + +2.0.6 2014-11-14 +---------------- +- Refactored code to be prototype based instead of privileged methods. +- Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +- Implemented missing aspects of the CRUD specification. +- Fixed documentation issues. +- Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +- Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +- Minor fixes to documentation and generation of documentation. +- NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +- Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +- Made each rewind on each call allowing for re-using the cursor. +- Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +- NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +- NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +- Bumped mongodb-core to 1.0.2. +- Fixed bson module dependency issue by relying on the mongodb-core one. +- Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +- Dependency fix + +2.0.0 2014-10-07 +---------------- +- First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +- CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +- Cluster Management Spec compatible + +2.0.0-alpha1 2014-09-08 +----------------------- +- Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +- Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +- Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +- remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + - Might break some application +- Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +- MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +- Removed Grid class +- GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +- Cursor toArray and each resets and re-runs the cursor +- FindAndModify returns whole result document instead of just value +- Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +- Removed db.dereference method +- Removed db.cursorInfo method +- Removed db.stats method +- Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +- Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +- Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +- Fixed BSON and Kerberos compilation issues +- Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +- Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +- Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +- Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +- Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +- Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +- NODE-240 Operations on SSL connection hang on node 0.11.x +- NODE-235 writeResult is not being passed on when error occurs in insert +- NODE-229 Allow count to work with query hints +- NODE-233 collection.save() does not support fullResult +- NODE-244 Should parseError also emit a `disconnected` event? +- NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +- NODE-248 Crash with X509 auth +- NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +- Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +- NODE-205 correctly emit authenticate event +- NODE-210 ensure no undefined connection error when checking server state +- NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +- NODE-220 don't throw error if ensureIndex errors out in Gridstore +- Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +- Fixed test running filters +- Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +- False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +- Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +- Fixed parsing issue for w:0 in url parser when in connection string +- Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +- Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +- Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +- Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +- Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +- Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +- Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +- Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +- return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +- Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +- Removed leaking global variable (Issue #1174, https://github.com/dainis) +- MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +- Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +- Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +- Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +- Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +- A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +- Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +- Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +- Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +- Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +- Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +- Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +- Correctly emit joined event when primary change +- Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +- All node exceptions will no longer be caught if on('error') is defined +- Added X509 auth support +- Fix for MongoClient connection timeout issue (NODE-97) +- Pass through error messages from parseError instead of just text (Issue #1125) +- Close db connection on error (Issue #1128, https://github.com/benighted) +- Fixed documentation generation +- Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +- New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +- Insert/Update/Remove using new write commands when available +- Added support for new roles based API's in 2.6 for addUser/removeUser +- Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +- Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +- Support for OP_LOG_REPLAY flag (NODE-94) +- Fixes for SSL HA ping and discovery. +- Uses createIndexes if available for ensureIndex/createIndex +- Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +- Made CommandCursor behave as Readable stream. +- Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +- Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +- GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +- Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +- Refactored commands to all go through command function ensuring consistent command execution. +- Fixed issues where readPreferences where not correctly passed to mongos. +- Catch error == null and make err detection more prominent (NODE-130) +- Allow reads from arbiter for single server connection (NODE-117) +- Handle error coming back with no documents (NODE-130) +- Correctly use close parameter in Gridstore.write() (NODE-125) +- Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +- Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +- Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +- GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +- GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +- Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +- Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +- Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +- Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +- Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +- Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +- Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +- Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +- No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +- Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +- Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +- Ignore return commands that have no registered callback +- Made collection.count not use the db.command function +- Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +- Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +- Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +- Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +- Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +- Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +- BSON size checking now done pre serialization (Issue #1037) +- Added isConnected returns false when no connection Pool exists (Issue #1043) +- Unified command handling to ensure same handling (Issue #1041, #1042) +- Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +- Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +- Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +- Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +- Fixed issue with Kerberos authentication on Windows for re-authentication. +- Fixed Mongos failover behavior to correctly throw out old servers. +- Ensure stored queries/write ops are executed correctly after connection timeout +- Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +- Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +- Fixed bug with callback third parameter on some commands (Issue #1033) +- Fixed possible issue where killcursor command might leave hanging functions +- Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +- Throw error if dbName or collection name contains null character (at command level and at collection level) +- Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +- Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +- Add driver version to export (Issue #1021, https://github.com/aheckmann) +- Add text to readpreference obedient commands (Issue #1019) +- Drivers should check the query failure bit even on getmore response (Issue #1018) +- Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +- Support SASL PLAIN authentication (Issue #1009) +- Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +- Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +- Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +- Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +- Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +- Introduced write and read concerns for GridFS (Issue #996) +- Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +- Fixed issue with pool size on replicaset connections (Issue #1000) +- Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +- Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +- Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +- Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +- Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +- After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +- Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +- Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +- Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +- Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +- Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +- Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +- Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +- Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +- Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +- Applied auth before server instance is set as connected when single server connection +- Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +- Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +- Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +- Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +- Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +- Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +- Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +- Refactored test suite to speed up running of replicaset tests +- Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +- Corrected a slaveOk setting issue (Issue #906, #905) +- Fixed HA issue where ping's would not go to correct server on HA server connection failure. +- Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +- Fixed race condition in Cursor stream (NODE-31) +- Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +- Added support for maxMessageSizeBytes if available (DRIVERS-1) +- Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +- Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +- Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +- Fixed missing MongoErrors on some cursor methods (Issue #882) +- Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +- Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +- Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +- Added limit/skip options to Collection.count (Issue #870) +- Added applySkipLimit option to Cursor.count (Issue #870) +- Enabled ping strategy as default for Replicaset if none specified (Issue #876) +- Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +- Added fixes for handling type 2 binary due to PHP driver (Issue #864) +- Moved callBackStore to Base class to have single unified store (Issue #866) +- Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +- Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +- Only open a new HA socket when previous one dead (Issue #859, #857) +- Minor fixes + +1.2.9 2013-01-15 +---------------- +- Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +- Connection string with no db specified should default to admin db (Issue #848) +- Support port passed as string to Server class (Issue #844) +- Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +- Included toError wrapper code moved to utils.js file (Issue #839, #840) +- Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +- Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +- Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +- Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +- Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +- Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +- Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +- Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +- Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +- Rolled back batches as they hang in certain situations +- Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +- domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +- Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +- Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +- Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +- Fixed ssl regression, added more test coverage (Issue #800) +- Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +- Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +- Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +- Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +- Fix for journal write concern not correctly being passed under some circumstances. +- Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +- Fix for double callback on insert with w:0 specified (Issue #783) +- Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +- Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +- Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +- Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +- Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +- Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +- Force correct setting of read_secondary based on the read preference (Issue #741) +- If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +- noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +- Mongos connection with auth not working (Issue #737) +- Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +- new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + - open/close/db/connect methods implemented +- Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +- Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +- Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +- fix Admin.serverStatus (Issue #723, https://github.com/Contra) +- logging on connection open/close(Issue #721, https://github.com/asiletto) +- more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +- Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +- Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +- Cleanup of non-closing connections (Issue #706) +- More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +- Set keepalive on as default, override if not needed +- Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +- Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +- Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +- Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +- Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +- Proper stopping of strategy on replicaset stop +- Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +- Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +- Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +- Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +- Fix for eval on replicaset Issue #684 +- Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +- Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +- Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +- Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +- Added exhaust option for find for feature completion (not recommended for normal use) +- Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +- Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +- Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +- Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +- Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +- Fix gridfs readstream (Issue #607, https://github.com/tedeh). +- Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +- Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +- Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +- Cleanup map reduce (Issue #614, https://github.com/aheckmann). +- Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +- Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +- Date identification handled correctly in bson js parser when running in vm context. +- Documentation updates +- GridStore filename not set on read (Issue #621) +- Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +- Added support for awaitdata for tailable cursors (Issue #624) +- Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +- Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + - ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +- Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +- Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +- Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +- Fixed auth to work better when multiple connections are involved. +- Default connection pool size increased to 5 connections. +- Fixes for the ReadStream class to work properly with 0.8 of Node.js +- Added explain function support to aggregation helper +- Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +- Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +- Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +- Fixed Always emit db events (Issue #657) +- Close event not correctly resets DB openCalled variable to allow reconnect +- Added open event on connection established for replicaset, mongos and server +- Much faster BSON C++ parser thanks to Lucasfilm Singapore. +- Refactoring of replicaset connection logic to simplify the code. +- Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +- Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +- Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +- Passing back getLastError object as 3rd parameter on findAndModify command. +- Fixed a bunch of performance regressions in objectId and cursor. +- Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +- Fixes to handling of failover on server error +- Only emits error messages if there are error listeners to avoid uncaught events +- Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +- _id=0 is being turned into an ObjectID (Issue #551) +- fix for error in GridStore write method (Issue #559) +- Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +- Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +- Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +- Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +- Connection pools handles closing themselves down and clearing the state +- Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +- Returning update status document at the end of the callback for updates, (Issue #569) +- Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +- Stats not returned from map reduce with inline results (Issue #542) +- Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +- Streaming large files from GridFS causes truncation (Issue #540) +- Make callback type checks agnostic to V8 context boundaries (Issue #545) +- Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +- Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +- BSON parser is externalized in it's own repository, currently using git master +- Fixes for Replicaset connectivity issue (Issue #537) +- Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +- Removed SimpleEmitter and replaced with standard EventEmitter +- GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +- Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +- Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +- Fixed memory leak in C++ bson parser (Issue #526) +- Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +- Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + - Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/node_modules/mongoose/node_modules/mongodb/LICENSE b/node_modules/mongoose/node_modules/mongodb/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/Makefile b/node_modules/mongoose/node_modules/mongodb/Makefile new file mode 100644 index 0000000..b4575ca --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/Makefile @@ -0,0 +1,14 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + cp -R ./docs/history-header.md ./docs/content/meta/release-notes.md + more ./HISTORY.md >> ./docs/content/meta/release-notes.md + pandoc docs/layouts/partials/welcome.md -o docs/layouts/partials/welcome.html + hugo -s docs/ -d ../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/node_modules/mongoose/node_modules/mongodb/README.md b/node_modules/mongoose/node_modules/mongodb/README.md new file mode 100644 index 0000000..374e30a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/README.md @@ -0,0 +1,322 @@ +[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) + +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The MongoDB driver is the high level part of the 2.0 or higher MongoDB driver and is meant for end users. + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| api-doc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +QuickStart +========== +The quick start guide will show you how to setup a simple application using node.js and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. + +Create the package.json file +---------------------------- +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project + +``` +npm init +``` + +Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + +``` +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb": "~2.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +Connecting to MongoDB +--------------------- +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server and the database **myproject**. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.close(); +}); +``` + +Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. + +Let's Add some code to show the different CRUD operations available. + +Inserting a Document +-------------------- +Let's create a function that will insert some documents for us. + +```js +var insertDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.insert([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the document collection"); + callback(result); + }); +} +``` + +The insert command will return a results object that contains several fields that might be useful. + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + db.close(); + }); +}); +``` + +We can now run the update **app.js** file. + +``` +node app.js +``` + +You should see the following output after running the **app.js** file. + +``` +Connected correctly to server +Inserted 3 documents into the document collection +``` + +Updating a document +------------------- +Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. + +```js +var updateDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.update({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + db.close(); + }); + }); +}); +``` + +Remove a document +----------------- +Next lets remove the document where the field **a** equals to **3**. + +```js +var removeDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.remove({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +This will remove the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient.connect** callback function. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + db.close(); + }); + }); + }); +}); +``` + +Finally let's retrieve all the documents using a simple find. + +Find All Documents +------------------ +We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. + +```js +var findDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + assert.equal(2, docs.length); + console.log("Found the following records"); + console.dir(docs); + callback(docs); + }); +} +``` + +This query will return all the documents in the **documents** collection. Since we removed a document the total documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + findDocuments(db, function() { + db.close(); + }); + }); + }); + }); +}); +``` + +This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org/) + * [Read about Schemas](http://learnmongodbthehardway.com/) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/node_modules/mongoose/node_modules/mongodb/conf.json b/node_modules/mongoose/node_modules/mongodb/conf.json new file mode 100644 index 0000000..125c7df --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/conf.json @@ -0,0 +1,65 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/functional/operation_example_tests.js", + "lib/admin.js", + "lib/collection.js", + "lib/cursor.js", + "lib/aggregation_cursor.js", + "lib/command_cursor.js", + "lib/db.js", + "lib/mongo_client.js", + "lib/mongos.js", + "lib/read_preference.js", + "lib/replset.js", + "lib/server.js", + "lib/bulk/common.js", + "lib/bulk/ordered.js", + "lib/bulk/unordered.js", + "lib/gridfs/grid_store.js", + "node_modules/mongodb-core/lib/connection/logger.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/index.js new file mode 100644 index 0000000..a1df2e2 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/index.js @@ -0,0 +1,39 @@ +// Core module +var core = require('mongodb-core'); + +// Set up the connect function +var connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; + +// Actual driver classes exported +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/server'); +connect.ReplSet = require('./lib/replset'); +connect.Mongos = require('./lib/mongos'); +connect.ReadPreference = require('./lib/read_preference'); +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.Cursor = require('./lib/cursor'); + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; + +// Add connect method +connect.connect = connect; +// Set our exports to be the connect function +module.exports = connect; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/admin.js b/node_modules/mongoose/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..a0c898a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/admin.js @@ -0,0 +1,347 @@ +"use strict"; + +var toError = require('./utils').toError; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Use the admin database for the operation + * var adminDb = db.admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +var Admin = function(db, topology) { + if(!(this instanceof Admin)) return new Admin(db, topology); + var self = this; + + // Internal state + this.s = { + db: db + , topology: topology + } +} + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.command = function(command, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Execute a command + this.s.db.executeDbAdminCommand(command, options, function(err, doc) { + return callback != null ? callback(err, doc) : null; + }); +} + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.buildInfo = function(callback) { + this.serverInfo(callback); +} + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.serverInfo = function(callback) { + this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err != null) return callback(err, null); + return callback(null, doc); + }); +} + +/** + * Retrieve this db's server status. + * + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.serverStatus = function(callback) { + var self = this; + + this.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { + if(err == null && doc.ok === 1) { + callback(null, doc); + } else { + if(err) return callback(err, false); + return callback(toError(doc), false); + } + }); +}; + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.profilingLevel = function(callback) { + var self = this; + + this.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) { + var was = doc.was; + if(was == 0) return callback(null, "off"); + if(was == 1) return callback(null, "slow_only"); + if(was == 2) return callback(null, "all"); + return callback(new Error("Error: illegal profiling level value " + was), null); + } else { + err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + } + }); +}; + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.ping = function(options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + this.s.db.executeDbAdminCommand({ping: 1}, args.pop()); +} + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.authenticate = function(username, password, callback) { + this.s.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) { + return callback(err, doc); + }) +} + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.logout = function(callback) { + this.s.db.logout({authdb: 'admin'}, function(err, doc) { + return callback(err, doc); + }) +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.addUser = function(username, password, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + // Set the db name to admin + options.dbName = 'admin'; + // Add user + this.s.db.addUser(username, password, options, function(err, doc) { + return callback(err, doc); + }) +} + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {Admin~resultCallback} callback The command result callback + * @return {null} + */ +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + options.dbName = 'admin'; + + this.s.db.removeUser(username, options, function(err, doc) { + return callback(err, doc); + }) +} + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Admin~resultCallback} callback The command result callback. + * @return {null} + */ +Admin.prototype.setProfilingLevel = function(level, callback) { + var self = this; + var command = {}; + var profile = 0; + + if(level == "off") { + profile = 0; + } else if(level == "slow_only") { + profile = 1; + } else if(level == "all") { + profile = 2; + } else { + return callback(new Error("Error: illegal profiling level value " + level)); + } + + // Set up the profile number + command['profile'] = profile; + + this.s.db.executeDbAdminCommand(command, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) + return callback(null, level); + return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + }); +}; + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Admin~resultCallback} callback The command result callback. + * @return {null} + */ +Admin.prototype.profilingInfo = function(callback) { + try { + this.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); + } catch (err) { + return callback(err, null); + } +}; + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options=null] Optional settings. + * @param {Admin~resultCallback} callback The command result callback. + * @return {null} + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + var self = this; + var command = {validate: collectionName}; + var keys = Object.keys(options); + + // Decorate command with extra options + for(var i = 0; i < keys.length; i++) { + if(options.hasOwnProperty(keys[i])) { + command[keys[i]] = options[keys[i]]; + } + } + + this.s.db.command(command, function(err, doc) { + if(err != null) return callback(err, null); + + if(doc.ok === 0) + return callback(new Error("Error with validate command"), null); + if(doc.result != null && doc.result.constructor != String) + return callback(new Error("Error with validation data"), null); + if(doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error("Error: invalid collection " + collectionName), null); + if(doc.valid != null && !doc.valid) + return callback(new Error("Error: invalid collection " + collectionName), null); + + return callback(null, doc); + }); +}; + +/** + * List the available databases + * + * @param {Admin~resultCallback} callback The command result callback. + * @return {null} + */ +Admin.prototype.listDatabases = function(callback) { + this.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) { + if(err != null) return callback(err, null); + return callback(null, doc); + }); +} + +/** + * Get ReplicaSet status + * + * @param {Admin~resultCallback} callback The command result callback. + * @return {null} + */ +Admin.prototype.replSetGetStatus = function(callback) { + var self = this; + + this.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, doc); + if(err) return callback(err, false); + return callback(toError(doc), false); + }); +}; + +module.exports = Admin; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..2ab3043 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,396 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + } +} + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +// Extend the Cursor +for(var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw new MongoError("Cursor is closed"); + if(typeof value != 'number') throw new MongoError("batchSize requires an integer"); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({$geoNear: document}); + return this; +} + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({$group: document}); + return this; +} + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({$limit: value}); + return this; +} + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({$match: document}); + return this; +} + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({$out: destination}); + return this; +} + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({$project: document}); + return this; +} + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({$redact: document}); + return this; +} + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({$skip: value}); + return this; +} + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({$sort: document}); + return this; +} + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({$unwind: field}); + return this; +} + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Set the new batchSize of the cursor + * @function AggregationCursor.prototype.setBatchSize + * @param {number} value The new batchSize for the cursor + * @return {null} + */ + +/** + * Get the batchSize of the cursor + * @function AggregationCursor.prototype.batchSize + * @param {number} value The current batchSize for the cursor + * @return {null} + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {null} + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {null} + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..d6f6dc5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,393 @@ +"use strict"; + +var utils = require('../utils'); + +// Error codes +var UNKNOWN_ERROR = 8; +var INVALID_BSON_ERROR = 22; +var WRITE_CONCERN_ERROR = 64; +var MULTIPLE_ERROR = 65; + +// Insert types +var INSERT = 1; +var UPDATE = 2; +var REMOVE = 3 + + +// Get write concern +var writeConcern = function(target, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + target.writeConcern = options; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } + + return target +} + +/** + * Helper function to define properties + * @ignore + */ +var defineReadOnlyProperty = function(self, name, value) { + Object.defineProperty(self, name, { + enumerable: true + , get: function() { + return value; + } + }); +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +var Batch = function(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; +} + +/** + * Wraps a legacy operation so we can correctly rewrite it's error + * @ignore + */ +var LegacyOp = function(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {boolean} ok Did bulk operation correctly execute + * @property {number} nInserted number of inserted documents + * @property {number} nUpdated number of documents updated logically + * @property {number} nUpserted Number of upserted documents + * @property {number} nModified Number of documents updated physically on disk + * @property {number} nRemoved Number of removed documents + * @return {BulkWriteResult} a BulkWriteResult instance + */ +var BulkWriteResult = function(bulkResult) { + defineReadOnlyProperty(this, "ok", bulkResult.ok); + defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); + defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); + defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); + defineReadOnlyProperty(this, "nModified", bulkResult.nModified); + defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); + + /** + * Return an array of inserted ids + * + * @return {object[]} + */ + this.getInsertedIds = function() { + return bulkResult.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + this.getUpsertedIds = function() { + return bulkResult.upserted; + } + + /** + * Return the upserted id at position x + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + this.getUpsertedIdAt = function(index) { + return bulkResult.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + this.getRawResponse = function() { + return bulkResult; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + this.hasWriteErrors = function() { + return bulkResult.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + this.getWriteErrorCount = function() { + return bulkResult.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @return {WriteError} + */ + this.getWriteErrorAt = function(index) { + if(index < bulkResult.writeErrors.length) { + return bulkResult.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + this.getWriteErrors = function() { + return bulkResult.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + this.getLastOp = function() { + return bulkResult.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + this.getWriteConcernError = function() { + if(bulkResult.writeConcernErrors.length == 0) { + return null; + } else if(bulkResult.writeConcernErrors.length == 1) { + // Return the error + return bulkResult.writeConcernErrors[0]; + } else { + + // Combine the errors + var errmsg = ""; + for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { + var err = bulkResult.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if(i == 0) errmsg = errmsg + " and "; + } + + return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); + } + } + + this.toJSON = function() { + return bulkResult; + } + + this.toString = function() { + return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; + } + + this.isOk = function() { + return bulkResult.ok == 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteConcernError = function(err) { + if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + this.toJSON = function() { + return {code: err.code, errmsg: err.errmsg}; + } + + this.toString = function() { + return "WriteConcernError(" + err.errmsg + ")"; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {number} index Write concern error original bulk operation index. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteError = function(err) { + if(!(this instanceof WriteError)) return new WriteError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "index", err.index); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + // + // Define access methods + this.getOperation = function() { + return err.op; + } + + this.toJSON = function() { + return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; + } + + this.toString = function() { + return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if(err) { + result = err; + } else if(result && result.result) { + result = result.result; + } else if(result == null) { + return; + } + + // Do we have a top level error stop processing and return + if(result.ok == 0 && bulkResult.ok == 1) { + bulkResult.ok = 0; + // bulkResult.error = utils.toError(result); + var writeError = { + index: 0 + , code: result.code || 0 + , errmsg: result.message + , op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if(result.ok == 0 && bulkResult.ok == 0) { + return; + } + + // Add lastop if available + if(result.lastOp) { + bulkResult.lastOp = result.lastOp; + } + + // If we have an insert Batch type + if(batch.batchType == INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if(batch.batchType == REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + var nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if(Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for(var i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex + , _id: result.upserted[i]._id + }); + } + } else if(result.upserted) { + + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex + , _id: result.upserted + }); + } + + // If we have an update Batch type + if(batch.batchType == UPDATE && result.n) { + var nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if(typeof nModified == 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if(Array.isArray(result.writeErrors)) { + for(var i = 0; i < result.writeErrors.length; i++) { + + var writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index + , code: result.writeErrors[i].code + , errmsg: result.writeErrors[i].errmsg + , op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if(result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +// +// Clone the options +var cloneOptions = function(options) { + var clone = {}; + var keys = Object.keys(options); + for(var i = 0; i < keys.length; i++) { + clone[keys[i]] = options[keys[i]]; + } + + return clone; +} + +// Exports symbols +exports.BulkWriteResult = BulkWriteResult; +exports.WriteError = WriteError; +exports.Batch = Batch; +exports.LegacyOp = LegacyOp; +exports.mergeBatchResults = mergeBatchResults; +exports.cloneOptions = cloneOptions; +exports.writeConcern = writeConcern; +exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; +exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; +exports.MULTIPLE_ERROR = MULTIPLE_ERROR; +exports.UNKNOWN_ERROR = UNKNOWN_ERROR; +exports.INSERT = INSERT; +exports.UPDATE = UPDATE; +exports.REMOVE = REMOVE; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..32380a0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,470 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. + */ +var FindOperatorsOrdered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +FindOperatorsOrdered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.deleteOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.delete = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; + +// Add to internal list of documents +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Reset the current size trackers + _self.s.currentBatchSize = 0; + _self.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + _self.s.currentBatchSize = _self.s.currentBatchSize + 1; + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + } + + if(docType == common.INSERT) { + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentBatch.operations.push(document) + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Return self + return _self; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +function OrderedBulkOperation(topology, collection, options) { + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + var self = this; + var executed = false; + + // Current item + var currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Namespace for the operation + var namespace = collection.collectionName; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; + var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; + + // Get the capabilities + var capabilities = topology.capabilities(); + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Current batch + var currentBatch = null; + var currentIndex = 0; + var currentBatchSize = 0; + var currentBatchSizeBytes = 0; + var batches = []; + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentBatch: null + , currentIndex: 0 + , currentBatchSize: 0 + , currentBatchSizeBytes: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Capabilities + , capabilities: capabilities + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + } +} + +OrderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +OrderedBulkOperation.prototype.insert = function(document) { + if(document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +OrderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsOrdered(this); +} + +Object.defineProperty(OrderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// +// Execute next write command in a chain +var executeCommands = function(self, callback) { + if(self.s.batches.length == 0) { + return callback(null, new BulkWriteResult(self.s.bulkResult)); + } + + // Ordered execution of the command + var batch = self.s.batches.shift(); + + var resultHandler = function(err, result) { + // If we have and error + if(err) err.ok = 0; + // Merge the results together + var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); + if(mergeResult != null) { + return callback(null, new BulkWriteResult(self.s.bulkResult)); + } + + // If we are ordered and have errors and they are + // not all replication errors terminate the operation + if(self.s.bulkResult.writeErrors.length > 0) { + return callback(self.s.bulkResult.writeErrors[0], new BulkWriteResult(self.s.bulkResult)); + } + + // Execute the next command in line + executeCommands(self, callback); + } + + var finalOptions = {ordered: true} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +/** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} callback The result callback + * @throws {MongoError} + * @return {null} + */ +OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + if(this.s.executed) throw new toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute the commands + return executeCommands(this, callback); +} + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeOrderedBulkOp = function(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +module.exports = initializeOrderedBulkOp; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..4f1d8a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,482 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. + */ +var FindOperatorsUnordered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.removeOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.remove = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// +// Add to the operations list +// +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Holds the current batch + _self.s.currentBatch = null; + // Get the right type of batch + if(docType == common.INSERT) { + _self.s.currentBatch = _self.s.currentInsertBatch; + } else if(docType == common.UPDATE) { + _self.s.currentBatch = _self.s.currentUpdateBatch; + } else if(docType == common.REMOVE) { + _self.s.currentBatch = _self.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.operations.push(document); + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if(docType == common.INSERT) { + _self.s.currentInsertBatch = _self.s.currentBatch; + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } else if(docType == common.UPDATE) { + _self.s.currentUpdateBatch = _self.s.currentBatch; + } else if(docType == common.REMOVE) { + _self.s.currentRemoveBatch = _self.s.currentBatch; + } + + // Update current batch size + _self.s.currentBatch.size = _self.s.currentBatch.size + 1; + _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; + + // Return self + return _self; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +var UnorderedBulkOperation = function(topology, collection, options) { + options = options == null ? {} : options; + + // Contains reference to self + var self = this; + // Get the namesspace for the write operations + var namespace = collection.collectionName; + // Used to mark operation as executed + var executed = false; + + // Current item + // var currentBatch = null; + var currentOp = null; + var currentIndex = 0; + var batches = []; + + // The current Batches for the different operations + var currentInsertBatch = null; + var currentUpdateBatch = null; + var currentRemoveBatch = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Get the capabilities + var capabilities = topology.capabilities(); + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; + var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentInsertBatch: null + , currentUpdateBatch: null + , currentRemoveBatch: null + , currentBatch: null + , currentIndex: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Capabilities + , capabilities: capabilities + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + } +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +UnorderedBulkOperation.prototype.insert = function(document) { + if(document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsUnordered} + */ +UnorderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsUnordered(this); +} + +Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +UnorderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +// +// Execute the command +var executeBatch = function(self, batch, callback) { + var finalOptions = {ordered: false} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + var resultHandler = function(err, result) { + // If we have and error + if(err) err.ok = 0; + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +// +// Execute all the commands +var executeBatches = function(self, callback) { + var numberOfCommandsToExecute = self.s.batches.length; + // Execute over all the batches + for(var i = 0; i < self.s.batches.length; i++) { + executeBatch(self, self.s.batches[i], function(err, result) { + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if(numberOfCommandsToExecute == 0) { + var error = self.s.bulkResult.writeErrors.length > 0 ? self.s.bulkResult.writeErrors[0] : null; + callback(error, new BulkWriteResult(self.s.bulkResult)); + } + }); + } +} + +/** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} callback The result callback + * @throws {MongoError} + * @return {null} + */ +UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + if(this.s.executed) throw toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute batches + return executeBatches(this, function(err, result) { + callback(err, result); + }); +} + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeUnorderedBulkOp = function(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +module.exports = initializeUnorderedBulkOp; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/collection.js b/node_modules/mongoose/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..47bd50e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/collection.js @@ -0,0 +1,2097 @@ +"use strict"; + +var checkCollectionName = require('./utils').checkCollectionName + , ObjectID = require('mongodb-core').BSON.ObjectID + , Long = require('mongodb-core').BSON.Long + , Code = require('mongodb-core').BSON.Code + , f = require('util').format + , AggregationCursor = require('./aggregation_cursor') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone + , isObject = require('./utils').isObject + , toError = require('./utils').toError + , normalizeHintField = require('./utils').normalizeHintField + , handleCallback = require('./utils').handleCallback + , decorateCommand = require('./utils').decorateCommand + , formattedOrderClause = require('./utils').formattedOrderClause + , ReadPreference = require('./read_preference') + , CoreReadPreference = require('mongodb-core').ReadPreference + , CommandCursor = require('./command_cursor') + , Cursor = require('./cursor') + , unordered = require('./bulk/unordered') + , ordered = require('./bulk/ordered'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +var Collection = function(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + var self = this; + // Unpack variables + var internalHint = null; + var opts = options != null && ('object' === typeof options) ? options : {}; + var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; + var raw = options == null || options.raw == null ? db.raw : options.raw; + var readPreference = null; + var collectionHint = null; + var namespace = f("%s.%s", dbName, name); + + // Assign the right collection level readPreference + if(options && options.readPreference) { + readPreference = options.readPreference; + } else if(db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null + ? ObjectID + : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory + // Db + , db: db + // Topology + , topology: topology + // dbName + , dbName: dbName + // Options + , options: options + // Namespace + , namespace: namespace + // Read preference + , readPreference: readPreference + // Raw + , raw: raw + // SlaveOK + , slaveOk: slaveOk + // Serialize functions + , serializeFunctions: serializeFunctions + // internalHint + , internalHint: internalHint + // collectionHint + , collectionHint: collectionHint + // Name + , name: name + } +} + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, get: function() { return this.s.name; } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, get: function() { return this.s.namespace; } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, "hint", { + enumerable: true + , get: function () { return this.s.collectionHint; } + , set: function (v) { this.s.collectionHint = normalizeHintField(v); } +}); + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} query The cursor query object. + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = function() { + var options + , args = Array.prototype.slice.call(arguments, 0) + , has_callback = typeof args[args.length - 1] === 'function' + , has_weird_callback = typeof args[0] === 'function' + , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) + , len = args.length + , selector = len >= 1 ? args[0] : {} + , fields = len >= 2 ? args[1] : undefined; + + if(len === 1 && has_weird_callback) { + // backwards compat for callback?, options case + selector = {}; + options = args[0]; + } + + if(len === 2 && !Array.isArray(fields)) { + var fieldKeys = Object.keys(fields); + var is_option = false; + + for(var i = 0; i < fieldKeys.length; i++) { + if(testForFields[fieldKeys[i]] != null) { + is_option = true; + break; + } + } + + if(is_option) { + options = fields; + fields = undefined; + } else { + options = {}; + } + } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { + var newFields = {}; + // Rewrite the array + for(var i = 0; i < fields.length; i++) { + newFields[fields[i]] = 1; + } + // Set the fields + fields = newFields; + } + + if(3 === len) { + options = args[2]; + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + var object = selector; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Validate correctness of the field selector + var object = fields; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { + selector = {_id:selector}; + } + + // If it's a serialized fields field we need to just let it through + // user be warned it better be good + if(options && options.fields && !(Buffer.isBuffer(options.fields))) { + fields = {}; + + if(Array.isArray(options.fields)) { + if(!options.fields.length) { + fields['_id'] = 1; + } else { + for (var i = 0, l = options.fields.length; i < l; i++) { + fields[options.fields[i]] = 1; + } + } + } else { + fields = options.fields; + } + } + + if (!options) options = {}; + + var newOptions = {}; + // Make a shallow copy of options + for (var key in options) { + newOptions[key] = options[key]; + } + + // Unpack options + newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; + newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; + newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions = getReadPreference(this, newOptions, this.s.db, this); + // Set slave ok to true if read preference different from primary + if(newOptions.readPreference != null + && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if(selector != null && typeof selector != 'object') { + throw new MongoError("query selector must be an object"); + } + + // Build the find command + var findCommand = { + find: this.s.namespace + , limit: newOptions.limit + , skip: newOptions.skip + , query: selector + } + + // Ensure we use the right await data option + if(typeof newOptions.awaitdata == 'boolean') { + newOptions.awaitData = newOptions.awaitdata + }; + + // Translate to new command option noCursorTimeout + if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + // Merge in options to command + for(var name in newOptions) { + if(newOptions[name] != null) findCommand[name] = newOptions[name]; + } + + // Format the fields + var formatFields = function(fields) { + var object = {}; + if(Array.isArray(fields)) { + for(var i = 0; i < fields.length; i++) { + if(Array.isArray(fields[i])) { + object[fields[i][0]] = fields[i][1]; + } else { + object[fields[i][0]] = 1; + } + } + } else { + object = fields; + } + + return object; + } + + // Special treatment for the fields selector + if(fields) findCommand.fields = formatFields(fields); + + // Add db object to the new options + newOptions.db = this.s.db; + + // Set raw if available at collection level + if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; + + // Sort options + if(findCommand.sort) + findCommand.sort = formattedOrderClause(findCommand.sort); + + // Create the cursor + if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); + return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); +} + +/** + * Inserts a single document into MongoDB. + * @method + * @param {object} doc Document to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.insertOne = function(doc, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(Array.isArray(doc)) return callback(new MongoError('doc parameter must be an object')); + insertDocuments(this, [doc], options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if(callback) callback(null, r); + }); +} + +/** + * Inserts an array of documents into MongoDB. + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.insertMany = function(docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(!Array.isArray(docs)) return callback(new MongoError('docs parameter must be an array of documents')); + insertDocuments(this, docs, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.insertedCount = r.result.n; + var ids = []; + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id) ids.push(docs[i]._id); + } + r.insertedIds = ids; + if(callback) callback(null, r); + }); +} + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Collection~bulkWriteOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(typeof callback != 'function') throw new MongoError("bulkWrite must have a callback function specified"); + if(!Array.isArray(operations)) throw new MongoError("operations must be an array of documents"); + var bulk = options.ordered == true || options.ordered == null ? this.initializeOrderedBulkOp() : this.initializeUnorderedBulkOp(); + + // for each op go through and add to the bulk + for(var i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + + // Final options for write concern + var finalOptions = writeConcern(shallowClone(options), this.s.db, this, options); + var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + + // Execute the bulk + bulk.execute(writeCon, function(err, r) { + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Inserted documents + var inserted = r.getInsertedIds(); + // Map inserted ids + for(var i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + var upserted = r.getUpsertedIds(); + // Map upserted ids + for(var i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Return the results + callback(null, r); + }); +} + +var insertDocuments = function(self, docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; + + // If keep going set unordered + if(options.keepGoing == true) finalOptions.ordered = false; + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Add _id if not specified + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + + // File inserts + self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = function(docs, options, callback) { + return insertDocuments(this, docs, options, callback); +} + +/** + * Update a single document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + // Set single document update + options.multi = false; + // Execute update + updateDocuments(this, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +/** + * Replace a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.replaceOne = function(filter, update, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + // Set single document update + options.multi = false; + // Execute update + updateDocuments(this, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.ops = [update]; + if(callback) callback(null, r); + }); +} + +/** + * Update multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + // Set single document update + options.multi = true; + // Execute update + updateDocuments(this, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +var updateDocuments = function(self, selector, document, options, callback) { + if('function' === typeof options) callback = options, options = null; + if(options == null) options = {}; + if(!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); + if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Execute the operation + var op = {q: selector, u: document}; + if(options.upsert) op.upsert = true; + if(options.multi) op.multi = true; + + // Update options + self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {Collection~writeOpCallback} callback The command result callback + * @throws {MongoError} + * @return {null} + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = function(selector, document, options, callback) { + return updateDocuments(this, selector, document, options, callback); +} + +/** + * Delete a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + options.single = true; + removeDocuments(this, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +/** + * Delete multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + options.single = false; + removeDocuments(this, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +var removeDocuments = function(self, selector, options, callback) { + if(typeof options == 'function') { + callback = options, options = {}; + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // If selector is null set empty + if(selector == null) selector = {}; + + // Build the op + var op = {q: selector, limit: 0}; + if(options.single) op.limit = 1; + + // Execute the remove + self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = function(selector, options, callback) { + return removeDocuments(this, selector, options, callback); +} + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.save = function(doc, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), this.s.db, this, options); + // Establish if we need to perform an insert or update + if(doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(this, {_id: doc._id}, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(this, [doc], options, function(err, r) { + if(callback == null) return; + if(doc == null) return handleCallback(callback, null, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, r); + }); +} + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options=null] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan=null] Limit the number of items to scan. + * @param {number} [options.min=null] Set index bounds. + * @param {number} [options.max=null] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.findOne = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + var cursor = this.find.apply(this, args).limit(-1).batchSize(1); + + // Return the item + cursor.next(function(err, item) { + if(err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Collection~collectionResultCallback} callback The results callback + * @return {null} + */ +Collection.prototype.rename = function(newName, opt, callback) { + var self = this; + if(typeof opt == 'function') callback = opt, opt = {}; + // Check the collection name + checkCollectionName(newName); + // Build the command + var renameCollection = f("%s.%s", this.s.dbName, this.s.name); + var toCollection = f("%s.%s", this.s.dbName, newName); + var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; + var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; + + // Execute against admin + self.s.db.admin().command(cmd, opt, function(err, doc) { + if(err) return handleCallback(callback, err, null); + // We have an error + if(doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); + } catch(err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Collection~resultCallback} callback The results callback + * @return {null} + */ +Collection.prototype.drop = function(callback) { + this.s.db.dropCollection(this.s.name, callback); +} + +/** + * Returns the options of the collection. + * + * @method + * @param {Collection~resultCallback} callback The results callback + * @return {null} + */ +Collection.prototype.options = function(callback) { + var self = this; + this.s.db.listCollections({name: this.s.name}).toArray(function(err, collections) { + if(err) return handleCallback(callback, err); + if(collections.length == 0) return handleCallback(callback, new MongoError(f("collection %s not found", self.s.namespace))); + handleCallback(callback, err, collections[0].options || null); + }); +} + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Collection~resultCallback} callback The results callback + * @return {null} + */ +Collection.prototype.isCapped = function(callback) { + this.options(function(err, document) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, document && document.capped); + }); +} + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + // Execute create index + this.s.db.createIndex(this.s.name, fieldOrSpec, options, callback); +} + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.createIndexes = function(indexSpecs, callback) { + // Ensure we generate the correct name if the parameter is not set + for(var i = 0; i < indexSpecs.length; i++) { + if(indexSpecs[i].name == null) { + var keys = []; + + for(var name in indexSpecs[i].key) { + keys.push(f('%s_%s', name, indexSpecs[i].key[name])); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + // Execute the index + this.s.db.command({ + createIndexes: this.s.name, indexes: indexSpecs + }, callback); +} + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + + // Delete index command + var cmd = {'deleteIndexes':this.s.name, 'index':indexName}; + + // Execute command + this.s.db.command(cmd, options, function(err, result) { + if(typeof callback != 'function') return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +/** + * Drops all indexes from this collection. + * @method + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.dropIndexes = function(callback) { + this.dropIndex('*', function (err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.reIndex = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Reindex + var cmd = {'reIndex':this.s.name}; + + // Execute the command + this.s.db.command(cmd, options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = shallowClone(options); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + + // We have a list collections command + if(this.s.db.serverConfig.capabilities().hasListIndexesCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + return this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); + } + + // Get the namespace + var ns = f('%s.system.indexes', this.s.dbName); + // Get the query + return this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + this.s.db.ensureIndex(this.s.name, fieldOrSpec, options, callback); +} + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.indexExists = function(indexes, callback) { + this.indexInformation(function(err, indexInformation) { + // If we have an error return + if(err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for(var i = 0; i < indexes.length; i++) { + if(indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.indexInformation = function(options, callback) { + // Unpack calls + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + // Call the index information + this.s.db.indexInformation(this.s.name, options, callback); +} + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} query The query for the count. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.limit=null] The limit of documents to count. + * @param {boolean} [options.skip=null] The number of documents to skip for the count. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~countCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.count = function(query, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + var skip = options.skip; + var limit = options.limit; + var hint = options.hint; + var maxTimeMS = options.maxTimeMS; + + // Final query + var cmd = { + 'count': this.s.name, 'query': query + , 'fields': null + }; + + // Add limit and skip if defined + if(typeof skip == 'number') cmd.skip = skip; + if(typeof limit == 'number') cmd.limit = limit; + if(hint) options.hint = hint; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Execute command + this.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +}; + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.distinct = function(key, query, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + // maxTimeMS option + var maxTimeMS = options.maxTimeMS; + + // Distinct command + var cmd = { + 'distinct': this.s.name, 'key': key, 'query': query + }; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Execute the command + this.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +}; + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.indexes = function(callback) { + this.s.db.indexInformation(this.s.name, {full:true}, callback); +} + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Collection~resultCallback} callback The collection result callback + * @return {null} + */ +Collection.prototype.stats = function(options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Build command object + var commandObject = { + collStats:this.s.name + } + + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Execute the command + this.s.db.command(commandObject, options, callback); +} + +/** + * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {Collection~resultCallback} callback The collection result callback + * @return {null} + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + this.findAndModify( + filter + , options.sort + , null + , { + fields: options.projection + , remove:true + } + , callback + ); +} + +/** + * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~resultCallback} callback The collection result callback + * @return {null} + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + this.findAndModify( + filter + , options.sort + , replacement + , { + fields: options.projection + , update: true + , new: typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false + , upsert: typeof options.upsert == 'boolean' ? options.upsert : false + } + , callback + ); +} + +/** + * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~resultCallback} callback The collection result callback + * @return {null} + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + this.findAndModify( + filter + , options.sort + , update + , { + fields: options.projection + , update: true + , new: typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false + , upsert: typeof options.upsert == 'boolean' ? options.upsert : false + } + , callback + ); +} + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + var options = shallowClone(options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + // Create findAndModify command object + var queryObject = { + 'findandmodify': this.s.name + , 'query': query + }; + + sort = formattedOrderClause(sort); + if(sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + if(options.fields) { + queryObject.fields = options.fields; + } + + if(doc && !options.remove) { + queryObject.update = doc; + } + + // Either use override on the function, or go back to default on either the collection + // level or db + if(options['serializeFunctions'] != null) { + options['serializeFunctions'] = options['serializeFunctions']; + } else { + options['serializeFunctions'] = this.s.serializeFunctions; + } + + // No check on the documents + options.checkKeys = false; + + // Execute the command + this.s.db.command(queryObject + , options, function(err, result) { + if(err) return handleCallback(callback, err, null); + return handleCallback(callback, null, result); + }); +} + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = function(query, sort, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + // Add the remove option + options['remove'] = true; + // Execute the callback + this.findAndModify(query, sort, null, options, callback); +} + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} pipeline Array containing all the aggregation framework commands for the execution. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {Collection~resultCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + if(Array.isArray(pipeline)) { + // Set up callback if one is provided + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if(options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + var args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + var opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = opts && (opts.readPreference + || opts.explain || opts.cursor || opts.out + || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // If out was specified + if(typeof options.out == 'string') { + pipeline.push({$out: options.out}); + } + + // Build the command + var command = { aggregate : this.s.name, pipeline : pipeline}; + // If we have allowDiskUse defined + if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If explain has been specified add it + if(options.explain) command.explain = options.explain; + + // Validate that cursor options is valid + if(options.cursor != null && typeof options.cursor != 'object') { + throw toError('cursor options must be an object'); + } + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if(typeof callback != 'function') { + if(this.s.topology.capabilities().hasAggregationCursor) { + options.cursor = options.cursor || { batchSize : 1000 }; + command.cursor = options.cursor; + } + + // Allow disk usage command + if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + var cursor = null; + // We do not allow cursor + if(options.cursor) { + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // Execute the command + this.s.db.command(command, options, function(err, result) { + if(err) { + handleCallback(callback, err); + } else if(result['err'] || result['errmsg']) { + handleCallback(callback, toError(result)); + } else if(typeof result == 'object' && result['serverPipeline']) { + handleCallback(callback, null, result['serverPipeline']); + } else if(typeof result == 'object' && result['stages']) { + handleCallback(callback, null, result['stages']); + } else { + handleCallback(callback, null, result.result); + } + }); +} + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.parallelCollectionScan = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {numCursors: 1}; + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Create command object + var commandObject = { + parallelCollectionScan: this.s.name + , numCursors: options.numCursors + } + + // Execute the command + this.s.db.command(commandObject, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); + + var cursors = []; + // Create command cursors for each item + for(var i = 0; i < result.cursors.length; i++) { + var rawId = result.cursors[i].cursor.id + // Convert cursorId to Long if needed + var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; + + // Command cursor options + var cmd = { + batchSize: options.batchSize + , cursorId: cursorId + , items: result.cursors[i].cursor.firstBatch + } + + // Add a command cursor + cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +/** + * Execute the geoNear command to search for items in the collection + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.num=null] Max number of results to return. + * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. + * @param {object} [options.query=null] Filter the results by a query. + * @param {boolean} [options.spherical=false] Perform query using a spherical model. + * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. + * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.geoNear = function(x, y, options, callback) { + var point = typeof(x) == 'object' && x + , args = Array.prototype.slice.call(arguments, point?1:2); + + callback = args.pop(); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Build command object + var commandObject = { + geoNear:this.s.name, + near: point || [x, y] + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Exclude readPreference and existing options to prevent user from + // shooting themselves in the foot + var exclude = { + readPreference: true, + geoNear: true, + near: true + }; + + // Filter out any excluded objects + commandObject = decorateCommand(commandObject, options, exclude); + + // Execute the command + this.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) return handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {object} [options.search=null] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Build command object + var commandObject = { + geoSearch: this.s.name, + near: [x, y] + } + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, {readPreference: true}); + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Execute the command + this.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +/** + * Group function helper + * @ignore + */ +var groupFunction = function () { + var c = db[ns].find(condition); + var map = new Map(); + var reduce_function = reduce; + + while (c.hasNext()) { + var obj = c.next(); + var key = {}; + + for (var i = 0, len = keys.length; i < len; ++i) { + var k = keys[i]; + key[k] = obj[k]; + } + + var aggObj = map.get(key); + + if (aggObj == null) { + var newObj = Object.extend({}, key); + aggObj = Object.extend(newObj, initial); + map.put(key, aggObj); + } + + reduce_function(obj, aggObj); + } + + return { "result": map.values() }; +}.toString(); + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} callback The command result callback + * @return {null} + */ +Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { + var args = Array.prototype.slice.call(arguments, 3); + callback = args.pop(); + // Fetch all commands + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if(!(typeof finalize == 'function')) { + command = finalize; + finalize = null; + } + + if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { + keys = Object.keys(keys); + } + + if(typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if(typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + // Execute using the command + if(command) { + var reduceFunction = reduce instanceof Code + ? reduce + : new Code(reduce); + + var selector = { + group: { + 'ns': this.s.name + , '$reduce': reduceFunction + , 'cond': condition + , 'initial': initial + , 'out': "inline" + } + }; + + // if finalize is defined + if(finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || keys instanceof Code) { + selector.group.$keyf = keys instanceof Code + ? keys + : new Code(keys); + } else { + var hash = {}; + keys.forEach(function (key) { + hash[key] = 1; + }); + selector.group.key = hash; + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + // Execute command + this.s.db.command(selector, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + var scope = reduce != null && reduce instanceof Code + ? reduce.scope + : {}; + + scope.ns = this.s.name; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + this.s.db.eval(new Code(groupfn, scope), function (err, results) { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope (scope) { + if(!isObject(scope)) { + return scope; + } + + var keys = Object.keys(scope); + var i = keys.length; + var key; + var new_scope = {}; + + while (i--) { + key = keys[i]; + if ('function' == typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query=null] Query filter object. + * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit=null] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize=null] Finalize function. + * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {Collection~resultCallback} callback The command result callback + * @throws {MongoError} + * @return {null} + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + var self = this; + if('function' === typeof options) callback = options, options = {}; + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if(null == options.out) { + throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); + } + + if('function' === typeof map) { + map = map.toString(); + } + + if('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + var mapCommandHash = { + mapreduce: this.s.name + , map: map + , reduce: reduce + }; + + // Add any other options passed in + for(var n in options) { + if('scope' == n) { + mapCommandHash[n] = processScope(options[n]); + } else { + mapCommandHash[n] = options[n]; + } + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If we have a read preference and inline is not set as output fail hard + if((options.readPreference != false && options.readPreference != 'primary') + && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { + options.readPreference = 'primary'; + } + + // Execute command + this.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { + if(err) return handleCallback(callback, err); + // Check if we have an error + if(1 != result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + var stats = {}; + if(result.timeMillis) stats['processtime'] = result.timeMillis; + if(result.counts) stats['counts'] = result.counts; + if(result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if(result.results) { + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, result.results, stats); + } + + // The returned collection + var collection = null; + + // If we have an object it's a different db + if(result.result != null && typeof result.result == 'object') { + var doc = result.result; + collection = self.s.db.db(doc.db).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = self.s.db.collection(result.result) + } + + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, collection, stats); + }); +} + +/** + * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {UnorderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + return unordered(this.s.topology, this, options); +} + +/** + * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + return ordered(this.s.topology, this, options); +} + +// Get write concern +var writeConcern = function(target, db, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w != null) opts.w = options.w; + if(options.wtimeout != null) opts.wtimeout = options.wtimeout; + if(options.j != null) opts.j = options.j; + if(options.fsync != null) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Figure out the read preference +var getReadPreference = function(self, options, db, coll) { + var r = null + if(options.readPreference) { + r = options.readPreference + } else if(self.s.readPreference) { + r = self.s.readPreference + } else if(db.readPreference) { + r = db.readPreference; + } + + if(r instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + options.readPreference = new CoreReadPreference(r); + } + + return options; +} + +var testForFields = { + limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 + , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 + , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 +} + +module.exports = Collection; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..ee2e7cc --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,282 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + // , CoreCursor = require('mongodb-core').Cursor + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + } +} + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed']; + +// // Map core cursor _next method so we can apply mapping +// CoreCursor.prototype._next = CoreCursor.prototype.next; + +// Only inherit the types we need +for(var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw new MongoError("Cursor is closed"); + if(typeof value != 'number') throw new MongoError("batchSize requires an integer"); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Set the new batchSize of the cursor + * @function CommandCursor.prototype.setBatchSize + * @param {number} value The new batchSize for the cursor + * @return {null} + */ + +/** + * Get the batchSize of the cursor + * @function CommandCursor.prototype.batchSize + * @param {number} value The current batchSize for the cursor + * @return {null} + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {null} + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..2b46965 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,876 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , CoreCursor = require('mongodb-core').Cursor + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +var fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Some example + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = Cursor.INIT; + var streamOptions = {}; + + // Tailable cursor options + var numberOfRetries = options.numberOfRetries || 5; + var tailableRetryInterval = options.tailableRetryInterval || 500; + var currentNumberOfRetries = numberOfRetries; + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries + , tailableRetryInterval: tailableRetryInterval + , currentNumberOfRetries: currentNumberOfRetries + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespace + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology options + , topologyOptions: topologyOptions + } + + // Legacy fields + this.timeout = self.s.options.noCursorTimeout == true; + this.sortValue = self.s.cmd.sort; + this.readPreference = self.s.options.readPreference; +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +for(var name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +Cursor.prototype.mister = function() {} + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + this.s.cmd.query = filter; + return this; +} + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + if(fields.indexOf(field) == -1) throw new MongoError(f("option %s not a supported option %s", field, fields)); + this.s[field] = value; + if(field == 'numberOfRetries') + this.s.currentNumberOfRetries = value; + return this; +} + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + if(flags.indexOf(flag) == -1) throw new MongoError(f("flag %s not a supported flag %s", flag, flags)); + if(typeof value != 'boolean') throw new MongoError(f("flag %s must be a boolean value", flag)); + this.s.cmd[flag] = value; + return this; +} + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + if(name[0] != '$') throw new MongoError(f("%s is not a valid query modifier")); + // Strip of the $ + var field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +} + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + this.s.cmd.comment = value; + return this; +} + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if(typeof value != 'number') throw new MongoError("maxTimeMS must be a number"); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + this.s.cmd.maxTimeMS = value; + return this; +} + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + this.s.cmd.fields = value; + return this; +} + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if(this.s.options.tailable) throw new MongoError("Tailable cursor doesn't support sorting"); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw new MongoError("Cursor is closed"); + var order = keyOrList; + + if(direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +} + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if(this.s.options.tailable) throw new MongoError("Tailable cursor doesn't support limit"); + if(this.s.state == Cursor.CLOSED || this.isDead()) throw new MongoError("Cursor is closed"); + if(typeof value != 'number') throw new MongoError("batchSize requires an integer"); + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if(this.s.options.tailable) throw new MongoError("Tailable cursor doesn't support limit"); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw new MongoError("Cursor is closed"); + if(typeof value != 'number') throw new MongoError("limit requires an integer"); + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +} + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if(this.s.options.tailable) throw new MongoError("Tailable cursor doesn't support skip"); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw new MongoError("Cursor is closed"); + if(typeof value != 'number') throw new MongoError("skip requires an integer"); + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +} + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function external:CoreCursor#next + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Set the new batchSize of the cursor + * @function Cursor.prototype.setBatchSize + * @param {number} value The new batchSize for the cursor + * @return {null} + */ + +/** + * Get the batchSize of the cursor + * @function Cursor.prototype.batchSize + * @param {number} value The current batchSize for the cursor + * @return {null} + */ + +/** + * Set the new skip value of the cursor + * @function Cursor.prototype.setCursorSkip + * @param {number} value The new skip for the cursor + * @return {null} + */ + +/** + * Get the skip value of the cursor + * @function Cursor.prototype.cursorSkip + * @param {number} value The current skip value for the cursor + * @return {null} + */ + +/** + * Set the new limit value of the cursor + * @function Cursor.prototype.setCursorLimit + * @param {number} value The new limit for the cursor + * @return {null} + */ + +/** + * Get the limit value of the cursor + * @function Cursor.prototype.cursorLimit + * @param {number} value The current limit value for the cursor + * @return {null} + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @deprecated + * @return {null} + */ +Cursor.prototype.nextObject = function(callback) { + var self = this; + if(this.s.state == Cursor.CLOSED || self.isDead()) return handleCallback(callback, new MongoError("Cursor is closed")); + if(this.s.state == Cursor.INIT && this.s.cmd.sort) { + try { + this.s.cmd.sort = formattedOrderClause(this.s.cmd.sort); + } catch(err) { + return handleCallback(callback, err); + } + } + + // Get the next object + self._next(function(err, doc) { + if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); + if(err && err.tailable && self.s.currentNumberOfRetries > 0) { + self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; + return setTimeout(function() { + self.nextObject(callback); + }, self.s.tailableRetryInterval); + } + + self.s.state = Cursor.OPEN; + if(err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +var loop = function(self, callback) { + // No more items we are done + if(self.bufferedCount() == 0) return; + // Get the next document + self._next(callback); + // Loop + return loop; +} + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + _each(this, callback); +}; + +// Run the each loop +var _each = function(self, callback) { + if(!callback) throw new MongoError('callback is mandatory'); + if(self.isNotified()) return; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return handleCallback(callback, new MongoError("Cursor is closed"), null); + } + + if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + var fn = null; + // Trampoline all the entries + if(self.bufferedCount() > 0) { + while(fn = loop(self, callback)) fn(self, callback); + _each(self, callback); + } else { + self._next(function(err, item) { + if(err) return handleCallback(callback, err); + if(item == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, null); + } + + if(handleCallback(callback, null, item) == false) return; + _each(self, callback); + }) + } +} + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.forEach = function(iterator, callback) { + this.each(function(err, doc){ + if(err) { callback(err); return false; } + if(doc != null) { iterator(doc); return true; } + if(doc == null && callback) { + var internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); +} + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(r) { + if(this.s.state != Cursor.INIT) throw new MongoError('cannot change cursor readPreference after cursor has been accessed'); + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else { + this.s.options.readPreference = new CoreReadPreference(r); + } + + return this; +} + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.toArray = function(callback) { + var self = this; + if(!callback) throw new MongoError('callback is mandatory'); + if(self.s.options.tailable) return handleCallback(callback, new MongoError("Tailable cursor cannot be converted to array"), null); + var items = []; + + // Reset cursor + this.rewind(); + self.s.state = Cursor.INIT; + + + // Fetch all the documents + var fetchDocs = function() { + self._next(function(err, doc) { + if(err) return handleCallback(callback, err); + if(doc == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, items); + } + + // Add doc to items + items.push(doc) + // Get all buffered objects + if(self.bufferedCount() > 0) { + var docs = self.readBufferedDocuments(self.bufferedCount()) + + // Transform the doc if transform method added + if(self.s.transforms && typeof self.s.transforms.doc == 'function') { + docs = docs.map(self.s.transforms.doc); + } + + items = items.concat(docs); + } + + // Attempt a fetch + fetchDocs(); + }) + } + + fetchDocs(); +} + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options=null] Optional settings. + * @param {number} [options.skip=null] The number of documents to skip. + * @param {number} [options.limit=null] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} callback The result callback. + * @return {null} + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + var self = this; + if(typeof opts == 'function') callback = opts, opts = {}; + opts = opts || {}; + if(self.s.cmd.query == null) callback(new MongoError("count can only be used with find command")); + if(typeof applySkipLimit == 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if(applySkipLimit) { + if(typeof this.cursorSkip() == 'number') opts.skip = this.cursorSkip(); + if(typeof this.cursorLimit() == 'number') opts.limit = this.cursorLimit(); + } + + // Command + var delimiter = self.s.ns.indexOf('.'); + + var command = { + 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query + } + + if(typeof opts.maxTimeMS == 'number') { + command.maxTimeMS = opts.maxTimeMS; + } else if(typeof self.s.maxTimeMS == 'number') { + command.maxTimeMS = self.s.maxTimeMS; + } + + // Get a server + var server = self.s.topology.getServer(opts); + // Get a connection + var connection = self.s.topology.getConnection(opts); + // Get the callbacks + var callbacks = server.getCallbacks(); + + // Merge in any options + if(opts.skip) command.skip = opts.skip; + if(opts.limit) command.limit = opts.limit; + if(self.s.options.hint) command.hint = self.s.options.hint; + + // Build Query object + var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set up callback + callbacks.register(query.requestId, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.documents.length == 1 + && (result.documents[0].errmsg + || result.documents[0].err + || result.documents[0]['$err'])) return callback(MongoError.create(result.documents[0])); + handleCallback(callback, null, result.documents[0].n); + }); + + // Write the initial command out + connection.write(query.toBin()); +}; + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {null} + */ +Cursor.prototype.close = function(callback) { + this.s.state = Cursor.CLOSED; + // Kill the cursor + this.kill(); + // Emit the close event for the cursor + this.emit('close'); + // Callback if provided + if(callback) return handleCallback(callback, null, this); +} + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {null} + */ +Cursor.prototype.map = function(transform) { + this.cursorState.transforms = { doc: transform }; + return this; +} + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +} + +Cursor.prototype.destroy = function(err) { + this.pause(); + this.close(); + if(err) this.emit('error', err); +} + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options=null] Optional settings. + * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +} + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {null} + */ +Cursor.prototype.explain = function(callback) { + this.s.cmd.explain = true; + this._next(callback); +} + +Cursor.prototype._read = function(n) { + var self = this; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return self.push(null); + } + + // Get the next item + self.nextObject(function(err, result) { + if(err) { + if(!self.isDead()) self.close(); + if(self.listeners('error') && self.listeners('error').length > 0) { + self.emit('error', err); + } + + // Emit end event + return self.emit('end'); + } + + // If we provided a transformation method + if(typeof self.s.streamOptions.transform == 'function' && result != null) { + return self.push(self.s.streamOptions.transform(result)); + } + + // If we provided a map function + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { + return self.push(self.cursorState.transforms.doc(result)); + } + + // Return the result + self.push(result); + }); +} + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + var ns = this.s.ns || ''; + var firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/db.js b/node_modules/mongoose/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..6ede3ff --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/db.js @@ -0,0 +1,1400 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , getSingleProperty = require('./utils').getSingleProperty + , shallowClone = require('./utils').shallowClone + , parseIndexOptions = require('./utils').parseIndexOptions + , debugOptions = require('./utils').debugOptions + , CommandCursor = require('./command_cursor') + , handleCallback = require('./utils').handleCallback + , toError = require('./utils').toError + , ReadPreference = require('./read_preference') + , f = require('util').format + , Admin = require('./admin') + , Code = require('mongodb-core').BSON.Code + , CoreReadPreference = require('mongodb-core').ReadPreference + , MongoError = require('mongodb-core').MongoError + , ObjectID = require('mongodb-core').ObjectID + , Logger = require('mongodb-core').Logger + , Collection = require('./collection') + , crypto = require('crypto'); + +var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' + , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' + , 'readPreference', 'pkFactory']; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * var testDb = db.db('test'); + * db.close(); + * }); + */ + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {number} [options.numberOfRetries=5] Number of retries off connection. + * @param {number} [options.retryMiliSeconds=500] Number of milliseconds between retries. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @fires Db#close + * @fires Db#authenticated + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +var Db = function(databaseName, topology, options) { + options = options || {}; + if(!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + var self = this; + // var self = this; // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName + // Children db's + , children: [] + // Topology + , topology: topology + // Options + , options: options + // Logger instance + , logger: Logger('Db', options) + // Get the bson parser + , bson: topology ? topology.bson : null + // Authsource if any + , authSource: options.authSource + // Unpack read preference + , readPreference: options.readPreference + // Set buffermaxEntries + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 + // Parent db (if chained) + , parentDb: options.parentDb || null + // Set up the primary key factory or fallback to ObjectID + , pkFactory: options.pkFactory || ObjectID + // Get native parser + , nativeParser: options.nativeParser || options.native_parser + } + + // Ensure we have a valid db name + validateDatabaseName(self.s.databaseName); + + // If we have specified the type of parser + if(typeof self.s.nativeParser == 'boolean') { + if(self.s.nativeParser) { + topology.setBSONParserType("c++"); + } else { + topology.setBSONParserType("js"); + } + } + + // Add a read Only property + getSingleProperty(this, 'serverConfig', self.s.topology); + getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', self.s.databaseName); + + // Last ismaster + Object.defineProperty(this, 'options', { + enumerable:true, + get: function() { return self.s.options; } + }); + + // Last ismaster + Object.defineProperty(this, 'native_parser', { + enumerable:true, + get: function() { return self.s.topology.parserType() == 'c++'; } + }); + + // Last ismaster + Object.defineProperty(this, 'slaveOk', { + enumerable:true, + get: function() { + if(self.s.options.readPreference != null + && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { + return true; + } + return false; + } + }); + + Object.defineProperty(this, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(self.s.options.w != null) ops.w = self.s.options.w; + if(self.s.options.j != null) ops.j = self.s.options.j; + if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; + if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; + return ops; + } + }); + + // This is a child db, do not register any listeners + if(options.parentDb) return; + + // Add listeners + topology.once('error', createListener(self, 'error', self)); + topology.once('timeout', createListener(self, 'timeout', self)); + topology.on('close', createListener(self, 'close', self)); + topology.once('parseError', createListener(self, 'parseError', self)); + topology.once('open', createListener(self, 'open', self)); + topology.once('fullsetup', createListener(self, 'fullsetup', self)); + topology.once('all', createListener(self, 'all', self)); + topology.on('reconnect', createListener(self, 'reconnect', self)); +} + +inherits(Db, EventEmitter); + +/** + * The callback format for the Db.open method + * @callback Db~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The Db instance if the open method was successful. + */ + +/** + * Open the database + * @method + * @param {Db~openCallback} callback Callback + * @return {null} + */ +Db.prototype.open = function(callback) { + var self = this; + self.s.topology.connect(self, self.s.options, function(err, topology) { + if(callback == null) return; + var internalCallback = callback; + callback == null; + + if(err) { + self.close(); + return internalCallback(err); + } + + internalCallback(null, self); + }); +} + +/** + * The callback format for results + * @callback Db~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.command = function(command, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var dbName = options.dbName || options.authdb || self.s.databaseName; + // Clone the options + options = shallowClone(options); + // If we have a readPreference set + if(options.readPreference == null && self.s.readPreference) { + options.readPreference = self.s.readPreference; + } + + // Convert the readPreference + if(options.readPreference && typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + // Debug information + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' + , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); + + // Execute command + self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * The callback format for results + * @callback Db~noResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {null} result Is not set to a value + */ + +/** + * Close the db and it's underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} callback The result callback + * @return {null} + */ +Db.prototype.close = function(force, callback) { + if(typeof force == 'function') callback = force, force = false; + this.s.topology.close(force); + var self = this; + + // Fire close event if any listeners + if(this.listeners('close').length > 0) { + this.emit('close'); + + // If it's the top level db emit close on all children + if(this.parentDb == null) { + // Fire close on all children + for(var i = 0; i < this.s.children.length; i++) { + this.s.children[i].emit('close'); + } + } + + // Remove listeners after emit + self.removeAllListeners('close'); + } + + // Close parent db if set + if(this.s.parentDb) this.s.parentDb.close(); + // Callback after next event loop tick + if(typeof callback == 'function') process.nextTick(function() { + handleCallback(callback, null); + }); +} + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + return new Admin(this, this.s.topology); +}; + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can + * can use it without a callback in the following way. var collection = db.collection('mycollection'); + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {Db~collectionResultCallback} callback The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + if(options == null || !options.strict) { + try { + var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); + if(callback) callback(null, collection); + return collection; + } catch(err) { + if(callback) return callback(err); + throw err; + } + } + + // Strict mode + if(typeof callback != 'function') { + throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); + } + + // Strict mode + this.listCollections({name:name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); + + try { + return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + } catch(err) { + return handleCallback(callback, err, null); + } + }); +} + +/** + * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {number} [options.size=null] The size of the capped collection in bytes. + * @param {number} [options.max=null] The maximum number of documents in the capped collection. + * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. + * @param {Db~collectionResultCallback} callback The results callback + * @return {null} + */ +Db.prototype.createCollection = function(name, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + name = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), this, options); + + // Check if we have the name + this.listCollections({name: name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length > 0 && finalOptions.strict) { + return handleCallback(callback, new MongoError(f("Collection %s already exists. Currently in strict mode.", name)), null); + } else if (collections.length > 0) { + try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } + catch(err) { return handleCallback(callback, err); } + } + + // Create collection command + var cmd = {'create':name}; + + // Add all optional parameters + for(var n in options) { + if(options[n] != null && typeof options[n] != 'function') + cmd[n] = options[n]; + } + + // Execute command + self.command(cmd, finalOptions, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + }); + }); +} + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Db~resultCallback} callback The collection result callback + * @return {null} + */ +Db.prototype.stats = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Build command object + var commandObject = { dbStats:true }; + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + // Execute the command + this.command(commandObject, options, callback); +} + +// Transformation methods for cursor results +var listCollectionsTranforms = function(databaseName) { + var matching = f('%s.', databaseName); + + return { + doc: function(doc) { + var index = doc.name.indexOf(matching); + // Remove database name if available + if(doc.name && index == 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + } +} + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} filter Query to filter collections by + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // We have a list collections command + if(this.serverConfig.capabilities().hasListCollectionsCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listCollections : true, filter: filter, cursor: cursor }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Filter out the correct field values + options.transforms = listCollectionsTranforms(this.s.databaseName); + // Execute the cursor + return this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); + } + + // We cannot use the listCollectionsCommand + if(!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { + filter = shallowClone(filter); + filter.name = f('%s.%s', this.s.databaseName, filter.name); + } + } + + // No filter, filter by current database + if(filter == null) { + filter.name = f('/%s/', this.s.databaseName); + } + + // Rewrite the filter to use $and to filter out indexes + if(filter.name) { + filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; + } else { + filter = {name:/^((?!\$).)*$/}; + } + + // Return options + var options = {transforms: listCollectionsTranforms(this.s.databaseName)} + // Get the cursor + var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, options); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // We have a fallback mode using legacy systems collections + return cursor; +}; + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {Db~resultCallback} callback The results callback + * @return {null} + */ +Db.prototype.eval = function(code, parameters, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + var finalCode = code; + var finalParameters = []; + + // If not a code object translate to one + if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + var cmd = {'$eval':finalCode, 'args':finalParameters}; + // Check if the nolock parameter is passed in + if(options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); + + // Execute the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result && result.ok == 1) return handleCallback(callback, null, result.retval); + if(result) return handleCallback(callback, new MongoError(f("eval failed: %s", result.errmsg)), null); + handleCallback(callback, err, result); + }); +}; + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Db~collectionResultCallback} callback The results callback + * @return {null} + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Add return new collection + options.new_collection = true; + // Execute using the collection method + this.collection(fromCollection).rename(toCollection, options, callback); +}; + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Db~resultCallback} callback The results callback + * @return {null} + */ +Db.prototype.dropCollection = function(name, callback) { + callback || (callback = function(){}); + + // Command to execute + var cmd = {'drop':name} + + // Execute command + this.command(cmd, this.s.options, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); +}; + +/** + * Drop a database. + * + * @method + * @param {Db~resultCallback} [callback] The results callback + * @return {null} + */ +Db.prototype.dropDatabase = function(callback) { + if(typeof options == 'function') callback = options, options = {}; + // Drop database command + var cmd = {'dropDatabase':1}; + + // Execute the command + this.command(cmd, this.s.options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +/** + * The callback format for the collections method. + * @callback Db~collectionsResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection[]} collections An array of all the collections objects for the db instance. + */ + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {null} + */ +Db.prototype.collections = function(callback) { + var self = this; + // Let's get the collection names + this.listCollections().toArray(function(err, documents) { + if(err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(function(doc) { + return doc.name.indexOf('$') == -1; + }); + + // Return the collection objects + handleCallback(callback, null, documents.map(function(d) { + return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); + })); + }); +}; + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(options.readPreference) { + options.readPreference = options.readPreference; + } + + // Execute command + this.s.topology.command('admin.$cmd', selector, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +}; + +/** + * Creates an index on the db and collection collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Ensure we have a callback + if(finalOptions.writeConcern && typeof callback != 'function') { + throw new MongoError("Cannot use a writeConcern without a provided callback"); + } + + // Shallow clone the options + options = shallowClone(options); + + // Always set read preference to primary + options.readPreference = ReadPreference.PRIMARY; + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { + if(err == null) return handleCallback(callback, err, result); + // Create command + var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + }); + }); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Create command + var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); + var index_name = selector.name; + + // Default command options + var commandOptions = {}; + // Check if the index allready exists + this.indexInformation(name, finalOptions, function(err, indexInformation) { + if(err != null && err.code != 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if(indexInformation == null || !indexInformation[index_name]) { + self.createIndex(name, fieldOrSpec, options, callback); + } else { + if(typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +}; + +Db.prototype.addChild = function(db) { + if(this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +} + +/** + * Create a new Db instance sharing the current socket connections. + * @method + * @param {string} name The name of the database we want to use. + * @return {Db} + */ +Db.prototype.db = function(dbName) { + // Copy the options and add out internal override of the not shared flag + var options = {}; + for(var key in this.options) { + options[key] = this.options[key]; + } + + // Add current db as parentDb + options.parentDb = this; + + // Return the db object + var db = new Db(dbName, this.s.topology, options) + + // Keep reference to the object + // if(this.s.parentDb) { + // this.s.parentDb.s.children.push(db); + this.addChild(db); + // } + // this.s.children.push(db); + + // // Add listeners to the parent database + // this.once('error', createListener(this, 'error', db)); + // this.once('timeout', createListener(this, 'timeout', db)); + // this.once('close', createListener(this, 'close', db)); + // this.once('parseError', createListener(this, 'parseError', db)); + + // Return the database + return db; +}; + +var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { + // Special case where there is no password ($external users) + if(typeof username == 'string' + && password != null && typeof password == 'object') { + options = password; + password = null; + } + + // Unpack all options + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if(options.digestPassword != null) { + throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); + } + + // Get additional values + var customData = options.customData != null ? options.customData : {}; + var roles = Array.isArray(options.roles) ? options.roles : []; + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if(roles.length == 0) { + console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); + } + + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { + roles = ['root'] + } else if(!Array.isArray(options.roles)) { + roles = ['dbOwner'] + } + + // Build the command to execute + var command = { + createUser: username + , customData: customData + , roles: roles + , digestPassword:false + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // No password + if(typeof password == 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, !result.ok ? toError(result) : null + , result.ok ? [{user: username, pwd: ''}] : null); + }) +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.addUser = function(username, password, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + + // Attempt to execute auth command + _executeAuthCreateUserCommand(this, username, password, options, function(err, r) { + // We need to perform the backward compatible insert operation + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + collection.count({}, function(err, count) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { + if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); + if(err) return handleCallback(callback, err, null) + handleCallback(callback, null, [{user:username, pwd:userPassword}]); + }); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +}; + +var _executeAuthRemoveUserCommand = function(self, username, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + var command = { + dropUser: username + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }) +} + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.removeUser = function(username, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + + // Attempt to execute command + _executeAuthRemoveUserCommand(this, username, options, function(err, result) { + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Locate the user + collection.findOne({user: username}, {}, function(err, user) { + if(user == null) return handleCallback(callback, err, false); + collection.remove({user: username}, finalOptions, function(err, result) { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +}; + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.authenticate = function(username, password, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + // Shallow copy the options + options = shallowClone(options); + + // Set default mechanism + if(!options.authMechanism) { + options.authMechanism = 'DEFAULT'; + } else if(options.authMechanism != 'GSSAPI' + && options.authMechanism != 'MONGODB-CR' + && options.authMechanism != 'MONGODB-X509' + && options.authMechanism != 'SCRAM-SHA-1' + && options.authMechanism != 'PLAIN') { + return handleCallback(callback, new MongoError("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism")); + } + + // the default db to authenticate against is 'this' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.authdb ? options.authdb : options.dbName; + authdb = options.authSource ? options.authSource : authdb; + authdb = authdb ? authdb : this.databaseName; + + // Callback + var _callback = function(err, result) { + if(self.listeners('authenticated').length > 0) { + self.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + } + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if(authMechanism == 'MONGODB-CR') { + this.s.topology.auth('mongocr', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'PLAIN') { + this.s.topology.auth('plain', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'MONGODB-X509') { + this.s.topology.auth('x509', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'SCRAM-SHA-1') { + this.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'GSSAPI') { + if(process.platform == 'win32') { + this.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + this.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if(authMechanism == 'DEFAULT') { + this.s.topology.auth('default', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback(callback, new MongoError(f("authentication mechanism %s not supported", options.authMechanism), false)); + } +}; + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options=null] Optional settings. + * @param {string} [options.dbName=null] Logout against different database than current. + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.logout = function(options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + options = args.length ? args.shift() || {} : {}; + + // logout command + var cmd = {'logout':1}; + + // Add onAll to login to ensure all connection are logged out + options.onAll = true; + + // We authenticated against a different db use that + if(this.s.authSource) options.dbName = this.s.authSource; + + // Execute the command + this.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true) + }); +} + +// Figure out the read preference +var getReadPreference = function(options, db) { + if(options.readPreference) return options; + if(db.readPreference) options.readPreference = db.readPreference; + return options; +} + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} callback The command result callback + * @return {null} + */ +Db.prototype.indexInformation = function(name, options, callback) { + if(typeof callback === 'undefined') { + if(typeof options === 'undefined') { + callback = name; + name = null; + } else { + callback = options; + } + options = {}; + } + + // If we specified full information + var full = options['full'] == null ? false : options['full']; + var self = this; + + // Process all the results from the index command and collection + var processResults = function(indexes) { + // Contains all the information + var info = {}; + // Process all the indexes + for(var i = 0; i < indexes.length; i++) { + var index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for(var name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + this.collection(name).listIndexes().toArray(function(err, indexes) { + if(err) return callback(toError(err)); + if(!Array.isArray(indexes)) return handleCallback(callback, null, []); + if(full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +}; + +var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { + var indexParameters = parseIndexOptions(fieldOrSpec); + var fieldHash = indexParameters.fieldHash; + var keys = indexParameters.keys; + + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + var selector = { + 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName + } + + // Ensure we have a correct finalUnique + var finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options == 'boolean' ? {} : options; + + // Add all the options + var keysToOmit = Object.keys(selector); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + selector[optionName] = options[optionName]; + } + } + + if(selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { + // Build the index + var indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + // Set up the index + var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + var keysToOmit = Object.keys(indexes[0]); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + indexes[0][optionName] = options[optionName]; + } + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete indexes[0][removeKeys[i]]; + } + } + + // Create command + var cmd = {createIndexes: name, indexes: indexes}; + + // Apply write concern to command + cmd = writeConcern(cmd, self, options); + + // Build the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result.ok == 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +// Validate the database name +var validateDatabaseName = function(databaseName) { + if(typeof databaseName !== 'string') throw new MongoError("database name must be a string"); + if(databaseName.length === 0) throw new MongoError("database name cannot be the empty string"); + if(databaseName == '$external') return; + + var invalidChars = [" ", ".", "$", "/", "\\"]; + for(var i = 0; i < invalidChars.length; i++) { + if(databaseName.indexOf(invalidChars[i]) != -1) throw new MongoError("database names cannot contain the character '" + invalidChars[i] + "'"); + } +} + +// Get write concern +var writeConcern = function(target, db, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w) opts.w = options.w; + if(options.wtimeout) opts.wtimeout = options.wtimeout; + if(options.j) opts.j = options.j; + if(options.fsync) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Add listeners to topology +var createListener = function(self, e, object) { + var listener = function(err) { + if(e != 'error') { + object.emit(e, err, self); + + // Emit on all associated db's if available + for(var i = 0; i < self.s.children.length; i++) { + self.s.children[i].emit(e, err, self.s.children[i]); + } + } + } + return listener; +} + +/** + * Db close event + * + * @event Db#close + * @type {object} + */ + +/** + * Db authenticated event + * + * @event Db#authenticated + * @type {object} + */ + +/** + * Db reconnect event + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * @event Db#timeout + * @type {object} + */ + +/** + * Db parseError event + * + * @event Db#parseError + * @type {object} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; +Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; +Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; +Db.SYSTEM_USER_COLLECTION = "system.users"; +Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; +Db.SYSTEM_JS_COLLECTION = "system.js"; + +module.exports = Db; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..eb1beed --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,236 @@ +"use strict"; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').BSON.ObjectID; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var self = this; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || {w:1}; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if(mongoObjectFinal.data == null) { + } else if(typeof mongoObjectFinal.data == "string") { + var buffer = new Buffer(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 'binary', 0); + this.data = new Binary(buffer); + } else if(Array.isArray(mongoObjectFinal.data)) { + var buffer = new Buffer(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data.join(''), 'binary', 0); + this.data = new Binary(buffer); + } else if(mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if(Buffer.isBuffer(mongoObjectFinal.data)) { + } else { + throw Error("Illegal chunk format"); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition); + this.internalPosition = this.data.length(); + if(callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length == 0 ? this.length() : length; + + if(this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if ((this.length() - this.internalPosition) >= length) { + var data = null; + if (this.data.buffer != null) { //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { //Native BSON + data = new Buffer(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition == this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if(typeof options == 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if(err) return callback(err); + + // Merge the options + var writeOptions = {}; + for(var name in options) writeOptions[name] = options[name]; + for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { + collection.remove({'_id':self.objectId}, writeOptions, function(err, result) { + if(err) return callback(err); + + if(self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = {forceServerObjectId:true}; + for(var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.insert(mongoObject, writeOptions, function(err, collection) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *

+ *        {
+ *          '_id' : , // {number} id for this chunk
+ *          'files_id' : , // {number} foreign key to the file collection
+ *          'n' : , // {number} chunk number
+ *          'data' : , // {bson#Binary} the chunk data itself
+ *        }
+ *        
+ * + * @see
MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + 'files_id': this.file.fileId, + 'n': this.chunkNumber, + 'data': this.data}; + // If we are saving using a specific ObjectId + if(this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, "position", { enumerable: true + , get: function () { + return this.internalPosition; + } + , set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..945ba5e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1603 @@ +"use strict"; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * GridStore = require('mongodb').GridStore, + * ObjectID = require('mongodb').ObjectID, + * test = require('assert'); + * + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * var gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * db.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +var Chunk = require('./chunk'), + ObjectID = require('mongodb-core').BSON.ObjectID, + ReadPreference = require('../read_preference'), + Buffer = require('buffer').Buffer, + fs = require('fs'), + timers = require('timers'), + f = require('util').format, + util = require('util'), + MongoError = require('mongodb-core').MongoError, + inherits = util.inherits, + Duplex = require('stream').Duplex || require('readable-stream').Duplex; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata=null] Arbitrary data the user wants to store. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + var self = this; + this.db = db; + + // Handle options + if(typeof options === 'undefined') options = {}; + // Handle mode + if(typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if(typeof mode == 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if(id instanceof ObjectID) { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if(typeof filename == 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? "r" : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = this.options.readPreference || ReadPreference.PRIMARY; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + Object.defineProperty(this, "chunkSize", { enumerable: true + , get: function () { + return this.internalChunkSize; + } + , set: function(value) { + if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, "md5", { enumerable: true + , get: function () { + return this.internalMd5; + } + }); + + Object.defineProperty(this, "chunkNumber", { enumerable: true + , get: function () { + return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; + } + }); +} + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {GridStore~openCallback} callback this will be called after executing this method + * @return {null} + */ +GridStore.prototype.open = function(callback) { + if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ + callback(new MongoError("Illegal mode " + this.mode), null); + return; + } + + var self = this; + + // Get the write concern + var writeConcern = _getWriteConcern(this.db, this.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if((self.mode == "w" || self.mode == "w+")) { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) { + // Open the connection + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +}; + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + */ +GridStore.prototype.eof = function() { + return this.position == this.length ? true : false; +} + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {null} + */ +GridStore.prototype.getc = function(callback) { + var self = this; + + if(self.eof()) { + callback(null, null); + } else if(self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +} + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {GridStore~resultCallback} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {null} + */ +GridStore.prototype.puts = function(string, callback) { + var finalString = string.match(/\n$/) == null ? string + "\n" : string; + this.write(finalString, callback); +} + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +} + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {GridStore~resultCallback} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {null} + */ +GridStore.prototype.write = function write(data, close, callback) { + return _writeNormal(this, data, close, callback); +} + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if(!this.writable) return; + this.readable = false; + if(this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +} + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {GridStore~resultCallback} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {null} + */ +GridStore.prototype.writeFile = function (file, callback) { + var self = this; + if (typeof file === 'string') { + fs.open(file, 'r', function (err, fd) { + if(err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function (err, self) { + if(err) return callback(err, self); + + fs.fstat(file, function (err, stats) { + if(err) return callback(err, self); + + var offset = 0; + var index = 0; + var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); + + // Write a chunk + var writeChunk = function() { + fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { + if(err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, {n:index++}, self.writeConcern); + chunk.write(data, function(err, chunk) { + if(err) return callback(err, self); + + chunk.save({}, function(err, result) { + if(err) return callback(err, self); + + self.position = self.position + data.length; + + // Point to current chunk + self.currentChunk = chunk; + + if(offset >= stats.size) { + fs.close(file); + self.close(function(err, result) { + if(err) return callback(err, self); + return callback(null, self); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + } + + // Process the first write + process.nextTick(writeChunk); + }); + }); +}; + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {GridStore~resultCallback} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {null} + */ +GridStore.prototype.close = function(callback) { + var self = this; + + if(self.mode[0] == "w") { + // Set up options + var options = self.writeConcern; + + if(self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err, chunk) { + if(err && typeof callback == 'function') return callback(err); + + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + // Build the mongo object + if(self.uploadDate != null) { + files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) { + if(err && typeof callback == 'function') return callback(err); + + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } + } else if(self.mode[0] == "r") { + if(typeof callback == 'function') + callback(null, null); + } else { + if(typeof callback == 'function') + callback(new MongoError(f("Illegal mode %s", self.mode), null)); + } +}; + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + */ +GridStore.prototype.chunkCollection = function(callback) { + if(typeof callback == 'function') + return this.db.collection((this.root + ".chunks"), callback); + return this.db.collection((this.root + ".chunks")); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {GridStore~resultCallback} callback the command callback. + * @return {null} + */ +GridStore.prototype.unlink = function(callback) { + var self = this; + deleteChunks(this, function(err) { + if(err!==null) { + err.message = "at deleteChunks: " + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if(err!==null) { + err.message = "at collection: " + err.message; + return callback(err); + } + + collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +}; + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + */ +GridStore.prototype.collection = function(callback) { + if(typeof callback == 'function') + this.db.collection(this.root + ".files", callback); + return this.db.collection(this.root + ".files"); +}; + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {GridStore~readlinesCallback} callback the command callback. + * @return {null} + */ +GridStore.prototype.readlines = function(separator, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + separator = args.length ? args.shift() : "\n"; + + this.read(function(err, data) { + if(err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for(var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +}; + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {GridStore~resultCallback} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {null} + */ +GridStore.prototype.rewind = function(callback) { + var self = this; + + if(this.currentChunk.chunkNumber != 0) { + if(this.mode[0] == "w") { + deleteChunks(self, function(err, gridStore) { + if(err) return callback(err); + self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if(err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +}; + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~readCallback} callback the command callback. + * @return {null} + */ +GridStore.prototype.read = function(length, buffer, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if(finalLength == 0 && finalBuffer.length == 0) return callback(new MongoError("File does not exist"), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if(err) return callback(err); + + if(chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if(finalBuffer._index > 0) { + callback(null, finalBuffer) + } else { + callback(new MongoError("no chunks found for file, possibly corrupt"), null); + } + } + }); +} + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~tellCallback} callback the command callback. + * @return {null} + */ +GridStore.prototype.tell = function(callback) { + callback(null, this.position); +}; + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {GridStore~gridStoreCallback} callback the command callback. + * @return {null} + */ +GridStore.prototype.seek = function(position, seekLocation, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + seekLocation = args.length ? args.shift() : null; + + // Seek only supports read mode + if(self.mode != 'r') { + return callback(new MongoError("seek is only supported for mode r")) + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if(seekLocationFinal == GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if(seekLocationFinal == GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition/self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; + + seekChunk(); +} + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if(query != null) { + collection.findOne(query, options, function(err, doc) { + if(err) return error(err); + + // Check if the collection for the files exists otherwise prepare the new one + if(doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode != 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; + return error(new MongoError(f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename))), self); + } + + // Process the mode of the object + if(self.mode == "r") { + nthChunk(self, 0, options, function(err, chunk) { + if(err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err, result) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + var collection2 = self.chunkCollection(); + // No file exists set up write mode + if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err, result) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error (err) { + if(error.err) return; + callback(error.err = err); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if(typeof close === "function") { callback = close; close = null; } + var finalClose = typeof close == 'boolean' ? close : false; + + if(self.mode != "w") { + callback(new MongoError(f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename))), null); + } else { + if(self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while(leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + var firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + // If we have left over data write it + if(leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for(var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err, result) { + if(err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if(numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if(finalClose) { + return self.close(function(err, result) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if(finalClose) { + return self.close(function(err, result) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + '_id': self.fileId, + 'filename': self.filename, + 'contentType': self.contentType, + 'length': self.position ? self.position : 0, + 'chunkSize': self.chunkSize, + 'uploadDate': self.uploadDate, + 'aliases': self.aliases, + 'metadata': self.metadata + }; + + var md5Command = {filemd5:self.fileId, root:self.root}; + self.db.command(md5Command, function(err, results) { + if(err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { + if(err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if(self.fileId != null) { + self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) { + if(err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** +* The collection to be used for holding the files and chunks collection. +* +* @classconstant DEFAULT_ROOT_COLLECTION +**/ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** +* Default file mime type +* +* @classconstant DEFAULT_CONTENT_TYPE +**/ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** +* Seek mode where the given length is absolute. +* +* @classconstant IO_SEEK_SET +**/ +GridStore.IO_SEEK_SET = 0; + +/** +* Seek mode where the given length is an offset to the current read/write head. +* +* @classconstant IO_SEEK_CUR +**/ +GridStore.IO_SEEK_CUR = 1; + +/** +* Seek mode where the given length is an offset to the end of the file. +* +* @classconstant IO_SEEK_END +**/ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {GridStore~resultCallback} callback result from exists. + * @return {null} + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + ".files", function(err, collection) { + if(err) return callback(err); + + // Build query + var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) + ? {'filename':fileIdObject} + : {'_id':fileIdObject}; // Attempt to locate file + + // We have a specific query + if(fileIdObject != null + && typeof fileIdObject == 'object' + && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, {readPreference:readPreference}, function(err, item) { + if(err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +}; + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {GridStore~resultCallback} callback result from exists. + * @return {null} + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + // Ensure we have correct values + if(rootCollection != null && typeof rootCollection == 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection((rootCollectionFinal + ".files"), function(err, collection) { + if(err) return callback(err); + + collection.find({}, {readPreference:readPreference}, function(err, cursor) { + if(err) return callback(err); + + cursor.each(function(err, item) { + if(item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +}; + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {GridStore~readCallback} callback the command callback. + * @return {null} + */ + +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + // Make sure we are not reading out of bounds + if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); + if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); + if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); + + if(offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if(err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +}; + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {GridStore~readlinesCallback} callback the command callback. + * @return {null} + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + + var finalSeperator = separator == null ? "\n" : separator; + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +}; + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options=null] Optional settings. + * @param {GridStore~resultCallback} callback the command callback. + * @return {null} + */ +GridStore.unlink = function(db, names, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if(names.constructor == Array) { + var tc = 0; + for(var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function(result) { + if(--tc == 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, "w", options).open(function(err, gridStore) { + if(err) return callback(err); + deleteChunks(gridStore, function(err, result) { + if(err) return callback(err); + gridStore.collection(function(err, collection) { + if(err) return callback(err); + collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) { + callback(err, self); + }); + }); + }); + }); + } +}; + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, callback) { + // If we have a buffer write it using the writeBuffer method + if(Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, new Buffer(data, 'binary'), close, callback); + } +} + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if(options.w != null) finalOptions.w = options.w; + if(options.journal == true) finalOptions.j = options.journal; + if(options.j == true) finalOptions.j = options.j; + if(options.fsync == true) finalOptions.fsync = options.fsync; + if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +} + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = {w:1}; + options = options || {}; + + // Local options verification + if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(options); + } else if(options.safe != null && typeof options.safe == 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if(typeof options.safe == "boolean") { + finalOptions = {w: (options.safe ? 1 : 0)}; + } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(self.options); + } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { + finalOptions = _setWriteConcernHash(self.safe); + } else if(typeof self.safe == "boolean") { + finalOptions = {w: (self.safe ? 1 : 0)}; + } + + // Ensure we don't have an invalid combination of write concerns + if(finalOptions.w < 1 + && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new MongoError("No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true"); + + // Return the options + return finalOptions; +} + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + */ +var GridStoreStream = function(gs) { + var self = this; + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +} + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if(!self.gs.isOpen) { + self.gs.open(function(err) { + if(err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } +} + +// Called by stream +GridStoreStream.prototype._read = function(n) { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if(err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if(self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if(buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if(buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if(self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + } + + // Set read length + var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if(!self.gs.isOpen) { + self.gs.open(function(err, gs) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if(err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +} + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +} + +GridStoreStream.prototype.write = function(chunk, encoding, callback) { + var self = this; + if(self.endCalled) return self.emit('error', new MongoError('attempting to write to stream after end called')) + // Do we have to open the gridstore + if(!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +} + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if(chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); + }); + } + + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); +} + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js b/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..7f5f7a2 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,413 @@ +"use strict"; + +var parse = require('./url_parser') + , Server = require('./server') + , Mongos = require('./mongos') + , ReplSet = require('./replset') + , ReadPreference = require('./read_preference') + , Db = require('./db'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @return {MongoClient} a MongoClient instance. + */ +function MongoClient() { + /** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The connected database. + */ + + /** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {MongoClient~connectCallback} callback The command result callback + * @return {null} + */ + this.connect = MongoClient.connect; +} + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {MongoClient~connectCallback} callback The command result callback + * @return {null} + */ +MongoClient.connect = function(url, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Set default empty server options + var serverOptions = options.server || {}; + var mongosOptions = options.mongos || {}; + var replSetServersOptions = options.replSet || options.replSetServers || {}; + var dbOptions = options.db || {}; + + // If callback is null throw an exception + if(callback == null) + throw new Error("no callback function provided"); + + // Parse the string + var object = parse(url, options); + + // Merge in any options for db in options object + if(dbOptions) { + for(var name in dbOptions) object.db_options[name] = dbOptions[name]; + } + + // Added the url to the options + object.db_options.url = url; + + // Merge in any options for server in options object + if(serverOptions) { + for(var name in serverOptions) object.server_options[name] = serverOptions[name]; + } + + // Merge in any replicaset server options + if(replSetServersOptions) { + for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; + } + + if(replSetServersOptions.ssl + || replSetServersOptions.sslValidate + || replSetServersOptions.sslCA + || replSetServersOptions.sslCert + || replSetServersOptions.sslKey + || replSetServersOptions.sslPass) { + object.server_options.ssl = replSetServersOptions.ssl; + object.server_options.sslValidate = replSetServersOptions.sslValidate; + object.server_options.sslCA = replSetServersOptions.sslCA; + object.server_options.sslCert = replSetServersOptions.sslCert; + object.server_options.sslKey = replSetServersOptions.sslKey; + object.server_options.sslPass = replSetServersOptions.sslPass; + } + + // Merge in any replicaset server options + if(mongosOptions) { + for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; + } + + if(typeof object.server_options.poolSize == 'number') { + if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; + if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; + } + + if(mongosOptions.ssl + || mongosOptions.sslValidate + || mongosOptions.sslCA + || mongosOptions.sslCert + || mongosOptions.sslKey + || mongosOptions.sslPass) { + object.server_options.ssl = mongosOptions.ssl; + object.server_options.sslValidate = mongosOptions.sslValidate; + object.server_options.sslCA = mongosOptions.sslCA; + object.server_options.sslCert = mongosOptions.sslCert; + object.server_options.sslKey = mongosOptions.sslKey; + object.server_options.sslPass = mongosOptions.sslPass; + } + + // We need to ensure that the list of servers are only either direct members or mongos + // they cannot be a mix of monogs and mongod's + var totalNumberOfServers = object.servers.length; + var totalNumberOfMongosServers = 0; + var totalNumberOfMongodServers = 0; + var serverConfig = null; + var errorServers = {}; + + // Failure modes + if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); + + // If we have no db setting for the native parser try to set the c++ one first + object.db_options.native_parser = _setNativeParser(object.db_options); + // If no auto_reconnect is set, set it to true as default for single servers + if(typeof object.server_options.auto_reconnect != 'boolean') { + object.server_options.auto_reconnect = true; + } + + // If we have more than a server, it could be replicaset or mongos list + // need to verify that it's one or the other and fail if it's a mix + // Connect to all servers and run ismaster + for(var i = 0; i < object.servers.length; i++) { + // Set up socket options + var providedSocketOptions = object.server_options.socketOptions || {}; + + var _server_options = { + poolSize:1 + , socketOptions: { + connectTimeoutMS: providedSocketOptions.connectTimeoutMS || 30000 + , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || 30000 + } + , auto_reconnect:false}; + + // Ensure we have ssl setup for the servers + if(object.server_options.ssl) { + _server_options.ssl = object.server_options.ssl; + _server_options.sslValidate = object.server_options.sslValidate; + _server_options.sslCA = object.server_options.sslCA; + _server_options.sslCert = object.server_options.sslCert; + _server_options.sslKey = object.server_options.sslKey; + _server_options.sslPass = object.server_options.sslPass; + } else if(object.rs_options.ssl) { + _server_options.ssl = object.rs_options.ssl; + _server_options.sslValidate = object.rs_options.sslValidate; + _server_options.sslCA = object.rs_options.sslCA; + _server_options.sslCert = object.rs_options.sslCert; + _server_options.sslKey = object.rs_options.sslKey; + _server_options.sslPass = object.rs_options.sslPass; + } + + // Error + var error = null; + // Set up the Server object + var _server = object.servers[i].domain_socket + ? new Server(object.servers[i].domain_socket, _server_options) + : new Server(object.servers[i].host, object.servers[i].port, _server_options); + + var setName; + + var connectFunction = function(__server) { + // Attempt connect + new Db(object.dbName, __server, {w:1, native_parser:false}).open(function(err, db) { + // Update number of servers + totalNumberOfServers = totalNumberOfServers - 1; + // If no error do the correct checks + if(!err) { + // Close the connection + db.close(); + var isMasterDoc = db.serverConfig.isMasterDoc; + // Check what type of server we have + if(isMasterDoc.setName) { + totalNumberOfMongodServers++; + setName = isMasterDoc.setName; + } + if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; + } else { + error = err; + errorServers[__server.host + ":" + __server.port] = __server; + } + + if(totalNumberOfServers == 0) { + // Error out + if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { + return callback(error, null); + } + + // If we have a mix of mongod and mongos, throw an error + if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { + if(db) db.close(); + return process.nextTick(function() { + try { + callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); + } catch (err) { + throw err + } + }) + } + + if(totalNumberOfMongodServers == 0 + && totalNumberOfMongosServers == 0 + && object.servers.length == 1) { + var obj = object.servers[0]; + serverConfig = obj.domain_socket ? + new Server(obj.domain_socket, object.server_options) + : new Server(obj.host, obj.port, object.server_options); + } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) { + var finalServers = object.servers + .filter(function(serverObj) { + return errorServers[serverObj.host + ":" + serverObj.port] == null; + }) + .map(function(serverObj) { + return new Server(serverObj.host, serverObj.port, object.server_options); + }); + // Clean out any error servers + errorServers = {}; + // Set up the final configuration + if(totalNumberOfMongodServers > 0) { + try { + if (totalNumberOfMongodServers == 1) { + object.rs_options.replicaSet = object.rs_options.replicaSet || setName; + } + serverConfig = new ReplSet(finalServers, object.rs_options); + } catch(err) { + return callback(err, null); + } + } else { + serverConfig = new Mongos(finalServers, object.mongos_options); + } + } + + if(serverConfig == null) { + return process.nextTick(function() { + try { + callback(new Error("Could not locate any valid servers in initial seed list")); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // Ensure no firing of open event before we are ready + serverConfig.emitOpen = false; + // Set up all options etc and connect to the database + _finishConnecting(serverConfig, object, options, callback) + } + }); + } + + // Wrap the context of the call + connectFunction(_server); + } +} + +var _setNativeParser = function(db_options) { + if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; + + try { + require('mongodb-core').BSON.BSONNative.BSON; + return true; + } catch(err) { + return false; + } +} + +var _finishConnecting = function(serverConfig, object, options, callback) { + // If we have a readPreference passed in by the db options + if(typeof object.db_options.readPreference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); + } else if(typeof object.db_options.read_preference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); + } + + // Do we have readPreference tags + if(object.db_options.readPreference && object.db_options.readPreferenceTags) { + object.db_options.readPreference.tags = object.db_options.readPreferenceTags; + } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { + object.db_options.readPreference.tags = object.db_options.read_preference_tags; + } + + // Get the socketTimeoutMS + var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; + + // If we have a replset, override with replicaset socket timeout option if available + if(serverConfig instanceof ReplSet) { + socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; + } + + // Set socketTimeout to the same as the connectTimeoutMS or 30 sec + serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; + serverConfig.socketTimeoutMS = serverConfig.connectTimeoutMS; + + // Set up the db options + var db = new Db(object.dbName, serverConfig, object.db_options); + // Open the db + db.open(function(err, db){ + + if(err) { + return process.nextTick(function() { + try { + callback(err, null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // Reset the socket timeout + serverConfig.socketTimeoutMS = socketTimeoutMS || 0; + + // Return object + if(err == null && object.auth){ + // What db to authenticate against + var authentication_db = db; + if(object.db_options && object.db_options.authSource) { + authentication_db = db.db(object.db_options.authSource); + } + + // Build options object + var options = {}; + if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; + if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; + + // Authenticate + authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ + if(success){ + process.nextTick(function() { + try { + callback(null, db); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } else { + if(db) db.close(); + process.nextTick(function() { + try { + callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + }); + } else { + process.nextTick(function() { + try { + callback(err, db); + } catch (err) { + if(db) db.close(); + throw err + } + }) + } + }); +} + +module.exports = MongoClient diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongos.js b/node_modules/mongoose/node_modules/mongodb/lib/mongos.js new file mode 100644 index 0000000..88913c0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/mongos.js @@ -0,0 +1,454 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , MongoCR = require('mongodb-core').MongoCR + , CMongos = require('mongodb-core').Mongos + , Cursor = require('./cursor') + , Server = require('./server') + , Store = require('./topology_base').Store + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Mongos = require('mongodb').Mongos, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using Mongos + * var server = new Server('localhost', 27017); + * var db = new Db('test', new Mongos([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @return {Mongos} a Mongos instance. + */ +var Mongos = function(servers, options) { + if(!(this instanceof Mongos)) return new Mongos(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw new MongoError("all seed list instances must be of the Server type"); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + if(options.socketOptions.socketTimeoutMS) + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Create the Mongos + var mongos = new CMongos(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + mongos.addAuthProvider('mongocr', new MongoCR()); + + // Internal state + this.s = { + // Create the Mongos + mongos: mongos + // Server capabilities + , sCapabilities: sCapabilities + // Debug turned on + , debug: debug + // Store option defaults + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Actual store of callbacks + , store: store + // Options + , options: options + } + + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } + }); + + // Last ismaster + Object.defineProperty(this, 'numberOfConnectedServers', { + enumerable:true, get: function() { return self.s.mongos.connectedServers().length; } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.mongos.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.mongos.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(Mongos, EventEmitter); + +// Connect +Mongos.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.mongos.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect'); + self.s.store.execute(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.mongos.removeAllListeners(e); + }); + + // Set up listeners + self.s.mongos.once('timeout', errorHandler('timeout')); + self.s.mongos.once('error', errorHandler('error')); + self.s.mongos.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Set up serverConfig listeners + self.s.mongos.on('joined', relay('joined')); + self.s.mongos.on('left', relay('left')); + self.s.mongos.on('fullsetup', relay('fullsetup')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + self.s.mongos.once('timeout', connectErrorHandler('timeout')); + self.s.mongos.once('error', connectErrorHandler('error')); + self.s.mongos.once('close', connectErrorHandler('close')); + self.s.mongos.once('connect', connectHandler); + // Reconnect server + self.s.mongos.on('reconnect', reconnectHandler); + + // Start connection + self.s.mongos.connect(_options); +} + +Mongos.prototype.parserType = function() { + return this.s.mongos.parserType(); +} + +// Server capabilities +Mongos.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); + return this.s.sCapabilities; +} + +// Command +Mongos.prototype.command = function(ns, cmd, options, callback) { + this.s.mongos.command(ns, cmd, options, callback); +} + +// Insert +Mongos.prototype.insert = function(ns, ops, options, callback) { + this.s.mongos.insert(ns, ops, options, function(e, m) { + callback(e, m) + }); +} + +// Update +Mongos.prototype.update = function(ns, ops, options, callback) { + this.s.mongos.update(ns, ops, options, callback); +} + +// Remove +Mongos.prototype.remove = function(ns, ops, options, callback) { + this.s.mongos.remove(ns, ops, options, callback); +} + +// IsConnected +Mongos.prototype.isConnected = function() { + return this.s.mongos.isConnected(); +} + +// Insert +Mongos.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.mongos.cursor(ns, cmd, options); +} + +Mongos.prototype.setBSONParserType = function(type) { + return this.s.mongos.setBSONParserType(type); +} + +Mongos.prototype.lastIsMaster = function() { + return this.s.mongos.lastIsMaster(); +} + +Mongos.prototype.close = function(forceClosed) { + this.s.mongos.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +Mongos.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.auth.apply(this.s.mongos, args); +} + +/** + * All raw connections + * @method + * @return {array} + */ +Mongos.prototype.connections = function() { + return this.s.mongos.connections(); +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +module.exports = Mongos; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js b/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 0000000..73b253a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,104 @@ +"use strict"; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * ReadPreference = require('mongodb').ReadPreference, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * test.equal(null, err); + * // Perform a read + * var cursor = db.collection('t').find({}); + * cursor.setReadPreference(ReadPreference.PRIMARY); + * cursor.toArray(function(err, docs) { + * test.equal(null, err); + * db.close(); + * }); + * }); + */ + +/** + * Creates a new ReadPreference instance + * + * Read Preferences + * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). + * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. + * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. + * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. + * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. + * + * @class + * @param {string} mode The ReadPreference mode as listed above. + * @param {object} tags An object representing read preference tags. + * @property {string} mode The ReadPreference mode. + * @property {object} tags The ReadPreference tags. + * @return {ReadPreference} a ReadPreference instance. + */ +var ReadPreference = function(mode, tags) { + if(!(this instanceof ReadPreference)) + return new ReadPreference(mode, tags); + this._type = 'ReadPreference'; + this.mode = mode; + this.tags = tags; +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.isValid = function(_mode) { + return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED + || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED + || _mode == ReadPreference.NEAREST + || _mode == true || _mode == false || _mode == null); +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.prototype.isValid = function(mode) { + var _mode = typeof mode == 'string' ? mode : this.mode; + return ReadPreference.isValid(_mode); +} + +/** + * @ignore + */ +ReadPreference.prototype.toObject = function() { + var object = {mode:this.mode}; + + if(this.tags != null) { + object['tags'] = this.tags; + } + + return object; +} + +/** + * @ignore + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest' + +/** + * @ignore + */ +module.exports = ReadPreference; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/replset.js b/node_modules/mongoose/node_modules/mongodb/lib/replset.js new file mode 100644 index 0000000..caab621 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/replset.js @@ -0,0 +1,527 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , Server = require('./server') + , Mongos = require('./mongos') + , Cursor = require('./cursor') + , ReadPreference = require('./read_preference') + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , CServer = require('mongodb-core').Server + , CReplSet = require('mongodb-core').ReplSet + , CoreReadPreference = require('mongodb-core').ReadPreference + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {string} options.replicaSet The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @return {ReplSet} a ReplSet instance. + */ +var ReplSet = function(servers, options) { + if(!(this instanceof ReplSet)) return new ReplSet(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw new MongoError("all seed list instances must be of the Server type"); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + } + + // Get the name + var replicaSet = options.replicaSet || options.rs_name; + + // Set up options + finalOptions.setName = replicaSet; + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + if(options.connectWithNoPrimary == true) { + finalOptions.secondaryOnlyConnectionAllowed = true; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Translate the options + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + + // Create the ReplSet + var replset = new CReplSet(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + replset.addAuthProvider('mongocr', new MongoCR()); + + // Listen to reconnect event + replset.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + replset: replset + // Server capabilities + , sCapabilities: null + // Debug tag + , tag: options.tag + // Store options + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Store + , store: store + // Options + , options: options + } + + // Debug + if(debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable:true, get: function() { return replset; } + }); + } + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return replset.lastIsMaster(); } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return replset.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return replset.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(ReplSet, EventEmitter); + +// Ensure the right read Preference object +var translateReadPreference = function(options) { + if(typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + return options; +} + +ReplSet.prototype.parserType = function() { + return this.s.replset.parserType(); +} + +// Connect method +ReplSet.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.replset.removeAllListeners(e); + }); + + // Set up listeners + self.s.replset.once('timeout', errorHandler('timeout')); + self.s.replset.once('error', errorHandler('error')); + self.s.replset.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + } + } + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if(t == 'start') { + self.emit('ha_connect', t, state); + } else if(t == 'end') { + self.emit('ha_ismaster', t, state); + } + } + + // Set up serverConfig listeners + self.s.replset.on('joined', replsetRelay('joined')); + self.s.replset.on('left', relay('left')); + self.s.replset.on('ping', relay('ping')); + self.s.replset.on('ha', relayHa); + + self.s.replset.on('fullsetup', function(topology) { + self.emit('fullsetup', null, self); + }); + + self.s.replset.on('all', function(topology) { + self.emit('all', null, self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.replset.removeListener(e, connectErrorHandler); + }); + + self.s.replset.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.replset.destroy(); + + // Try to callback + try { + callback(err); + } catch(err) { + if(!self.s.replset.isConnected()) + process.nextTick(function() { throw err; }) + } + } + } + + // Set up listeners + self.s.replset.once('timeout', connectErrorHandler('timeout')); + self.s.replset.once('error', connectErrorHandler('error')); + self.s.replset.once('close', connectErrorHandler('close')); + self.s.replset.once('connect', connectHandler); + + // Start connection + self.s.replset.connect(_options); +} + +// Server capabilities +ReplSet.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); + return this.s.sCapabilities; +} + +// Command +ReplSet.prototype.command = function(ns, cmd, options, callback) { + options = translateReadPreference(options); + this.s.replset.command(ns, cmd, options, callback); +} + +// Insert +ReplSet.prototype.insert = function(ns, ops, options, callback) { + this.s.replset.insert(ns, ops, options, callback); +} + +// Update +ReplSet.prototype.update = function(ns, ops, options, callback) { + this.s.replset.update(ns, ops, options, callback); +} + +// Remove +ReplSet.prototype.remove = function(ns, ops, options, callback) { + this.s.replset.remove(ns, ops, options, callback); +} + +// IsConnected +ReplSet.prototype.isConnected = function() { + return this.s.replset.isConnected(); +} + +ReplSet.prototype.setBSONParserType = function(type) { + return this.s.replset.setBSONParserType(type); +} + +// Insert +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + return this.s.replset.cursor(ns, cmd, options); +} + +ReplSet.prototype.lastIsMaster = function() { + return this.s.replset.lastIsMaster(); +} + +ReplSet.prototype.close = function(forceClosed) { + var self = this; + this.s.replset.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +ReplSet.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.auth.apply(this.s.replset, args); +} + +/** + * All raw connections + * @method + * @return {array} + */ +ReplSet.prototype.connections = function() { + return this.s.replset.connections(); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +module.exports = ReplSet; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/server.js b/node_modules/mongoose/node_modules/mongodb/lib/server.js new file mode 100644 index 0000000..f823fac --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/server.js @@ -0,0 +1,408 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , CServer = require('mongodb-core').Server + , Cursor = require('./cursor') + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using single Server + * var db = new Db('test', new Server('localhost', 27017);); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options=null] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @return {Server} a Server instance. + */ +var Server = function(host, port, options) { + options = options || {}; + if(!(this instanceof Server)) return new Server(host, port, options); + EventEmitter.call(this); + var self = this; + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if(host.indexOf('\/') != -1) { + if(port != null && typeof port == 'object') { + options = port; + port = null; + } + } else if(port == null) { + throw new MongoError('port must be specified'); + } + + // Clone options + var clonedOptions = shallowClone(options); + clonedOptions.host = host; + clonedOptions.port = port; + + // Reconnect + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + if(typeof options.socketOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + clonedOptions.keepAlive = true; + } + + if(typeof options.socketOptions.noDelay == 'boolean') { + clonedOptions.noDelay = options.socketOptions.noDelay; + } + } + + // Add the cursor factory function + clonedOptions.cursorFactory = Cursor; + clonedOptions.reconnect = reconnect; + clonedOptions.emitError = emitError; + clonedOptions.size = poolSize; + + // Translate the options + if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; + if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; + if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; + if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; + if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; + + // Add the non connection store + clonedOptions.disconnectHandler = store; + + // Create an instance of a server instance from mongodb-core + var server = new CServer(clonedOptions); + // Server capabilities + var sCapabilities = null; + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + server: server + // Server capabilities + , sCapabilities: null + // Cloned options + , clonedOptions: clonedOptions + // Reconnect + , reconnect: reconnect + // Emit error + , emitError: emitError + // Pool size + , poolSize: poolSize + // Store Options + , storeOptions: storeOptions + // Store + , store: store + // Host + , host: host + // Port + , port: port + // Options + , options: options + } + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.server.bson; + } + }); + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { + return self.s.server.lastIsMaster(); + } + }); + + // Last ismaster + Object.defineProperty(this, 'poolSize', { + enumerable:true, get: function() { return self.s.server.connections().length; } + }); + + Object.defineProperty(this, 'autoReconnect', { + enumerable:true, get: function() { return self.s.reconnect; } + }); + + Object.defineProperty(this, 'host', { + enumerable:true, get: function() { return self.s.host; } + }); + + Object.defineProperty(this, 'port', { + enumerable:true, get: function() { return self.s.port; } + }); +} + +inherits(Server, EventEmitter); + +Server.prototype.parserType = function() { + return this.s.server.parserType(); +} + +// Connect +Server.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.server.removeListener(e, connectHandlers[e]); + }); + + self.s.server.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect', self); + self.s.store.execute(); + } + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.server.removeAllListeners(e); + }); + + // Set up listeners + self.s.server.once('timeout', errorHandler('timeout')); + self.s.server.once('error', errorHandler('error')); + self.s.server.on('close', errorHandler('close')); + // Only called on destroy + self.s.server.once('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Add the event handlers + self.s.server.once('timeout', connectHandlers.timeout); + self.s.server.once('error', connectHandlers.error); + self.s.server.once('close', connectHandlers.close); + self.s.server.once('connect', connectHandler); + // Reconnect server + self.s.server.on('reconnect', reconnectHandler); + + // Start connection + self.s.server.connect(_options); +} + +// Server capabilities +Server.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); + return this.s.sCapabilities; +} + +// Command +Server.prototype.command = function(ns, cmd, options, callback) { + this.s.server.command(ns, cmd, options, callback); +} + +// Insert +Server.prototype.insert = function(ns, ops, options, callback) { + this.s.server.insert(ns, ops, options, callback); +} + +// Update +Server.prototype.update = function(ns, ops, options, callback) { + this.s.server.update(ns, ops, options, callback); +} + +// Remove +Server.prototype.remove = function(ns, ops, options, callback) { + this.s.server.remove(ns, ops, options, callback); +} + +// IsConnected +Server.prototype.isConnected = function() { + return this.s.server.isConnected(); +} + +// Insert +Server.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.server.cursor(ns, cmd, options); +} + +Server.prototype.setBSONParserType = function(type) { + return this.s.server.setBSONParserType(type); +} + +Server.prototype.lastIsMaster = function() { + return this.s.server.lastIsMaster(); +} + +Server.prototype.close = function(forceClosed) { + this.s.server.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +Server.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.auth.apply(this.s.server, args); +} + +/** + * All raw connections + * @method + * @return {array} + */ +Server.prototype.connections = function() { + return this.s.server.connections(); +} + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js b/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js new file mode 100644 index 0000000..460cd31 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js @@ -0,0 +1,140 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + , f = require('util').format; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} + + // Internal state + this.s = { + storedOps: storedOps + , storeOptions: storeOptions + , topology: topology + } + + Object.defineProperty(this, 'length', { + enumerable:true, get: function() { return self.s.storedOps.length; } + }); +} + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if(this.s.storeOptions.force) return callback(new MongoError("db closed by application")); + if(this.s.storeOptions.bufferMaxEntries == 0) return callback(new MongoError(f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries))); + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(new MongoError(f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries))); + } + + return; + } + + this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) +} + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if(this.s.storeOptions.force) return callback(new MongoError("db closed by application")); + if(this.s.storeOptions.bufferMaxEntries == 0) return callback(new MongoError(f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries))); + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(new MongoError(f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries))); + } + + return; + } + + this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) +} + +Store.prototype.flush = function() { + while(this.s.storedOps.length > 0) { + this.s.storedOps.shift().c(new MongoError(f("no connection available for operation"))); + } +} + +Store.prototype.execute = function() { + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Execute all the stored ops + while(ops.length > 0) { + var op = ops.shift(); + + if(op.t == 'cursor') { + op.o[op.m].apply(op.o, op.p); + } else { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } +} + +Store.prototype.all = function() { + return this.s.storedOps; +} + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true + , get: function () { return value; } + }); + } + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + + if(ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if(ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if(ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if(ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + // If no min or max wire version set to 0 + if(ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if(ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, "hasAggregationCursor", aggregationCursor); + setup_get_property(this, "hasWriteCommands", writeCommands); + setup_get_property(this, "hasTextSearch", textSearch); + setup_get_property(this, "hasAuthCommands", authCommands); + setup_get_property(this, "hasListCollectionsCommand", listCollections); + setup_get_property(this, "hasListIndexesCommand", listIndexes); + setup_get_property(this, "minWireVersion", ismaster.minWireVersion); + setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); + setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); +} + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js b/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..c4f9719 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,281 @@ +"use strict"; + +var ReadPreference = require('./read_preference'); + +module.exports = function(url, options) { + // Ensure we have a default options object if none set + options = options || {}; + // Variables + var connection_part = ''; + var auth_part = ''; + var query_string_part = ''; + var dbName = 'admin'; + + // Must start with mongodb + if(url.indexOf("mongodb://") != 0) + throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); + // If we have a ? mark cut the query elements off + if(url.indexOf("?") != -1) { + query_string_part = url.substr(url.indexOf("?") + 1); + connection_part = url.substring("mongodb://".length, url.indexOf("?")) + } else { + connection_part = url.substring("mongodb://".length); + } + + // Check if we have auth params + if(connection_part.indexOf("@") != -1) { + auth_part = connection_part.split("@")[0]; + connection_part = connection_part.split("@")[1]; + } + + // Check if the connection string has a db + if(connection_part.indexOf(".sock") != -1) { + if(connection_part.indexOf(".sock/") != -1) { + dbName = connection_part.split(".sock/")[1]; + connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); + } + } else if(connection_part.indexOf("/") != -1) { + dbName = connection_part.split("/")[1]; + connection_part = connection_part.split("/")[0]; + } + + // Result object + var object = {}; + + // Pick apart the authentication part of the string + var authPart = auth_part || ''; + var auth = authPart.split(':', 2); + + // Decode the URI components + auth[0] = decodeURIComponent(auth[0]); + if(auth[1]){ + auth[1] = decodeURIComponent(auth[1]); + } + + // Add auth to final object if we have 2 elements + if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; + + // Variables used for temporary storage + var hostPart; + var urlOptions; + var servers; + var serverOptions = {socketOptions: {}}; + var dbOptions = {read_preference_tags: []}; + var replSetServersOptions = {socketOptions: {}}; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = {}; + + // Let's check if we are using a domain socket + if(url.match(/\.sock/)) { + // Split out the socket part + var domainSocket = url.substring( + url.indexOf("mongodb://") + "mongodb://".length + , url.lastIndexOf(".sock") + ".sock".length); + // Clean out any auth stuff if any + if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; + servers = [{domain_socket: domainSocket}]; + } else { + // Split up the db + hostPart = connection_part; + // Parse all server results + servers = hostPart.split(',').map(function(h) { + var _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + var hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; + } + // Return the mapped object + return {host: _host, port: _port}; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if(!opt) return; + var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; + // Options implementations + switch(name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = (value == 'true'); + dbOptions.slaveOk = (value == 'true'); + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = (value == 'true'); + break; + case 'minPoolSize': + throw new Error("minPoolSize not supported"); + case 'maxIdleTimeMS': + throw new Error("maxIdleTimeMS not supported"); + case 'waitQueueMultiple': + throw new Error("waitQueueMultiple not supported"); + case 'waitQueueTimeoutMS': + throw new Error("waitQueueTimeoutMS not supported"); + case 'uuidRepresentation': + throw new Error("uuidRepresentation not supported"); + case 'ssl': + if(value == 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + break; + } + serverOptions.ssl = (value == 'true'); + replSetServersOptions.ssl = (value == 'true'); + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = (value == 'true'); + break; + case 'fsync': + dbOptions.fsync = (value == 'true'); + break; + case 'journal': + dbOptions.j = (value == 'true'); + break; + case 'safe': + dbOptions.safe = (value == 'true'); + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = (value == 'true'); + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if(isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if(value == 'GSSAPI') { + // If no password provided decode only the principal + if(object.auth == null) { + var urlDecodeAuthPart = decodeURIComponent(authPart); + if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); + object.auth = {user: urlDecodeAuthPart, password: null}; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if(value == 'MONGODB-X509') { + object.auth = {user: decodeURIComponent(authPart)}; + } + + // Only support GSSAPI or MONGODB-CR for now + if(value != 'GSSAPI' + && value != 'MONGODB-X509' + && value != 'MONGODB-CR' + && value != 'SCRAM-SHA-1' + && value != 'PLAIN') + throw new Error("only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + // Split up into key, value pairs + var values = value.split(','); + var o = {}; + // For each value split into key, value + values.forEach(function(x) { + var v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); + dbOptions.read_preference = value; + break; + case 'readPreferenceTags': + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + var tagObject = {}; + if(value == null || value == '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + var tags = value.split(/\,/); + for(var i = 0; i < tags.length; i++) { + var parts = tags[i].trim().split(/\:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + break; + default: + break; + } + }); + + // No tags: should be null (not []) + if(dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if((dbOptions.w == -1 || dbOptions.w == 0) && ( + dbOptions.journal == true + || dbOptions.fsync == true + || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") + + // If no read preference set it to primary + if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; + + // Add servers to result + object.servers = servers; + // Returned parsed object + return object; +} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..e13c85c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/utils.js @@ -0,0 +1,233 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + +var shallowClone = function(obj) { + var copy = {}; + for(var name in obj) copy[name] = obj[name]; + return copy; +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +var formatSortValue = exports.formatSortValue = function(sortDirection) { + var value = ("" + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]"); + } +}; + +var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if(sortValue == null) return null; + if (Array.isArray(sortValue)) { + if(sortValue.length === 0) { + return null; + } + + for(var i = 0; i < sortValue.length; i++) { + if(sortValue[i].constructor == String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if(sortValue != null && typeof sortValue == 'object') { + orderBy = sortValue; + } else if (typeof sortValue == 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return orderBy; +}; + +var checkCollectionName = function checkCollectionName (collectionName) { + if('string' !== typeof collectionName) { + throw Error("collection name must be a String"); + } + + if(!collectionName || collectionName.indexOf('..') != -1) { + throw Error("collection names cannot be empty"); + } + + if(collectionName.indexOf('$') != -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + throw Error("collection names must not contain '$'"); + } + + if(collectionName.match(/^\.|\.$/) != null) { + throw Error("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the colletion name + if(!!~collectionName.indexOf("\x00")) { + throw new Error("collection names cannot contain a null character"); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if(callback == null) return; + if(value2) return callback(err, value1, value2); + return callback(err, value1); + } catch(err) { + process.nextTick(function() { throw err; }); + return false; + } + + return true; +} + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = new MongoError(msg); + + // Get all object keys + var keys = typeof error == 'object' + ? Object.keys(error) + : []; + + for(var i = 0; i < keys.length; i++) { + e[keys[i]] = error[keys[i]]; + } + + return e; +} + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if(typeof hint == 'string') { + finalHint = hint; + } else if(Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if(hint != null && typeof hint == 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if('string' == typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if(Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if('string' == typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if(Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if(isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if(isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join("_"), keys: keys, fieldHash: fieldHash + } +} + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == toString.call(arg) +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var decorateCommand = function(command, options, exclude) { + for(var name in options) { + if(exclude[name] == null) command[name] = options[name]; + } + + return command; +} + +exports.shallowClone = shallowClone; +exports.getSingleProperty = getSingleProperty; +exports.checkCollectionName = checkCollectionName; +exports.toError = toError; +exports.formattedOrderClause = formattedOrderClause; +exports.parseIndexOptions = parseIndexOptions; +exports.normalizeHintField = normalizeHintField; +exports.handleCallback = handleCallback; +exports.decorateCommand = decorateCommand; +exports.isObject = isObject; +exports.debugOptions = debugOptions; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.travis.yml b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.travis.yml new file mode 100644 index 0000000..c8a809e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.travis.yml @@ -0,0 +1,11 @@ +os: linux +language: node_js +node_js: + - node + - '0.10' + - iojs +sudo: false +env: + - MONGODB_VERSION=2.4.x + - MONGODB_VERSION=2.6.x + - MONGODB_VERSION=3.0.x diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..e6fc093 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,174 @@ +1.1.32 05-20-2015 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 05-19-2015 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 05-18-2015 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 05-17-2015 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 05-12-2015 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 05-12-2015 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 05-06-2015 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 04-24-2015 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 04-22-2015 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 04-15-2015 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 04-10-2015 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 03-26-2015 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 03-24-2015 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 03-21-2015 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 03-17-2015 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 03-16-2015 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 03-06-2015 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 03-04-2015 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 02-26-2015 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 02-24-2015 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 02-16-2015 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 02-02-2015 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 31-01-2015 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 21-01-2015 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 09-12-2015 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 18-12-2014 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 18-12-2014 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 17-12-2014 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 17-12-2014 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 01-12-2014 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 20-11-2014 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 14-11-2014 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 29-10-2014 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 24-10-2014 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 21-10-2014 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 07-10-2014 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 07-10-2014 +---------------- +- Dependency issue solved + +1.0.0 07-10-2014 +---------------- +- Initial release of mongodb-core diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile new file mode 100644 index 0000000..e942bc6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile @@ -0,0 +1,14 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + cp -R ./docs/history-header.md ./docs/content/meta/release-notes.md + more ./HISTORY.md >> ./docs/content/meta/release-notes.md + hugo -s docs/ -d ../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. + +.PHONY: total diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..9275c8d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md @@ -0,0 +1,225 @@ +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/christkv/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next steps is to get more inn depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md new file mode 100644 index 0000000..fe03ea0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md @@ -0,0 +1,18 @@ +Testing setup +============= + +Single Server +------------- +mongod --dbpath=./db + +Replicaset +---------- +mongo --nodb +var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) +x.startSet(); +var config = x.getReplSetConfig() +x.initiate(config); + +Mongos +------ +var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json new file mode 100644 index 0000000..c5eca92 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json @@ -0,0 +1,60 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/tests/functional/operation_example_tests.js", + "lib/topologies/mongos.js", + "lib/topologies/command_result.js", + "lib/topologies/read_preference.js", + "lib/topologies/replset.js", + "lib/topologies/server.js", + "lib/topologies/session.js", + "lib/topologies/replset_state.js", + "lib/connection/logger.js", + "lib/connection/connection.js", + "lib/cursor.js", + "lib/error.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..60c9d53 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js @@ -0,0 +1,17 @@ +module.exports = { + MongoError: require('./lib/error') + , Server: require('./lib/topologies/server') + , ReplSet: require('./lib/topologies/replset') + , Mongos: require('./lib/topologies/mongos') + , Logger: require('./lib/connection/logger') + , Cursor: require('./lib/cursor') + , ReadPreference: require('./lib/topologies/read_preference') + , BSON: require('bson') + // Raw operations + , Query: require('./lib/connection/commands').Query + // Auth mechanisms + , MongoCR: require('./lib/auth/mongocr') + , X509: require('./lib/auth/x509') + , Plain: require('./lib/auth/plain') + , GSSAPI: require('./lib/auth/gssapi') +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..c442b9b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,244 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, pool, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// +// Initialize step +var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Perform initialization + mongo_auth_process.init(username, password, function(err, context) { + if(err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if(err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { + // Build the sasl start command + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: payload + , autoAuthorize: 1 + }; + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if(err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build final command + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + mongo_auth_process.transition(null, function(err, payload) { + if(err) return callback(err, null); + callback(null, r); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..d0e9f59 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,160 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function() { + this.authStore = []; +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeMongoCR = function(connection) { + // Let's start the process + server.command(f("%s.$cmd", db) + , { getnonce: 1 } + , { connection: connection }, function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if(err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password); + key = md5.digest('hex'); + } + + // Execute command + server.command(f("%s.$cmd", db) + , { authenticate: 1, user: username, nonce: nonce, key:key} + , { connection: connection }, function(err, r) { + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + }); + } + + // Get the connection + executeMongoCR(connections.shift()); + } +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..31ce872 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,150 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Create payload + var payload = new Binary(f("\x00%s\x00%s", username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1 + , mechanism: 'PLAIN' + , payload: payload + , autoAuthorize: 1 + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..b14f9db --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,316 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @return {ScramSHA1} A cursor instance + */ +var ScramSHA1 = function() { + this.authStore = []; +} + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for(var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +var passwordDigest = function(username, password) { + if(typeof username != 'string') throw new MongoError("username must be a string"); + if(typeof password != 'string') throw new MongoError("password must be a string"); + if(password.length == 0) throw new MongoError("password cannot be empty"); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + return md5.digest('hex'); +} + +// XOR two buffers +var xor = function(a, b) { + if (!Buffer.isBuffer(a)) a = new Buffer(a) + if (!Buffer.isBuffer(b)) b = new Buffer(b) + var res = [] + if (a.length > b.length) { + for (var i = 0; i < b.length; i++) { + res.push(a[i] ^ b[i]) + } + } else { + for (var i = 0; i < a.length; i++) { + res.push(a[i] ^ b[i]) + } + } + return new Buffer(res); +} + +// Create a final digest +var hi = function(data, salt, iterations) { + // Create digest + var digest = function(msg) { + var hmac = crypto.createHmac('sha1', data); + hmac.update(msg); + return new Buffer(hmac.digest('base64'), 'base64'); + } + + // Create variables + salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) + var ui = digest(salt); + var u1 = ui; + + for(var i = 0; i < iterations - 1; i++) { + u1 = digest(u1); + ui = xor(ui, u1); + } + + return ui; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeScram = function(connection) { + // Clean up the user + username = username.replace('=', "=3D").replace(',', '=2C'); + + // Create a random nonce + var nonce = crypto.randomBytes(24).toString('base64'); + // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' + var firstBare = f("n=%s,r=%s", username, nonce); + + // Build command structure + var cmd = { + saslStart: 1 + , mechanism: 'SCRAM-SHA-1' + , payload: new Binary(f("n,,%s", firstBare)) + , autoAuthorize: 1 + } + + // Handle the error + var handleError = function(err, r) { + if(err) { + errorObject = err; return false; + } else if(r.result['$err']) { + errorObject = r.result; return false; + } else if(r.result['errmsg']) { + errorObject = r.result; return false; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true + } + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if(_count == 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(_count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + } + + var handleEnd = function(_err, _r) { + // Handle any error + handleError(_err, _r) + // Adjust the number of connections + count = count - 1; + // Execute the finish + finish(count, numberOfValidConnections); + } + + // Execute start sasl command + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + + // Do we have an error, handle it + if(handleError(err, r) == false) { + count = count - 1; + + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.payload.value()) + + // Unpack dictionary + var iterations = parseInt(dict.i, 10); + var salt = dict.s; + var rnonce = dict.r; + + // Set up start of proof + var withoutProof = f("c=biws,r=%s", rnonce); + var passwordDig = passwordDigest(username, password); + var saltedPassword = hi(passwordDig + , new Buffer(salt, 'base64') + , iterations); + + // Create the client key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer("Client Key")); + var clientKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Create the stored key + var hash = crypto.createHash('sha1'); + hash.update(clientKey); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); + + // Create the authentication message + var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); + + // Create client signature + var hmac = crypto.createHmac('sha1', storedKey); + hmac.update(new Buffer(authMsg)); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); + + // Create client proof + var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); + + // Create client final + var clientFinal = [withoutProof, clientProof].join(','); + + // Generate server key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer('Server Key')) + var serverKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Generate server signature + var hmac = crypto.createHmac('sha1', serverKey); + hmac.update(new Buffer(authMsg)) + var serverSig = new Buffer(hmac.digest('base64'), 'base64'); + + // + // Create continue message + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Binary(new Buffer(clientFinal)) + } + + // + // Execute sasl continue + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + if(r && r.result.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Buffer(0) + } + + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } + }); + }); + } + + // Get the connection + executeScram(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + + +module.exports = ScramSHA1; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..177ede5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,234 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, pool, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r && typeof r == 'object' && r.result['$err']) { + errorObject = r.result; + } else if(r && typeof r == 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: '' + , autoAuthorize: 1 + }; + + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.init(username, password, function(err) { + if(err) return callback(err); + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + if(doc.done) return callback(null, true); + callback(new Error("Authentication failed"), false); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..641990e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,145 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1 + , mechanism: 'MONGODB-X509' + , user: username + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..8529dd0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,482 @@ +"use strict"; + +var f = require('util').format + , Long = require('bson').Long + , setProperty = require('./utils').setProperty + , getProperty = require('./utils').getProperty + , getSingleProperty = require('./utils').getSingleProperty; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var OP_QUERY = 2004; +var OP_GETMORE = 2005; +var OP_KILL_CURSORS = 2007; + +// Query flags +var OPTS_NONE = 0; +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if(ns == null) throw new Error("ns must be specified for query"); + if(query == null) throw new Error("query must be specified for query"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new Error("namespace cannot contain a null character"); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = _requestId++; + + // Serialization option + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = false; + this.oplogReply = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +} + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + // Basic length + var length = 4 + + Buffer.byteLength(self.ns) + + 1 + 4 + 4 + + self.bson.calculateObjectSize(self.query, self.serializeFunctions, true) + + (4 * 4); + + // Additional size for field selection + if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + length += self.bson.calculateObjectSize(self.returnFieldSelector, self.serializeFunctions, true); + } + + // Allocate buffer for message + var _buffer = new Buffer(length); + + // Set up the flags + var flags = 0; + if(this.tailable) flags |= OPTS_TAILABLE_CURSOR; + if(this.slaveOk) flags |= OPTS_SLAVE; + if(this.oplogReply) flags |= OPTS_OPLOG_REPLAY; + if(this.noCursorTimeout) flags |= OPTS_NO_CURSOR_TIMEOUT; + if(this.awaitData) flags |= OPTS_AWAIT_DATA; + if(this.exhaust) flags |= OPTS_EXHAUST; + if(this.partial) flags |= OPTS_PARTIAL; + + // If batchSize is different to self.numberToReturn + if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; + + // Initial index + var index = 4; + + // Write header information requestId + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // Write header information responseTo + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write header information OP_QUERY + _buffer[index + 3] = (OP_QUERY >> 24) & 0xff; + _buffer[index + 2] = (OP_QUERY >> 16) & 0xff; + _buffer[index + 1] = (OP_QUERY >> 8) & 0xff; + _buffer[index] = (OP_QUERY) & 0xff; + index = index + 4; + + // Write header information flags + _buffer[index + 3] = (flags >> 24) & 0xff; + _buffer[index + 2] = (flags >> 16) & 0xff; + _buffer[index + 1] = (flags >> 8) & 0xff; + _buffer[index] = (flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write header information flags numberToSkip + _buffer[index + 3] = (this.numberToSkip >> 24) & 0xff; + _buffer[index + 2] = (this.numberToSkip >> 16) & 0xff; + _buffer[index + 1] = (this.numberToSkip >> 8) & 0xff; + _buffer[index] = (this.numberToSkip) & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Serialize query + var queryLength = this.bson.serializeWithBufferAndIndex(this.query + , this.checkKeys + , _buffer, index + , this.serializeFunctions) - index + 1; + + // Write header information flags queryLength + _buffer[index + 3] = (queryLength >> 24) & 0xff; + _buffer[index + 2] = (queryLength >> 16) & 0xff; + _buffer[index + 1] = (queryLength >> 8) & 0xff; + _buffer[index] = (queryLength) & 0xff; + index = index + 4; + + // Add to the index + index = index - 4 + queryLength; + _buffer[index + 1] = 0x00; + + // If we have field selectors + if(this.returnFieldSelector && Object.keys(this.returnFieldSelector).length > 0) { + var fieldSelectorLength = this.bson.serializeWithBufferAndIndex(this.returnFieldSelector + , this.checkKeys + , _buffer + , index + , this.serializeFunctions) - index + 1; + + // Write header information flags fieldSelectorLength + _buffer[index + 3] = (fieldSelectorLength >> 24) & 0xff; + _buffer[index + 2] = (fieldSelectorLength >> 16) & 0xff; + _buffer[index + 1] = (fieldSelectorLength >> 8) & 0xff; + _buffer[index] = (fieldSelectorLength) & 0xff; + index = index + 4; + + index = index - 4 + fieldSelectorLength; + _buffer[index + 1] = 0x00; + } + + // Write total document length + _buffer[3] = (index >> 24) & 0xff; + _buffer[2] = (index >> 16) & 0xff; + _buffer[1] = (index >> 8) & 0xff; + _buffer[0] = (index) & 0xff; + // Return buffer + return _buffer; +} + +Query.getRequestId = function() { + return ++_requestId; +} + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = (OP_GETMORE) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getHighBits()) & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, cursorIds) { + this.requestId = _requestId++; + this.cursorIds = cursorIds; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); + + // Create command buffer + var index = 0; + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = (OP_KILL_CURSORS) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = (this.cursorIds.length) & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for(var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +} + +var Response = function(bson, data, opts) { + opts = opts || {promoteLongs: true}; + this.parsed = false; + + // + // Parse Header + // + this.index = 0; + this.raw = data; + this.data = data; + this.bson = bson; + this.opts = opts; + + // Read the message length + this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the request id for this reply + this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the id of the request that triggered the response + this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Skip op-code field + this.index = this.index + 4; + + // Unpack flags + this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the cursor + var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + // Create long object + this.cursorId = new Long(lowBits, highBits); + + // Unpack the starting from + this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the number of objects returned + this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; + this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; +} + +Response.prototype.isParsed = function() { + return this.parsed; +} + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if(this.parsed) return; + options = options || {}; + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + + // + // Parse Body + // + for(var i = 0; i < this.numberReturned; i++) { + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Parse options + var _options = {promoteLongs: this.opts.promoteLongs}; + + // If we have raw results specified slice the return document + if(raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +} + +module.exports = { + Query: Query + , GetMore: GetMore + , Response: Response + , KillCursor: KillCursor +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..2a9a8d8 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,454 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , net = require('net') + , tls = require('tls') + , f = require('util').format + , getSingleProperty = require('./utils').getSingleProperty + , debugOptions = require('./utils').debugOptions + , Response = require('./commands').Response + , MongoError = require('../error') + , Logger = require('./logger'); + +var _id = 0; +var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' + , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' + , 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = options.messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); + // Debug information + if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; + this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; + this.connectionTimeout = options.connectionTimeout || 0; + this.socketTimeout = options.socketTimeout || 0; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('\/') != -1; + + // Serialize commands using function + this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; + this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true + + // If ssl not enabled + if(!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true + } + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; +} + +inherits(Connection, EventEmitter); + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); + // Emit the error + if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); + } +} + +var timeoutHandler = function(self) { + return function() { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit("timeout" + , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) + , self); + } +} + +var closeHandler = function(self) { + return function(hadError) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + // Emit close event + if(!hadError) { + self.emit("close" + , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) + , self); + } + } +} + +var dataHandler = function(self) { + return function(data) { + // Parse until we are done with the data + while(data.length > 0) { + // If we still have bytes to read on the current message + if(self.bytesRead > 0 && self.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; + // Check if the current chunk contains the rest of the message + if(remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(self.buffer, self.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + self.bytesRead = self.bytesRead + data.length; + + // Reset state of buffer + data = new Buffer(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + try { + var emitBuffer = self.buffer; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Emit the buffer + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch(err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if(self.stubBuffer != null && self.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if(self.stubBuffer.length + data.length > 4) { + // Prepad the data + var newData = new Buffer(self.stubBuffer.length + data.length); + self.stubBuffer.copy(newData, 0); + data.copy(newData, self.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + + } else { + + // Add the the bytes to the stub buffer + var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); + // Copy existing stub buffer + self.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, self.stubBuffer.length); + // Exit parsing loop + data = new Buffer(0); + } + } else { + if(data.length > 4) { + // Retrieve the message size + // var sizeOfMessage = data.readUInt32LE(0); + var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; + // If we have a negative sizeOfMessage emit error and return + if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { + self.buffer = new Buffer(sizeOfMessage); + // Copy all the data into the buffer + data.copy(self.buffer, 0); + // Update bytes read + self.bytesRead = data.length; + // Update sizeOfMessage + self.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + + } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { + try { + var emitBuffer = data; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch (err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ + sizeOfMessage:sizeOfMessage, + bytesRead:0, + buffer:null, + stubBuffer:null}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + + // Clear out the state of the parser + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + } else { + var emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } + } else { + // Create a buffer that contains the space for the non-complete message + self.stubBuffer = new Buffer(data.length) + // Copy the data to the stub buffer + data.copy(self.stubBuffer, 0); + // Exit parsing loop + data = new Buffer(0); + } + } + } + } + } +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + var self = this; + _options = _options || {}; + // Check if we are overriding the promoteLongs + if(typeof _options.promoteLongs == 'boolean') { + self.responseOptions.promoteLongs = _options.promoteLongs; + } + + // Create new connection instance + self.connection = self.domainSocket + ? net.createConnection(self.host) + : net.createConnection(self.port, self.host); + + // Set the options for the connection + self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + self.connection.setTimeout(self.connectionTimeout); + self.connection.setNoDelay(self.noDelay); + + // If we have ssl enabled + if(self.ssl) { + var sslOptions = { + socket: self.connection + , rejectUnauthorized: self.rejectUnauthorized + } + + if(self.ca) sslOptions.ca = self.ca; + if(self.cert) sslOptions.cert = self.cert; + if(self.key) sslOptions.key = self.key; + if(self.passphrase) sslOptions.passphrase = self.passphrase; + + // Attempt SSL connection + self.connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if(self.connection.authorizationError && self.rejectUnauthorized) { + return self.emit("error", self.connection.authorizationError, self, {ssl:true}); + } + + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + } else { + self.connection.on('connect', function() { + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + } + + // Add handlers for events + self.connection.once('error', errorHandler(self)); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + if(this.connection) this.connection.destroy(); +} + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + // Debug log + if(this.logger.isDebug()) this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); + // Write out the command + this.connection.write(buffer, 'binary'); +} + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return "" + this.id; +} + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return {id: this.id, host: this.host, port: this.port}; +} + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + return !this.connection.destroyed && this.connection.writable; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..e50a011 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,193 @@ +"use strict"; + +var f = require('util').format + , MongoError = require('../error'); + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if(!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + var self = this; + this.className = className; + + // Current logger + if(currentLogger == null && options.logger) { + currentLogger = options.logger; + } else if(currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if(level == null) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if(filteredClasses[this.className] == null) classFilters[this.className] = true; +} + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if(this.isDebug() + && classFilters[this.className] && (filteredClasses[this.className] || Object.keys(filteredClasses).length == 0)) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +} + +/** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.info = function(message, object) { + if(this.isInfo() + && classFilters[this.className] && (filteredClasses[this.className] || Object.keys(filteredClasses).length == 0)) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.error = function(message, object) { + if(this.isError() + && classFilters[this.className] && (filteredClasses[this.className] || Object.keys(filteredClasses).length == 0)) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Is the logger set at info level + * @method + * @return {boolean} + */ +Logger.prototype.isInfo = function() { + return level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isError = function() { + return level == 'error' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at debug level + * @method + * @return {boolean} + */ +Logger.prototype.isDebug = function() { + return level == 'debug'; +} + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +} + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +} + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if(typeof logger != 'function') throw new MongoError("current logger must be a function"); + currentLogger = logger; +} + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if(type == 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +} + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); + level = _level; +} + +module.exports = Logger; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..27274d1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,266 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , Connection = require('./connection') + , Query = require('./commands').Query + , Logger = require('./logger') + , f = require('util').format; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(options) { + var self = this; + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + this.size = typeof options.size == 'number' ? options.size : 5; + // Message handler + this.messageHandler = options.messageHandler; + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Contains all connections + this.connections = []; + this.state = DISCONNECTED; + // Round robin index + this.index = 0; + this.dead = false; + // Logger instance + this.logger = Logger('Pool', options); + // Pool id + this.id = _id++; + // Grouping tag used for debugging purposes + this.tag = options.tag; +} + +inherits(Pool, EventEmitter); + +var errorHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('error', err, self); + } + } +} + +var timeoutHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timedout out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('timeout', err, self); + } + } +} + +var closeHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('close', err, self); + } + } +} + +var parseErrorHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('parseError', err, self); + } + } +} + +var connectHandler = function(self) { + return function(connection) { + self.connections.push(connection); + // We have connected to all servers + if(self.connections.length == self.size) { + self.state = CONNECTED; + // Done connecting + self.emit("connect", self); + } + } +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function() { + this.state = DESTROYED; + // Set dead + this.dead = true; + // Destroy all the connections + this.connections.forEach(function(c) { + // Destroy all event emitters + ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { + c.removeAllListeners(e); + }); + + // Destroy the connection + c.destroy(); + }); +} + +var execute = null; + +try { + execute = setImmediate; +} catch(err) { + execute = process.nextTick; +} + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function(_options) { + var self = this; + // Set to connecting + this.state = CONNECTING + // No dead + this.dead = false; + // Connect all sockets + for(var i = 0; i < this.size; i++) { + execute(function() { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Add all handlers + connection.once('close', closeHandler(self)); + connection.once('error', errorHandler(self)); + connection.once('timeout', timeoutHandler(self)); + connection.once('parseError', parseErrorHandler(self)); + connection.on('connect', connectHandler(self)); + + // Start connection + connection.connect(_options); + }); + } +} + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + // if(this.dead) return null; + var connection = this.connections[this.index++]; + this.index = this.index % this.connections.length; + return connection; +} + +/** + * Get all pool connections + * @method + * @return {array} + */ +Pool.prototype.getAll = function() { + return this.connections.slice(0); +} + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + for(var i = 0; i < this.connections.length; i++) { + if(!this.connections[i].isConnected()) return false; + } + + return this.state == CONNECTED; +} + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +module.exports = Pool; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..7f0b89d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,77 @@ +"use strict"; + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable:true, + set: function(value) { + if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); + // Flip the bit to 1 + if(value == true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if(value == false && (values.flags & flag) == flag) values.flags ^= flag; + prop.value = value; + } + , get: function() { return prop.value; } + }); +} + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable:true, + get: function() { + // Not parsed yet, parse it + if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if(typeof func == 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for(var name in fObj) tObj[name] = fObj[name]; + return tObj; +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + return domain.bind(callback); +} + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.bindToCurrentDomain = bindToCurrentDomain; +exports.debugOptions = debugOptions; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..78a3dba --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,617 @@ +"use strict"; + +var Long = require('bson').Long + , Logger = require('./connection/logger') + , MongoError = require('./error') + , f = require('util').format; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + // Cursor reference + var self = this; + // Initial query + var query = null; + + // Cursor connection + this.connection = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null + , documents: options.documents || [] + , cursorIndex: 0 + , dead: false + , killed: false + , init: false + , notified: false + , limit: options.limit || cmd.limit || 0 + , skip: options.skip || cmd.skip || 0 + , batchSize: options.batchSize || cmd.batchSize || 1000 + , currentLimit: 0 + // Result field name if not a cursor (contains the array of results) + , transforms: options.transforms + } + + // Callback controller + this.callbacks = null; + + // Logger + this.logger = Logger('Cursor', options); + + // + // Did we pass in a cursor id + if(typeof cmd == 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + } else if(cmd instanceof Long) { + this.cursorState.cursorId = cmd; + } +} + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +} + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +} + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +} + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +} + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +} + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +} + +// +// Execute getMore command +var execGetMore = function(self, callback) { + if(self.logger.isDebug()) self.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(self.query))) + // Determine if it's a raw query + var raw = self.options.raw || self.cmd.raw; + // We have a wire protocol handler + self.server.wireProtocolHandler.getMore(self.bson, self.ns, self.cursorState, self.cursorState.batchSize, raw, self.connection, self.callbacks, self.options, callback); +} + +// +// Execute the first query +var execInitialQuery = function(self, query, cmd, options, cursorState, connection, logger, callbacks, callback) { + if(logger.isDebug()) { + logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(cmd) + , JSON.stringify(query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if (result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 && !cmd.find) { + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + cursorState.documents = result.documents[0].result; + cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + cursorState.cursorId = result.cursorId; + cursorState.documents = result.documents; + + // Transform the results with passed in transformation method if provided + if(cursorState.transforms && typeof cursorState.transforms.query == 'function') { + cursorState.documents = cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + + // If we have a raw query decorate the function + if(options.raw || cmd.raw) { + queryCallback.raw = options.raw || cmd.raw; + } + + // Set up callback + callbacks.register(query.requestId, queryCallback); + + // Write the initial command out + connection.write(query.toBin()); +} + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } +} + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +} + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead == true; +} + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed == true; +} + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified == true; +} + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +} + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); + this.cursorState.currentLimit = this.cursorState.currentLimit + length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + length; + + // Transform the doc with passed in transformation method if provided + if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { + // Transform all the elements + for(var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Return elements + return elements; +} + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { + if(callback) callback(null, null); + return; + } + + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.cursorState.cursorId, this.connection, callback); +} + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if(this.cursorState.init) { + if(!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +} + +/** + * Validate if the connection is dead and return error + */ +var isConnectionDead = function(self, callback) { + if(self.connection + && !self.connection.isConnected()) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + callback(MongoError.create(f('connection to host %s:%s was destroyed', self.connection.host, self.connection.port))) + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if(self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if(self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, MongoError.create("cursor is dead")); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if(self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +var nextFunction = function(self, callback) { + // We have notified about it + if(self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + // Cursor is killed return null + if(isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if(isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if(isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if(!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + try { + // Get a server + self.server = self.topology.getServer(self.options); + // Get a connection + self.connection = self.server.getConnection(); + // Get the callbacks + self.callbacks = self.server.getCallbacks(); + } catch(err) { + return callback(err); + } + + // Set as init + self.cursorState.init = true; + // Get the right wire protocol command + self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); + } + + // Process exhaust messages + var processExhaustMessages = function(err, result) { + if(err) { + self.cursorState.dead = true; + self.callbacks.unregister(self.query.requestId); + return callback(err); + } + + // Concatenate all the documents + self.cursorState.documents = self.cursorState.documents.concat(result.documents); + + // If we have no documents left + if(Long.ZERO.equals(result.cursorId)) { + self.cursorState.cursorId = Long.ZERO; + self.callbacks.unregister(self.query.requestId); + return nextFunction(self, callback); + } + + // Set up next listener + self.callbacks.register(result.requestId, processExhaustMessages) + + // Initial result + if(self.cursorState.cursorId == null) { + self.cursorState.cursorId = result.cursorId; + nextFunction(self, callback); + } + } + + // If we have exhaust + if(self.cmd.exhaust && self.cursorState.cursorId == null) { + // Handle all the exhaust responses + self.callbacks.register(self.query.requestId, processExhaustMessages); + // Write the initial command out + return self.connection.write(self.query.toBin()); + } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { + return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); + } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { + self.callbacks.unregister(self.query.requestId); + return setCursorNotified(self, callback); + } else if(self.cmd.exhaust) { + return setTimeout(function() { + if(Long.ZERO.equals(self.cursorState.cursorId)) return; + nextFunction(self, callback); + }, 1); + } + + // If we don't have a cursorId execute the first query + if(self.cursorState.cursorId == null) { + // Check if connection is dead and return if not possible to + // execute the query against the db + if(isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // query, cmd, options, cursorState, callback + execInitialQuery(self, self.query, self.cmd, self.options, self.cursorState, self.connection, self.logger, self.callbacks, function(err, r) { + if(err) return handleCallback(callback, err, null); + if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } else if(self.cursorState.cursorIndex == self.cursorState.documents.length + && !Long.ZERO.equals(self.cursorState.cursorId)) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if(isConnectionDead(self, callback)) return; + + // Execute the next get more + execGetMore(self, function(err, doc) { + if(err) return handleCallback(callback, err); + if(self.cursorState.documents.length == 0 && Long.ZERO.equals(self.cursorState.cursorId)) self.cursorState.dead = true; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if(self.cursorState.documents.length == 0 && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } + + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && Long.ZERO.equals(self.cursorState.cursorId)) { + setCursorDeadAndNotified(self, callback); + } else { + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Transform the doc with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +} + +module.exports = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..086c5ef --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Creates a new MongoError + * @class + * @augments Error + * @param {string} message The error message + * @return {MongoError} A cursor instance + */ +function MongoError(message) { + this.name = 'MongoError'; + this.message = message; + Error.captureStackTrace(this, MongoError); +} + +/** + * Creates a new MongoError object + * @class + * @param {object} options The error options + * @return {MongoError} A cursor instance + */ +MongoError.create = function(options) { + var err = null; + + if(options instanceof Error) { + err = new MongoError(options.message); + err.stack = options.stack; + } else if(typeof options == 'string') { + err = new MongoError(options); + } else { + err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); + // Other options + for(var name in options) { + err[name] = options[name]; + } + } + + return err; +} + +// Extend JavaScript error +MongoError.prototype = new Error; + +module.exports = MongoError; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..dcceda4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,59 @@ +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results : [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: "" + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: "fail", + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: "" + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js new file mode 100644 index 0000000..ff7bf1b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js @@ -0,0 +1,37 @@ +"use strict"; + +var setProperty = require('../connection/utils').setProperty + , getProperty = require('../connection/utils').getProperty + , getSingleProperty = require('../connection/utils').getSingleProperty; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection) { + this.result = result; + this.connection = connection; +} + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +} + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +} + +module.exports = CommandResult; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..371bdb5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,975 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , BasicCursor = require('../cursor') + , Server = require('./server') + , Logger = require('../connection/logger') + , ReadPreference = require('./read_preference') + , Session = require('./session') + , MongoError = require('../error'); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +// Instance id +var mongosId = 0; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +var State = function(readPreferenceStrategies) { + // Internal state + this.s = { + connectedServers: [] + , disconnectedServers: [] + , readPreferenceStrategies: readPreferenceStrategies + } +} + +// +// A Mongos connected +State.prototype.connected = function(server) { + // Locate in disconnected servers and remove + this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.connectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.connectedServers.push(server); +} + +// +// A Mongos disconnected +State.prototype.disconnected = function(server) { + // Locate in disconnected servers and remove + this.s.connectedServers = this.s.connectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.disconnectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.disconnectedServers.push(server); +} + +// +// Return the list of disconnected servers +State.prototype.disconnectedServers = function() { + return this.s.disconnectedServers.slice(0); +} + +// +// Get connectedServers +State.prototype.connectedServers = function() { + return this.s.connectedServers.slice(0) +} + +// +// Get all servers +State.prototype.getAll = function() { + return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); +} + +// +// Get all connections +State.prototype.getAllConnections = function() { + var connections = []; + this.s.connectedServers.forEach(function(e) { + connections = connections.concat(e.connections()); + }); + return connections; +} + +// +// Destroy the state +State.prototype.destroy = function() { + // Destroy any connected servers + while(this.s.connectedServers.length > 0) { + var server = this.s.connectedServers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Server destroy + server.destroy(); + // Add to list of disconnected servers + this.s.disconnectedServers.push(server); + } +} + +// +// Are we connected +State.prototype.isConnected = function() { + return this.s.connectedServers.length > 0; +} + +// +// Pick a server +State.prototype.pickServer = function(readPreference) { + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { + return this.s.readPreferenceStrategies[readPreference].pickServer(connectedServers, readPreference); + } + + // No valid connections + if(this.s.connectedServers.length == 0) throw new MongoError("no mongos proxy available"); + // Pick first one + return this.s.connectedServers[0]; +} + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#joined + * @fires Mongos#left + */ +var Mongos = function(seedlist, options) { + var self = this; + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // BSON Parser, ensure we have a single instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + // Pick the right bson parser + var bson = options.bson ? options.bson : bsonInstance; + // Add bson parser to options + options.bson = bson; + + // The Mongos state + this.s = { + // Seed list for sharding passed in + seedlist: seedlist + // Passed in options + , options: options + // Logger + , logger: Logger('Mongos', options) + // Reconnect tries + , reconnectTries: options.reconnectTries || 30 + // Ha interval + , haInterval: options.haInterval || 5000 + // Have omitted fullsetup + , fullsetup: false + // Cursor factory + , Cursor: options.cursorFactory || BasicCursor + // Current credentials used for auth + , credentials: [] + // BSON Parser + , bsonInstance: bsonInstance + , bson: bson + // Default state + , state: DISCONNECTED + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // Unique instance id + , id: mongosId++ + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Current retries left + , retriesLeft: options.reconnectTries || 30 + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + } + + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 1000; + + // Create a new state for the mongos + this.s.mongosState = new State(this.s.readPreferenceStrategies); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.mongosState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'mongos'; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.mongosState; } + }); +} + +inherits(Mongos, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Mongos.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + var connectedServers = this.s.mongosState.connectedServers(); + if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); + return null; +} + +/** + * Initiate server connect + * @method + */ +Mongos.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(mongosInquirer(self, self.s), self.s.haInterval); + // Additional options + if(_options) for(var name in _options) self.s.options[name] = _options[name]; + // For all entries in the seedlist build a server instance + self.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Don't emit errors + opts.emitError = true; + // Create a new Server + self.s.mongosState.disconnected(new Server(opts)); + }); + + // Get the disconnected servers + var servers = self.s.mongosState.disconnectedServers(); + + // Attempt to connect to all the servers + while(servers.length > 0) { + // Get the server + var server = servers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, server)); + server.once('close', errorHandlerTemp(self, self.s, server)); + server.once('timeout', errorHandlerTemp(self, self.s, server)); + server.once('parseError', errorHandlerTemp(self, self.s, server)); + server.once('connect', connectHandler(self, self.s, 'connect')); + + if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); + // Attempt to connect + server.connect(); + } +} + +/** + * Destroy the server connection + * @method + */ +Mongos.prototype.destroy = function(emitClose) { + this.s.state = DESTROYED; + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + // Destroy the state + this.s.mongosState.destroy(); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.s.mongosState.isConnected(); +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +// +// Operations +// + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + var server = null; + // Ensure we have no options + options = options || {}; + + // We need to execute the command on all servers + if(options.onAll) { + var servers = self.s.mongosState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(state, ns); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + + try { + // Get a primary + server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.mongosState.getAll().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { + if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; + this.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Mongos.prototype.addAuthProvider = function(name, provider) { + this.s.authProviders[name] = provider; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Mongos.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = this.s.mongosState.pickServer(options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Mongos.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return this.s.mongosState.pickServer(options.readPreference); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + return this.s.mongosState.getAllConnections(); +} + +// +// Inquires about state changes +// +var mongosInquirer = function(self, state) { + return function() { + if(state.state == DESTROYED) return + if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; + + // If we have a disconnected site + if(state.state == DISCONNECTED && state.retriesLeft == 0) { + self.destroy(); + return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); + } else if(state == DISCONNECTED) { + state.retriesLeft = state.retriesLeft - 1; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.mongosState.isConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Log the information + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); + + // Let's query any disconnected proxies + var disconnectedServers = state.mongosState.disconnectedServers(); + if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); + + // Count of connections waiting to be connected + var connectionCount = disconnectedServers.length; + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); + + // Let's attempt to reconnect + while(disconnectedServers.length > 0) { + var server = disconnectedServers.shift(); + if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); + + // Remove any listeners + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, server)); + server.once('close', errorHandlerTemp(self, state, server)); + server.once('timeout', errorHandlerTemp(self, state, server)); + server.once('connect', connectHandler(self, state, 'ha')); + // Start connect + server.connect(); + } + + // Let's keep monitoring but wait for possible timeout to happen + return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); + } +} + +// +// Error handler for initial connect +var errorHandlerTemp = function(self, state, server) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Signal disconnect of server + state.mongosState.disconnected(server); + } +} + +// +// Handlers +var errorHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); + state.mongosState.disconnected(server); + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + if(state.emitError) self.emit('error', err, server); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); + state.mongosState.disconnected(server); + + // No more servers emit close event if no entries left + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); + state.mongosState.disconnected(server); + + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +// Connect handler +var connectHandler = function(self, state, e) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // finish processing the server + var processNewServer = function(_server) { + // Add the server handling code + if(_server.isConnected()) { + _server.once('error', errorHandler(self, state)); + _server.once('close', closeHandler(self, state)); + _server.once('timeout', timeoutHandler(self, state)); + _server.once('parseError', timeoutHandler(self, state)); + } + + // Emit joined event + self.emit('joined', 'mongos', _server); + + // Add to list connected servers + state.mongosState.connected(_server); + + // Do we have a reconnect event + if('ha' == e && state.mongosState.connectedServers().length == 1) { + self.emit('reconnect', _server); + } + + // Full setup + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length > 0 && + !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup'); + } + + // all connected + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length == state.seedlist.length && + !state.all) { + state.all = true; + self.emit('all'); + } + + // Set connected + if(state.state == DISCONNECTED) { + state.state = CONNECTED; + self.emit('connect', self); + } + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(server); + + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(server); + }])); + } + } +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } +} + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(state, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(state, db + ".dummy"); + // Add new credentials to list + state.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(state, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < state.credentials.length; i++) { + if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); + } + + // Set new list of credentials + state.credentials = filteredCredentials; +} + +var processReadPreference = function(cmd, options) { + options = options || {} + // No read preference specified + if(options.readPreference == null) return cmd; +} + +// +// Execute write operation +var executeWriteOperation = function(state, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + try { + // Get a primary + server = state.mongosState.pickServer(); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + // Execute the command + server[op](ns, ops, options, callback); +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +module.exports = Mongos; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..913ca1b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,106 @@ +"use strict"; + +var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * var cursor = server.cursor('db.test' + * , {find: 'db.test', query: {}} + * , {readPreference: new ReadPreference('secondary')}); + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Pool instance + * @class + * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {object} tags The tags object + * @param {object} [options] Additional read preference options + * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @property {object} tags The tags object + * @property {object} options Additional read preference options + * @return {ReadPreference} + */ +var ReadPreference = function(preference, tags, options) { + this.preference = preference; + this.tags = tags; + this.options = options; +} + +/** + * This needs slaveOk bit set + * @method + * @return {boolean} + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.preference) != -1; +} + +/** + * Are the two read preference equal + * @method + * @return {boolean} + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.preference == this.preference; +} + +/** + * Return JSON representation + * @method + * @return {Object} + */ +ReadPreference.prototype.toJSON = function() { + var readPreference = {mode: this.preference}; + if(Array.isArray(this.tags)) readPreference.tags = this.tags; + return readPreference; +} + +/** + * Primary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..892fbbc --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1303 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , debugOptions = require('../connection/utils').debugOptions + , EventEmitter = require('events').EventEmitter + , Server = require('./server') + , ReadPreference = require('./read_preference') + , MongoError = require('../error') + , Ping = require('./strategies/ping') + , Session = require('./session') + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , State = require('./replset_state') + , Logger = require('../connection/logger'); + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connecctions. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// +// ReplSet instance id +var replSetId = 1; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // Add event listener + EventEmitter.call(this); + + // Set the bson instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + + // Internal state hash for the object + this.s = { + options: options + // Logger instance + , logger: Logger('ReplSet', options) + // Uniquely identify the replicaset instance + , id: replSetId++ + // Index + , index: 0 + // Ha Index + , haId: 0 + // Current credentials used for auth + , credentials: [] + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Special replicaset options + , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' + ? options.secondaryOnlyConnectionAllowed : false + , haInterval: options.haInterval || 10000 + // Are we running in debug mode + , debug: typeof options.debug == 'boolean' ? options.debug : false + // The replicaset name + , setName: options.setName + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // Currently connecting servers + , connectingServers: {} + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // All the servers + , disconnectedServers: [] + // Initial connection servers + , initialConnectionServers: [] + // High availability process running + , highAvailabilityProcessRunning: false + // Full setup + , fullsetup: false + // All servers accounted for (used for testing) + , all: false + // Seedlist + , seedlist: seedlist + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Minimum heartbeat frequency used if we detect a server close + , minHeartbeatFrequencyMS: 500 + } + + // Add bson parser to options + options.bson = this.s.bson; + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 10000; + + // Replicaset state + var replState = new State(this, { + id: this.s.id, setName: this.s.setName + , connectingServers: this.s.connectingServers + , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed + }); + + // Add Replicaset state to our internal state + this.s.replState = replState; + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.replState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.replState; } + }); + + // + // Debug options + if(self.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'readPreferenceStrategies', { + enumerable: true, get: function() { return self.s.readPreferenceStrategies; } + }); + } + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'replset'; } + }); + + // Add the ping strategy for nearest + this.addReadPreferenceStrategy('nearest', new Ping(options)); +} + +inherits(ReplSet, EventEmitter); + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { + this.s.readPreferenceStrategies[name] = func; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +ReplSet.prototype.addAuthProvider = function(name, provider) { + if(this.s.authProviders == null) this.s.authProviders = {}; + this.s.authProviders[name] = provider; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +ReplSet.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +ReplSet.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + return this.s.replState.lastIsMaster(); +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +ReplSet.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = pickServer(this, this.s, options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + return this.s.replState.getAllConnections(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +ReplSet.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return pickServer(this, this.s, options.readPreference); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +// +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + // Get a primary + try { + server = pickServer(self, self.s, ReadPreference.primary); + if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + + // Execute the command + server[op](ns, ops, options, function(err, r) { + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the result + callback(err, r); + }); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + var server = null; + var self = this; + // Ensure we have no options + options = options || {}; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected(options) && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // We need to execute the command on all servers + if(options.onAll) { + var servers = this.s.replState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + // Pick the right server based on readPreference + try { + server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); + if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + // Execute the command + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) { + replicasetInquirer(self, self.s, true)(); + } + // Return the error + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.replState.getAll().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +ReplSet.prototype.state = function() { + return this.s.replState.state; +} + +/** + * Ensure single socket connections to arbiters and hidden servers + * @method + */ +var handleIsmaster = function(self) { + return function(ismaster, _server) { + if(ismaster.arbiterOnly) { + _server.s.options.size = 1; + } else if(ismaster.hidden) { + _server.s.options.size = 1; + } + } +} + +/** + * Initiate server connect + * @method + */ +ReplSet.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(replicasetInquirer(this, this.s, false), this.s.haInterval); + // Additional options + if(_options) for(var name in _options) this.s.options[name] = _options[name]; + + // Set the state as connecting + this.s.replState.state = CONNECTING; + + // No fullsetup reached + this.s.fullsetup = false; + + // For all entries in the seedlist build a server instance + this.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + opts.emitError = true; + if(self.s.tag) opts.tag = self.s.tag; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Add to list of disconnected servers + self.s.disconnectedServers.push(server); + // Add to list of inflight Connections + self.s.initialConnectionServers.push(server); + }); + + // Attempt to connect to all the servers + while(this.s.disconnectedServers.length > 0) { + // Get the server + var server = this.s.disconnectedServers.shift(); + + // Set up the event handlers + server.once('error', errorHandlerTemp(this, this.s, 'error')); + server.once('close', errorHandlerTemp(this, this.s, 'close')); + server.once('timeout', errorHandlerTemp(this, this.s, 'timeout')); + server.once('connect', connectHandler(this, this.s)); + + // Attempt to connect + server.connect(); + } +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + // If we specified a read preference check if we are connected to something + // than can satisfy this + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondary)) + return this.s.replState.isSecondaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primary)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(this.s.secondaryOnlyConnectionAllowed) return this.s.replState.isSecondaryConnected(); + return this.s.replState.isPrimaryConnected(); +} + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.s.replState.state == DESTROYED; +} + +/** + * Destroy the server connection + * @method + */ +ReplSet.prototype.destroy = function(emitClose) { + var self = this; + if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); + this.s.replState.state = DESTROYED; + + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Destroy state + this.s.replState.destroy(); + + // Clear out any listeners + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +// +// Inquires about state changes +// + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(s, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(s, db + ".dummy"); + // Add new credentials to list + s.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(s, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < s.credentials.length; i++) { + if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); + } + + // Set new list of credentials + s.credentials = filteredCredentials; +} + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +// +// Pick a server based on readPreference +var pickServer = function(self, s, readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { + if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); + var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); + if(s.debug) self.emit('pickedServer', readPreference, server); + return server; + } + + // Filter out any hidden secondaries + var secondaries = s.replState.secondaries.filter(function(server) { + if(server.lastIsMaster().hidden) return false; + return true; + }); + + // Check if we can satisfy and of the basic read Preferences + if(readPreference.equals(ReadPreference.secondary) + && secondaries.length == 0) + throw new MongoError("no secondary server available"); + + if(readPreference.equals(ReadPreference.secondaryPreferred) + && secondaries.length == 0 + && s.replState.primary == null) + throw new MongoError("no secondary or primary server available"); + + if(readPreference.equals(ReadPreference.primary) + && s.replState.primary == null) + throw new MongoError("no primary server available"); + + // Secondary + if(readPreference.equals(ReadPreference.secondary)) { + s.index = (s.index + 1) % secondaries.length; + return secondaries[s.index]; + } + + // Secondary preferred + if(readPreference.equals(ReadPreference.secondaryPreferred)) { + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + } + + return s.replState.primary; + } + + // Primary preferred + if(readPreference.equals(ReadPreference.primaryPreferred)) { + if(s.replState.primary) return s.replState.primary; + + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + + // Throw error a we have not valid secondary or primary servers + throw new MongoError("no secondary or primary server available"); + } + } + + // Return the primary + return s.replState.primary; +} + +var replicasetInquirer = function(self, state, norepeat) { + return function() { + if(state.replState.state == DESTROYED) return + // Process already running don't rerun + if(state.highAvailabilityProcessRunning) return; + // Started processes + state.highAvailabilityProcessRunning = true; + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); + + // Unique HA id to identify the current look running + var localHaId = state.haId++; + + // Clean out any failed connection attempts + state.connectingServers = {}; + + // Controls if we are doing a single inquiry or repeating + norepeat = typeof norepeat == 'boolean' ? norepeat : false; + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Emit replicasetInquirer + self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + + // Let's process all the disconnected servers + while(state.disconnectedServers.length > 0) { + // Get the first disconnected server + var server = state.disconnectedServers.shift(); + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + // Attempt to connect + server.connect(); + } + + // Cleanup state (removed disconnected servers) + state.replState.clean(); + + // We need to query all servers + var servers = state.replState.getAll(); + var serversLeft = servers.length; + + // If no servers and we are not destroyed keep pinging + if(servers.length == 0 && state.replState.state == CONNECTED) { + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Restart ha process + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // + // ismaster for Master server + var primaryIsMaster = null; + + // + // Inspect a specific servers ismaster + var inspectServer = function(server) { + if(state.replState.state == DESTROYED) return; + // Did we get a server + if(server && server.isConnected()) { + // Execute ismaster + server.command('system.$cmd', {ismaster:true}, function(err, r) { + if(state.replState.state == DESTROYED) return; + // Count down the number of servers left + serversLeft = serversLeft - 1; + // If we have an error but still outstanding server request return + if(err && serversLeft > 0) return; + // We had an error and have no more servers to inspect, schedule a new check + if(err && serversLeft == 0) { + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunnfing + state.highAvailabilityProcessRunning = false; + // Return the replicasetInquirer + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // Let all the read Preferences do things to the servers + var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; + + // Handle the primary + var ismaster = r.result; + if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); + + // Update the replicaset state + state.replState.update(ismaster, server); + + // Add any new servers + if(err == null && ismaster.ismaster && Array.isArray(ismaster.hosts)) { + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + // Process all the hsots + processHosts(self, state, hosts); + } + + // No read Preferences strategies + if(rPreferencesCount == 0) { + // Don't schedule a new inquiry + if(serversLeft > 0) return; + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // No servers left to query, execute read preference strategies + if(serversLeft == 0) { + // Go over all the read preferences + for(var name in state.readPreferenceStrategies) { + state.readPreferenceStrategies[name].ha(self, state.replState, function() { + rPreferencesCount = rPreferencesCount - 1; + + if(rPreferencesCount == 0) { + // Add any new servers in primary ismaster + if(err == null + && ismaster.ismaster + && Array.isArray(ismaster.hosts)) { + processHosts(self, state, ismaster.hosts); + } + + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + }); + } + } + }); + } + } + + // Call ismaster on all servers + for(var i = 0; i < servers.length; i++) { + inspectServer(servers[i]); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + + // If all servers are accounted for and we have not sent the all event + if(state.replState.primary != null && self.lastIsMaster() + && Array.isArray(self.lastIsMaster().hosts) && !state.all) { + var length = 1 + state.replState.secondaries.length; + // If we have all secondaries + primary + if(length == self.lastIsMaster().hosts.length + 1) { + state.all = true; + self.emit('all', self); + } + } + } +} + +// Error handler for initial connect +var errorHandlerTemp = function(self, state, event) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Connection is destroyed, ignore + if(state.replState.state == DESTROYED) return; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Push to list of disconnected servers + addToListIfNotExist(state.disconnectedServers, server); + + // End connection operation if we have no legal replicaset state + if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { + if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) + || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) + return self.emit('error', new MongoError('no valid seed servers in list')); + } + } + + // If the number of disconnected servers is equal to + // the number of seed servers we cannot connect + if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { + if(state.emitError && self.listeners('error').length > 0) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) + self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } +} + +// Connect handler +var connectHandler = function(self, state) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); + // Destroyed connection + if(state.replState.state == DESTROYED) { + server.destroy(false, false); + return; + } + + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Process the new server + var processNewServer = function() { + // Discover any additional servers + var ismaster = server.lastIsMaster(); + + var events = ['error', 'close', 'timeout', 'connect', 'message']; + // Remove any non used handlers + events.forEach(function(e) { + server.removeAllListeners(e); + }) + + // Clean up + delete state.connectingServers[server.name]; + // Update the replicaset state, destroy if not added + if(!state.replState.update(ismaster, server)) { + return server.destroy(); + } + + // Add the server handling code + if(server.isConnected()) { + server.on('error', errorHandler(self, state)); + server.on('close', closeHandler(self, state)); + server.on('timeout', timeoutHandler(self, state)); + } + + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + + // Add any new servers + processHosts(self, state, hosts); + + // If have the server instance already destroy it + if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 + && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); + self.emit('error', new MongoError("no primary found in replicaset")); + return self.destroy(); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + } + + // Save up new members to be authenticated against + if(self.s.authInProgress) { + self.s.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(); + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(); + }])); + } + } +} + +// +// Detect if we need to add new servers +var processHosts = function(self, state, hosts) { + if(state.replState.state == DESTROYED) return; + if(Array.isArray(hosts)) { + // Check any hosts exposed by ismaster + for(var i = 0; i < hosts.length; i++) { + // If not found we need to create a new connection + if(!state.replState.contains(hosts[i])) { + if(state.connectingServers[hosts[i]] == null && !inInitialConnectingServers(self, state, hosts[i])) { + if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, hosts[i])); + // Make sure we know what is trying to connect + state.connectingServers[hosts[i]] = hosts[i]; + // Connect the server + connectToServer(self, state, hosts[i].split(':')[0], parseInt(hosts[i].split(':')[1], 10)); + } + } + } + } +} + +var inInitialConnectingServers = function(self, state, address) { + for(var i = 0; i < state.initialConnectionServers.length; i++) { + if(state.initialConnectionServers[i].name == address) return true; + } + return false; +} + +// Connect to a new server +var connectToServer = function(self, state, host, port) { + var opts = cloneOptions(state.options); + opts.host = host; + opts.port = port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + if(state.tag) opts.tag = state.tag; + // Share the auth store + opts.authProviders = state.authProviders; + opts.emitError = true; + // Create a new server instance + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + // Attempt to connect + server.connect(); +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } + + return found; +} + +var errorHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +// +// Validate if a non-master or recovering error +var notMasterError = function(r) { + // Get result of any + var result = r && r.result ? r.result : r; + + // Explore if we have a not master error + if(result && (result.err == 'not master' + || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) + || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) + || result.errmsg == 'node is recovering')) { + return true; + } + + return false; +} + +module.exports = ReplSet; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..b05d2a5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,472 @@ +"use strict"; + +var Logger = require('../connection/logger') + , f = require('util').format + , ObjectId = require('bson').ObjectId + , MongoError = require('../error'); + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +/** + * Creates a new Replicaset State object + * @class + * @property {object} primary Primary property + * @property {array} secondaries List of secondaries + * @property {array} arbiters List of arbiters + * @return {State} A cursor instance + */ +var State = function(replSet, options) { + this.replSet = replSet; + this.options = options; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.primary = null; + // Initial state is disconnected + this.state = DISCONNECTED; + // Current electionId + this.electionId = null; + // Get a logger instance + this.logger = Logger('ReplSet', options); + // Unpacked options + this.id = options.id; + this.setName = options.setName; + this.connectingServers = options.connectingServers; + this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; +} + +/** + * Is there a secondary connected + * @method + * @return {boolean} + */ +State.prototype.isSecondaryConnected = function() { + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].isConnected()) return true; + } + + return false; +} + +/** + * Is there a primary connection + * @method + * @return {boolean} + */ +State.prototype.isPrimaryConnected = function() { + return this.primary != null && this.primary.isConnected(); +} + +/** + * Is the given address the primary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPrimary = function(address) { + if(this.primary == null) return false; + return this.primary && this.primary.equals(address); +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isSecondary = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPassive = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Does the replicaset contain this server + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.contains = function(address) { + if(this.primary && this.primary.equals(address)) return true; + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) return true; + } + + for(var i = 0; i < this.arbiters.length; i++) { + if(this.arbiters[i].equals(address)) return true; + } + + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) return true; + } + + return false; +} + +/** + * Clean out all dead connections + * @method + */ +State.prototype.clean = function() { + if(this.primary != null && !this.primary.isConnected()) { + this.primary = null; + } + + // Filter out disconnected servers + this.secondaries = this.secondaries.filter(function(s) { + return s.isConnected(); + }); + + // Filter out disconnected servers + this.arbiters = this.arbiters.filter(function(s) { + return s.isConnected(); + }); +} + +/** + * Destroy state + * @method + */ +State.prototype.destroy = function() { + this.state = DESTROYED; + if(this.primary) this.primary.destroy(); + this.secondaries.forEach(function(s) { + s.destroy(); + }); +} + +/** + * Remove server from state + * @method + * @param {Server} Server to remove + * @return {string} Returns type of server removed (primary|secondary) + */ +State.prototype.remove = function(server) { + if(this.primary && this.primary.equals(server)) { + this.primary = null; + return 'primary'; + } + + var length = this.arbiters.length; + // Filter out the server from the arbiters + this.arbiters = this.arbiters.filter(function(s) { + return !s.equals(server); + }); + if(this.arbiters.length < length) return 'arbiter'; + + var length = this.passives.length; + // Filter out the server from the passives + this.passives = this.passives.filter(function(s) { + return !s.equals(server); + }); + + // We have removed a passive + if(this.passives.length < length) { + // Ensure we removed it from the list of secondaries as well if it exists + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + + return 'passive'; + } + + // Filter out the server from the secondaries + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + + return 'secondary'; +} + +/** + * Get the server by name + * @method + * @param {string} address Server address + * @return {Server} + */ +State.prototype.get = function(server) { + var found = false; + // All servers to search + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + // Locate the server + for(var i = 0; i < servers.length; i++) { + if(servers[i].equals(server)) { + return servers[i]; + } + } +} + +/** + * Get all the servers in the set + * @method + * @return {array} + */ +State.prototype.getAll = function() { + var servers = []; + if(this.primary) servers.push(this.primary); + return servers.concat(this.secondaries); +} + +/** + * All raw connections + * @method + * @return {array} + */ +State.prototype.getAllConnections = function() { + var connections = []; + if(this.primary) connections = connections.concat(this.primary.connections()); + this.secondaries.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + + return connections; +} + +/** + * Return JSON object + * @method + * @return {object} + */ +State.prototype.toJSON = function() { + return { + primary: this.primary ? this.primary.lastIsMaster().me : null + , secondaries: this.secondaries.map(function(s) { + return s.lastIsMaster().me + }) + } +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +State.prototype.lastIsMaster = function() { + if(this.primary) return this.primary.lastIsMaster(); + if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); + return {}; +} + +/** + * Promote server to primary + * @method + * @param {Server} server Server we wish to promote + */ +State.prototype.promotePrimary = function(server) { + var currentServer = this.get(server); + // Server does not exist in the state, add it as new primary + if(currentServer == null) { + this.primary = server; + return; + } + + // We found a server, make it primary and remove it from the secondaries + // Remove the server first + this.remove(currentServer); + // Set as primary + this.primary = currentServer; +} + +var add = function(list, server) { + // Check if the server is a secondary at the moment + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) return false; + } + + list.push(server); + return true; +} + +/** + * Add server to list of secondaries + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addSecondary = function(server) { + return add(this.secondaries, server); +} + +/** + * Add server to list of arbiters + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addArbiter = function(server) { + return add(this.arbiters, server); +} + +/** + * Add server to list of passives + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addPassive = function(server) { + return add(this.passives, server); +} + +var compareObjectIds = function(id1, id2) { + var a = new Buffer(id1.toHexString(), 'hex'); + var b = new Buffer(id2.toHexString(), 'hex'); + + if(a === b) { + return 0; + } + + if(typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +/** + * Update the state given a specific ismaster result + * @method + * @param {object} ismaster IsMaster result + * @param {Server} server IsMaster Server source + */ +State.prototype.update = function(ismaster, server) { + var self = this; + // Not in a known connection valid state + if(!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + // Remove the state + var result = self.remove(server); + if(self.state == CONNECTED) { + if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); + self.replSet.emit('left', self.remove(server), server); + } + + return false; + } + + // Set the setName if it's not set from the first server + if(self.setName == null && ismaster.setName) { + if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); + self.setName = ismaster.setName; + } + + // Check if the replicaset name matches the provided one + if(ismaster.setName && self.setName != ismaster.setName) { + if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); + self.remove(server); + self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); + return false; + } + + // Log information + if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); + + // It's a master set it + if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { + // Check if the electionId is not null + if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { + if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { + self.electionId = ismaster.electionId; + } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { + self.electionId = ismaster.electionId; + } else { + return false; + } + } + + // Initial electionId + if(ismaster.electionId instanceof ObjectId && self.electionId == null) { + self.electionId = ismaster.electionId; + } + + // Promote to primary + self.promotePrimary(server); + // Log change of primary + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); + // Emit primary + self.replSet.emit('joined', 'primary', this.primary); + + // We are connected + if(self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } else { + self.state = CONNECTED; + self.replSet.emit('reconnect', server); + } + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.arbiterOnly) { + if(self.addArbiter(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); + self.replSet.emit('joined', 'arbiter', server); + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary && ismaster.passive) { + if(self.addPassive(server) && self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); + self.replSet.emit('joined', 'passive', server); + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary) { + if(self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); + self.replSet.emit('joined', 'secondary', server); + + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } + + // Return update applied + return true; +} + +module.exports = State; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..efda721 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1252 @@ + "use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , Pool = require('../connection/pool') + , b = require('bson') + , Query = require('../connection/commands').Query + , MongoError = require('../error') + , ReadPreference = require('./read_preference') + , BasicCursor = require('../cursor') + , CommandResult = require('./command_result') + , getSingleProperty = require('../connection/utils').getSingleProperty + , getProperty = require('../connection/utils').getProperty + , debugOptions = require('../connection/utils').debugOptions + , BSON = require('bson').native().BSON + , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') + , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') + , Session = require('./session') + , Logger = require('../connection/logger') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; +// Server instance id +var serverId = 0; +// Callbacks instance id +var callbackId = 0; + +// Single store for all callbacks +var Callbacks = function() { + // EventEmitter.call(this); + var self = this; + // Callbacks + this.callbacks = {}; + // Set the callbacks id + this.id = callbackId++; + // Set the type to server + this.type = 'server'; +} + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// +// Flush all callbacks +Callbacks.prototype.flush = function(err) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, null); + } + } +} + +Callbacks.prototype.emit = function(id, err, value) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, value); +} + +Callbacks.prototype.raw = function(id) { + if(this.callbacks[id] == null) return false; + return this.callbacks[id].raw == true ? true : false +} + +Callbacks.prototype.unregister = function(id) { + delete this.callbacks[id]; +} + +Callbacks.prototype.register = function(id, callback) { + this.callbacks[id] = bindToCurrentDomain(callback); +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + return domain.bind(callback); +} + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// Supports server +var supportsServer = function(_s) { + return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; +} + +// +// createWireProtocolHandler +var createWireProtocolHandler = function(result) { + // 2.6 wire protocol handler + if(result && result.maxWireVersion >= 2) { + return new TwoSixWireProtocolSupport(); + } + + // 2.4 or earlier wire protocol handler + return new PreTwoSixWireProtocolSupport(); +} + +// +// Reconnect server +var reconnectServer = function(self, state) { + // If the current reconnect retries is 0 stop attempting to reconnect + if(state.currentReconnectRetry == 0) { + return self.destroy(true, true); + } + + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + + // Connect and retrieve the ismaster + isMasterDiscovery(self, self.s.options, function(err, r) { + // Set status to connecting + state.state = CONNECTING; + // Create a new Pool + state.pool = new Pool(state.options); + // error handler + var reconnectErrorHandler = function(err) { + state.state = DISCONNECTED; + // Destroy the pool + state.pool.destroy(); + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + // No more retries + if(state.currentReconnectRetry <= 0) { + self.state = DESTROYED; + self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); + } else { + setTimeout(function() { + reconnectServer(self, state); + }, state.reconnectInterval); + } + } + + // + // Attempt to connect + state.pool.once('connect', function() { + // Reset retries + state.currentReconnectRetry = state.reconnectTries; + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'parseError']; + events.forEach(function(e) { + state.pool.removeAllListeners(e); + }); + + // Set connected state + state.state = CONNECTED; + + // Add proper handlers + state.pool.once('error', reconnectErrorHandler); + state.pool.once('close', closeHandler(self, state)); + state.pool.once('timeout', timeoutHandler(self, state)); + state.pool.once('parseError', fatalErrorHandler(self, state)); + + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return self.emit('reconnect', self); + + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return self.emit('reconnect', self); + } + }); + } + }); + + // + // Handle connection failure + state.pool.once('error', errorHandler(self, state)); + state.pool.once('close', errorHandler(self, state)); + state.pool.once('timeout', errorHandler(self, state)); + state.pool.once('parseError', errorHandler(self, state)); + + // Connect pool + state.pool.connect(); + }); +} + +// +// Handlers +var messageHandler = function(self, state) { + return function(response, connection) { + try { + // Parse the message + response.parse({raw: state.callbacks.raw(response.responseTo)}); + if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); + state.callbacks.emit(response.responseTo, null, response); + } catch (err) { + state.callbacks.flush(new MongoError(err)); + self.destroy(); + } + } +} + +var errorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Destroy all connections + self.destroy(); + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + } +} + +var fatalErrorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Emit error event + self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var timeoutHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); + // Emit error event + self.emit('timeout', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var closeHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); + // Emit error event + self.emit('close', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var connectHandler = function(self, state) { + // Apply all stored authentications + var applyAuthentications = function(callback) { + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return callback(null, null); + + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return callback(null, null); + } + }); + } + } + + return function(connection) { + // Apply any applyAuthentications + applyAuthentications(function() { + + // Execute an ismaster + self.command('system.$cmd', {ismaster:true}, function(err, r) { + if(err) { + state.state = DISCONNECTED; + return self.emit('close', err, self); + } + + // Set the current ismaster + if(!err) { + state.ismaster = r.result; + } + + // Determine the wire protocol handler + state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); + + // Set the wireProtocolHandler + state.options.wireProtocolHandler = state.wireProtocolHandler; + + // Log the ismaster if available + if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); + + // Validate if we it's a server we can connect to + if(!supportsServer(state) && state.wireProtocolHandler == null) { + state.state = DISCONNECTED + return self.emit('error', new MongoError("non supported server version"), self); + } + + // Set the details + if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; + + // No read preference strategies just emit connect + if(state.readPreferenceStrategies == null) { + state.state = CONNECTED; + return self.emit('connect', self); + } + + // Signal connect to all readPreferences + notifyStrategies(self, self.s, 'connect', [self], function(err, result) { + state.state = CONNECTED; + return self.emit('connect', self); + }); + }); + }); + } +} + +var slaveOk = function(r) { + if(r) return r.slaveOk() + return false; +} + +// +// Execute readPreference Strategies +var notifyStrategies = function(self, state, op, params, callback) { + if(typeof callback != 'function') { + // Notify query start to any read Preference strategies + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + strat[op].apply(strat, params); + } + } + // Finish up + return; + } + + // Execute the async callbacks + var nPreferences = Object.keys(state.readPreferenceStrategies).length; + if(nPreferences == 0) return callback(null, null); + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + // Add a callback to params + var cParams = params.slice(0); + cParams.push(function(err, r) { + nPreferences = nPreferences - 1; + if(nPreferences == 0) { + callback(null, null); + } + }) + // Execute the readPreference + strat[op].apply(strat, cParams); + } + } +} + +var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' + , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout' + , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + */ +var Server = function(options) { + var self = this; + + // Add event listener + EventEmitter.call(this); + + // BSON Parser, ensure we have a single instance + if(bsonInstance == null) { + bsonInstance = new BSON(bsonTypes); + } + + // Reconnect retries + var reconnectTries = options.reconnectTries || 30; + + // Keeps all the internal state of the server + this.s = { + // Options + options: options + // Contains all the callbacks + , callbacks: new Callbacks() + // Logger + , logger: Logger('Server', options) + // Server state + , state: DISCONNECTED + // Reconnect option + , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true + , reconnectTries: reconnectTries + , reconnectInterval: options.reconnectInterval || 1000 + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Current state + , currentReconnectRetry: reconnectTries + // Contains the ismaster + , ismaster: null + // Contains any alternate strategies for picking + , readPreferenceStrategies: options.readPreferenceStrategies + // Auth providers + , authProviders: options.authProviders || {} + // Server instance id + , id: serverId++ + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // wireProtocolHandler methods + , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Internal connection pool + , pool: null + // Server details + , serverDetails: { + host: options.host + , port: options.port + , name: options.port ? f("%s:%s", options.host, options.port) : options.host + } + } + + // Reference state + var s = this.s; + + // Add bson parser to options + options.bson = s.bson; + + // Set error properties + getProperty(this, 'name', 'name', s.serverDetails, {}); + getProperty(this, 'bson', 'bson', s.options, {}); + getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); + getSingleProperty(this, 'id', s.id); + + // Add auth providers + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); +} + +inherits(Server, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Server.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.s.ismaster; +} + +var isMasterDiscovery = function(self, options, callback) { + if(options.noismaster) return callback(); + // Clone the options + var options = cloneOptions(options); + // Set the pool size to a single socket + options.size = 1; + options.noismaster = true; + // Create a new server instance + var server = new Server(options) + + // Add handlers + server.on('connect', function(_server) { + // Remove all listeners + _server.removeAllListeners('close'); + _server.removeAllListeners('error'); + _server.removeAllListeners('timeout'); + _server.removeAllListeners('parseError'); + // Destroy socket + _server.destroy(); + // Return lastIsMaster for this server + callback(null, _server.lastIsMaster()); + }); + + // Handle all errors + var errorHandler = function() { + if(callback) { + var _internalCallback = callback; + callback = null; + _internalCallback(); + } + } + + // Intercept all the errors + server.on('close', errorHandler); + server.on('error', errorHandler); + server.on('timeout', errorHandler); + server.on('parseError', errorHandler); + + // Connect + server.connect(); +} + +/** + * Initiate server connect + * @method + */ +Server.prototype.connect = function(_options) { + var self = this; + // Set server specific settings + _options = _options || {} + // Set the promotion + if(typeof _options.promoteLongs == 'boolean') { + self.s.options.promoteLongs = _options.promoteLongs; + } + + // Connect and retrieve the ismaster + isMasterDiscovery(self, self.s.options, function(err, r) { + // If we have an ismaster + if(r) { + self.emit('ismaster', r, self); + } + + // Destroy existing pool + if(self.s.pool) { + self.s.pool.destroy(); + self.s.pool = null; + } + + // Set the state to connection + self.s.state = CONNECTING; + // Create a new connection pool + if(!self.s.pool) { + self.s.options.messageHandler = messageHandler(self, self.s); + self.s.pool = new Pool(self.s.options); + } + + // Add all the event handlers + self.s.pool.once('timeout', timeoutHandler(self, self.s)); + self.s.pool.once('close', closeHandler(self, self.s)); + self.s.pool.once('error', errorHandler(self, self.s)); + self.s.pool.once('connect', connectHandler(self, self.s)); + self.s.pool.once('parseError', fatalErrorHandler(self, self.s)); + + // Connect the pool + self.s.pool.connect(); + }); +} + +/** + * Destroy the server connection + * @method + */ +Server.prototype.destroy = function(emitClose, emitDestroy) { + var self = this; + if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Emit destroy event + if(emitDestroy) self.emit('destroy', self); + // Set state as destroyed + self.s.state = DESTROYED; + // Close the pool + self.s.pool.destroy(); + // Flush out all the callbacks + if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + var self = this; + if(self.s.pool) return self.s.pool.isConnected(); + return false; +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { + // Create a query instance + var query = new Query(self.s.bson, ns, cmd, queryOptions); + + // Set slave OK + query.slaveOk = slaveOk(options.readPreference); + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) + notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); + + // Get a connection (either passed or from the pool) + var connection = options.connection || self.s.pool.get(); + + // Double check if we have a valid connection + if(!connection.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Print cmd and execution connection if in debug mode for logging + if(self.s.logger.isDebug()) { + var json = connection.toJSON(); + self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(cmd), json.id, json.host, json.port)); + } + + // Execute multiple queries + if(onAll) { + var connections = self.s.pool.getAll(); + var total = connections.length; + // We have an error + var error = null; + // Execute on all connections + for(var i = 0; i < connections.length; i++) { + try { + query.incRequestId(); + connections[i].write(query.toBin()); + } catch(err) { + total = total - 1; + if(total == 0) return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + if(err) error = err; + total = total - 1; + + // Done + if(total == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); + if(error) return callback(MongoError.create(error)); + // Execute callback, catch and rethrow if needed + try { callback(null, new CommandResult(result.documents[0], connections)); } + catch(err) { process.nextTick(function() { throw err}); } + } + }); + } + + return; + } + + // Execute a single command query + try { + connection.write(query.toBin()); + } catch(err) { + return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + if(err) return callback(err); + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); + // Execute callback, catch and rethrow if needed + try { callback(null, new CommandResult(result.documents[0], connection)); } + catch(err) { process.nextTick(function() { throw err}); } + }); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Ensure we have no options + options = options || {}; + // Do we have a read Preference it need to be of type ReadPreference + if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error("readPreference must be an instance of ReadPreference"); + } + + // Debug log + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ + ns: ns, cmd: cmd, options: debugOptions(debugFields, options) + }), self.name)); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // If we have no connection error + if(!self.s.pool.isConnected()) return callback(new MongoError(f("no connection available to server %s", self.name))); + + // Execute on all connections + var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; + + // Check keys + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; + + // Serialize function + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + + // Query options + var queryOptions = { + numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys + }; + + if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; + + // Single operation execution + if(!Array.isArray(cmd)) { + return executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); + } + + // Build commands for each of the instances + var queries = new Array(cmd.length); + for(var i = 0; i < cmd.length; i++) { + queries[i] = new Query(self.s.bson, ns, cmd[i], queryOptions); + queries[i].slaveOk = slaveOk(options.readPreference); + } + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) + notifyStrategies(self, self.s, 'startOperation', [self, queries, new Date()]); + + // Get a connection (either passed or from the pool) + var connection = options.connection || self.s.pool.get(); + + // Double check if we have a valid connection + if(!connection.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Print cmd and execution connection if in debug mode for logging + if(self.s.logger.isDebug()) { + var json = connection.toJSON(); + self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(queries), json.id, json.host, json.port)); + } + + // Canceled operations + var canceled = false; + // Number of operations left + var operationsLeft = queries.length; + // Results + var results = []; + + // We need to nest the callbacks + for(var i = 0; i < queries.length; i++) { + // Get the query object + var query = queries[i]; + + // Execute a single command query + try { + connection.write(query.toBin()); + } catch(err) { + return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + // If it's canceled ignore the operation + if(canceled) return; + // Update the current index + operationsLeft = operationsLeft - 1; + + // If we have an error cancel the operation + if(err) { + canceled = true; + return callback(err); + } + + // Return the result + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) { + + // Set to canceled + canceled = true; + // Return the error + return callback(MongoError.create(result.documents[0])); + } + + // Push results + results.push(result.documents[0]); + + // We are done, return the result + if(operationsLeft == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + + // Turn into command results + var commandResults = new Array(results.length); + for(var i = 0; i < results.length; i++) { + commandResults[i] = new CommandResult(results[i], connection); + } + + // Execute callback, catch and rethrow if needed + try { callback(null, commandResults); } + catch(err) { process.nextTick(function() { throw err}); } + } + }); + } +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(self.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // If we have the default mechanism we pick mechanism based on the wire + // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr + if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { + mechanism = 'scram-sha-1'; + } else if(mechanism == 'default') { + mechanism = 'mongocr'; + } + + // Actual arguments + var finalArguments = [self, self.s.pool, db].concat(args.slice(0)).concat([function(err, r) { + if(err) return callback(err); + if(!r) return callback(new MongoError('could not authenticate')); + callback(null, new Session({}, self)); + }]); + + // Let's invoke the auth mechanism + self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Server.prototype.addReadPreferenceStrategy = function(name, strategy) { + var self = this; + if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; + self.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Server.prototype.addAuthProvider = function(name, provider) { + var self = this; + self.s.authProviders[name] = provider; +} + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if(typeof server == 'string') return server == this.name; + return server.name == this.name; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.getAll(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Server.prototype.getServer = function(options) { + return this; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Server.prototype.getConnection = function(options) { + return this.s.pool.get(); +} + +/** + * Get callbacks object + * @method + * @return {Callbacks} + */ +Server.prototype.getCallbacks = function() { + return this.s.callbacks; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Server.prototype.parserType = function() { + var s = this.s; + if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {opResultCallback} callback A callback function + */ +Server.prototype.cursor = function(ns, cmd, cursorOptions) { + var s = this.s; + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || s.Cursor; + return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Server#close + * @type {Server} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Server#error + * @type {Server} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Server#timeout + * @type {Server} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Server#parseError + * @type {Server} + */ + +/** + * The server reestablished the connection + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * This is an insert result callback + * + * @callback opResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {CommandResult} command result + */ + +/** + * This is an authentication result callback + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Session} an authenticated session + */ + +module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js new file mode 100644 index 0000000..032c3c5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js @@ -0,0 +1,93 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , EventEmitter = require('events').EventEmitter; + +/** + * Creates a new Authentication Session + * @class + * @param {object} [options] Options for the session + * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session + */ +var Session = function(options, topology) { + this.options = options; + this.topology = topology; + + // Add event listener + EventEmitter.call(this); +} + +inherits(Session, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {object} [options.readPreference] Specify read preference if command supports it + * @param {object} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Session.prototype.command = function(ns, cmd, options, callback) { + this.topology.command(ns, cmd, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.insert = function(ns, ops, options, callback) { + this.topology.insert(ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.update = function(ns, ops, options, callback) { + this.topology.update(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.remove = function(ns, ops, options, callback) { + this.topology.remove(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {boolean} [options.tailable=false] Tailable flag set + * @param {boolean} [options.oplogReply=false] oplogReply flag set + * @param {boolean} [options.awaitdata=false] awaitdata flag set + * @param {boolean} [options.exhaust=false] exhaust flag set + * @param {boolean} [options.partial=false] partial flag set + * @param {opResultCallback} callback A callback function + */ +Session.prototype.cursor = function(ns, cmd, options) { + return this.topology.cursor(ns, cmd, options); +} + +module.exports = Session; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js new file mode 100644 index 0000000..3a7b460 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js @@ -0,0 +1,276 @@ +"use strict"; + +var Logger = require('../../connection/logger') + , EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format; + +/** + * Creates a new Ping read preference strategy instance + * @class + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {Ping} A cursor instance + */ +var Ping = function(options) { + // Add event listener + EventEmitter.call(this); + + // Contains the ping state + this.s = { + // Contains all the ping data + pings: {} + // Set no options if none provided + , options: options || {} + // Logger + , logger: Logger('Ping', options) + // Ping interval + , pingInterval: options.pingInterval || 10000 + , acceptableLatency: options.acceptableLatency || 15 + // Debug options + , debug: typeof options.debug == 'boolean' ? options.debug : false + // Index + , index: 0 + // Current ping time + , lastPing: null + + } + + // Log the options set + if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); + + // If we have enabled debug + if(this.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'data', { + enumerable: true, get: function() { return this.s.pings; } + }); + } +} + +inherits(Ping, EventEmitter); + +/** + * @ignore + */ +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +/** + * Pick a server + * @method + * @param {State} set The current replicaset state object + * @param {ReadPreference} readPreference The current readPreference object + * @param {readPreferenceResultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.pickServer = function(set, readPreference) { + var self = this; + // Only get primary and secondaries as seeds + var seeds = {}; + var servers = []; + if(set.primary) { + servers.push(set.primary); + } + + for(var i = 0; i < set.secondaries.length; i++) { + servers.push(set.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Transform the list + var serverList = []; + // for(var name in seeds) { + for(var i = 0; i < servers.length; i++) { + serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); + } + + // Sort by time + serverList.sort(function(a, b) { + return a.time > b.time; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = serverList.length > 0 ? serverList[0].time : 0; + + // Filter by latency + serverList = serverList.filter(function(s) { + return s.time <= lowest + self.s.acceptableLatency; + }); + + // No servers, default to primary + if(serverList.length == 0 && set.primary) { + if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); + return set.primary; + } else if(serverList.length == 0) { + return null + } + + // We picked first server + if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); + + // Add to the index + self.s.index = self.s.index + 1; + // Select the index + self.s.index = self.s.index % serverList.length; + // Return the first server of the sorted and filtered list + return set.get(serverList[self.s.index].name); +} + +/** + * Start of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {object} query The operation running + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.startOperation = function(server, query, date) { +} + +/** + * End of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {error} err An error from the operation + * @param {object} result The result from the operation + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.endOperation = function(server, err, result, date) { +} + +/** + * High availability process running + * @method + * @param {State} set The current replicaset state object + * @param {resultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.ha = function(topology, state, callback) { + var self = this; + var servers = state.getAll(); + var count = servers.length; + + // No servers return + if(servers.length == 0) return callback(null, null); + + // Return if we have not yet reached the ping interval + if(self.s.lastPing != null) { + var diff = new Date().getTime() - self.s.lastPing.getTime(); + if(diff < self.s.pingInterval) return callback(null, null); + } + + // Execute operation + var operation = function(_server) { + var start = new Date(); + // Execute ping against server + _server.command('system.$cmd', {ismaster:1}, function(err, r) { + count = count - 1; + var time = new Date().getTime() - start.getTime(); + self.s.pings[_server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); + // We are done with all the servers + if(count == 0) { + // Emit ping event + topology.emit('ping', err, r ? r.result : null); + // Update the last ping time + self.s.lastPing = new Date(); + // Return + callback(null, null); + } + }); + } + + // Let's ping all servers + while(servers.length > 0) { + operation(servers.shift()); + } +} + +var removeServer = function(self, server) { + delete self.s.pings[server.name]; +} + +/** + * Server connection closed + * @method + * @param {Server} server The server that closed + */ +Ping.prototype.close = function(server) { + removeServer(this, server); +} + +/** + * Server connection errored out + * @method + * @param {Server} server The server that errored out + */ +Ping.prototype.error = function(server) { + removeServer(this, server); +} + +/** + * Server connection timeout + * @method + * @param {Server} server The server that timed out + */ +Ping.prototype.timeout = function(server) { + removeServer(this, server); +} + +/** + * Server connection happened + * @method + * @param {Server} server The server that connected + * @param {resultCallback} callback The callback to return the result from the function + */ +Ping.prototype.connect = function(server, callback) { + var self = this; + // Get the command start date + var start = new Date(); + // Execute ping against server + server.command('system.$cmd', {ismaster:1}, function(err, r) { + var time = new Date().getTime() - start.getTime(); + self.s.pings[server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); + // Set last ping + self.s.lastPing = new Date(); + // Done, return + callback(null, null); + }); +} + +/** + * This is a result from a readPreference strategy + * + * @callback readPreferenceResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Server} server The server picked by the strategy + */ + +module.exports = Ping; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js new file mode 100644 index 0000000..14787e4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js @@ -0,0 +1,514 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +// Write concern fields +var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; + +var LegacySupport = function() {} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +LegacySupport.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; + ops = Array.isArray(ops) ? ops :[ops]; + + // If we have more than a 1000 ops fails + if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +LegacySupport.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +LegacySupport.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +LegacySupport.prototype.killCursor = function(bson, cursorId, connection, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(connection && connection.isConnected()) connection.write(killCursor.toBin()); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +LegacySupport.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + connection.write(getMore.toBin()); +} + +LegacySupport.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + // If we have explain, return a single document and close cursor + if(cmd.explain) { + numberToReturn = -1; + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +var hasWriteConcern = function(writeConcern) { + if(writeConcern.w + || writeConcern.wtimeout + || writeConcern.j == true + || writeConcern.fsync == true + || Object.keys(writeConcern).length == 0) { + return true; + } + return false; +} + +var cloneWriteConcern = function(writeConcern) { + var wc = {}; + if(writeConcern.w != null) wc.w = writeConcern.w; + if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; + if(writeConcern.j != null) wc.j = writeConcern.j; + if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; + return wc; +} + +// +// Aggregate up all the results +// +var aggregateWriteOperationResults = function(opType, ops, results, connection) { + var finalResult = { ok: 1, n: 0 } + + // Map all the results coming back + for(var i = 0; i < results.length; i++) { + var result = results[i]; + var op = ops[i]; + + if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { + finalResult.upserted = []; + } + + // Push the upserted document to the list of upserted values + if(result.upserted) { + finalResult.upserted.push({index: i, _id: result.upserted}); + } + + // We have an upsert where we passed in a _id + if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { + finalResult.upserted.push({index: i, _id: op.q._id}); + } + + // We have an insert command + if(result.ok == 1 && opType == 'insert' && result.err == null) { + finalResult.n = finalResult.n + 1; + } + + // We have a command error + if(result != null && result.ok == 0 || result.err || result.errmsg) { + if(result.ok == 0) finalResult.ok = 0; + finalResult.code = result.code; + finalResult.errmsg = result.errmsg || result.err || result.errMsg; + + // Check if we have a write error + if(result.code == 11000 + || result.code == 11001 + || result.code == 12582 + || result.code == 16544 + || result.code == 16538 + || result.code == 16542 + || result.code == 14 + || result.code == 13511) { + if(finalResult.writeErrors == null) finalResult.writeErrors = []; + finalResult.writeErrors.push({ + index: i + , code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + }); + } else { + finalResult.writeConcernError = { + code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + } + } + } else if(typeof result.n == 'number') { + finalResult.n += result.n; + } else { + finalResult.n += 1; + } + + // Result as expected + if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; + } + + // Return finalResult aggregated results + return new CommandResult(finalResult, connection); +} + +// +// Execute all inserts in an ordered manner +// +var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + var _ops = ops.slice(0); + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Collect all the getLastErrors + var getLastErrors = []; + + // Execute an operation + var executeOp = function(list, _callback) { + // Get a pool connection + var connection = pool.get(); + // No more items in the list + if(list.length == 0) return _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + + // Get the first operation + var doc = list.shift(); + + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Get the db name + var db = ns.split('.').shift(); + + // Error out if no connection available + if(connection == null) + return _callback(new MongoError("no connection available")); + + try { + // Execute the insert + connection.write(op.toBin()); + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var i = 0; i < writeConcernFields.length; i++) { + if(writeConcern[writeConcernFields[i]] != null) + getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Write the lastError message + connection.write(getLastErrorOp.toBin()); + // Register the callback + callbacks.register(getLastErrorOp.requestId, function(err, result) { + if(err) return callback(err); + // Get the document + var doc = result.documents[0]; + // Save the getLastError document + getLastErrors.push(doc); + // If we have an error terminate + if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + // Execute the next op in the list + executeOp(list, callback); + }); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); + // Return due to an error + return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + + // Execute the operations + executeOp(_ops, callback); +} + +var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Total operations to write + var totalOps = ops.length; + // Collect all the getLastErrors + var getLastErrors = []; + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Execute all the operations + for(var i = 0; i < ops.length; i++) { + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); + // Get db name + var db = ns.split('.').shift(); + + // Get a pool connection + var connection = pool.get(); + + // Error out if no connection available + if(connection == null) + return _callback(new MongoError("no connection available")); + + try { + // Execute the insert + connection.write(op.toBin()); + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var j = 0; j < writeConcernFields.length; j++) { + if(writeConcern[writeConcernFields[j]] != null) + getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Write the lastError message + connection.write(getLastErrorOp.toBin()); + + // Give the result from getLastError the right index + var callbackOp = function(_index) { + return function(err, result) { + // Update the number of operations executed + totalOps = totalOps - 1; + // Save the getLastError document + getLastErrors[_index] = result.documents[0]; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, callbackOp(i)); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // Update the number of operations executed + totalOps = totalOps - 1; + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + } + + // Empty w:0 return + if(writeConcern + && writeConcern.w == 0 && callback) { + callback(null, null); + } +} + +module.exports = LegacySupport; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..04e6879 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,249 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var LegacySupport = function() {} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + writeCommand.writeConcern = writeConcern; + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +LegacySupport.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +LegacySupport.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +LegacySupport.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +LegacySupport.prototype.killCursor = function(bson, cursorId, connection, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(connection && connection.isConnected()) connection.write(killCursor.toBin()); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +LegacySupport.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + connection.write(getMore.toBin()); +} + +LegacySupport.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + // If we have explain, return a single document and close cursor + if(cmd.explain) { + numberToReturn = -1; + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = LegacySupport; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js new file mode 100644 index 0000000..c67f30a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js @@ -0,0 +1,335 @@ +"use strict"; + +var MongoError = require('../error'); + +// Wire command operation ids +var OP_UPDATE = 2001; +var OP_INSERT = 2002; +var OP_DELETE = 2006; + +var Insert = function(requestId, ismaster, bson, ns, documents, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new MongoError("namespace cannot contain a null character"); + } + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.documents = documents; + this.ismaster = ismaster; + + // Ensure empty options + options = options || {}; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; + // Set flags + this.flags = this.continueOnError ? 1 : 0; +} + +// To Binary +Insert.prototype.toBin = function() { + // Calculate total length of the document + var length = 4 + Buffer.byteLength(this.ns) + 1 + (4 * 4); + + // Calculate the size of all documents + for(var i = 0; i < this.documents.length; i++) { + var docsize = this.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true); + + // Document is larger than maxBsonObjectSize, terminate serialization + if(docsize > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); + } + + // Add to total command size + length += docsize; + } + + // Command is larger than maxMessageSizeBytes terminate serialization + if(length > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); + } + + // Create command buffer + var buffer = new Buffer(length); + var index = 0; + + // Write header length + buffer[index + 3] = (length >> 24) & 0xff; + buffer[index + 2] = (length >> 16) & 0xff; + buffer[index + 1] = (length >> 8) & 0xff; + buffer[index] = (length) & 0xff; + index = index + 4; + + // Write header requestId + buffer[index + 3] = (this.requestId >> 24) & 0xff; + buffer[index + 2] = (this.requestId >> 16) & 0xff; + buffer[index + 1] = (this.requestId >> 8) & 0xff; + buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + buffer[index + 3] = (0 >> 24) & 0xff; + buffer[index + 2] = (0 >> 16) & 0xff; + buffer[index + 1] = (0 >> 8) & 0xff; + buffer[index] = (0) & 0xff; + index = index + 4; + + // Operation + buffer[index + 3] = (OP_INSERT >> 24) & 0xff; + buffer[index + 2] = (OP_INSERT >> 16) & 0xff; + buffer[index + 1] = (OP_INSERT >> 8) & 0xff; + buffer[index] = (OP_INSERT) & 0xff; + index = index + 4; + + // Flags + buffer[index + 3] = (this.flags >> 24) & 0xff; + buffer[index + 2] = (this.flags >> 16) & 0xff; + buffer[index + 1] = (this.flags >> 8) & 0xff; + buffer[index] = (this.flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + buffer.write(this.ns, index, 'utf8') + 1; + buffer[index - 1] = 0; + + // Write all the bson documents to the buffer at the index offset + for(var i = 0; i < this.documents.length; i++) { + // Serialize the entry + var newIndex = this.bson.serializeWithBufferAndIndex(this.documents[i], this.checkKeys, buffer, index, this.serializeFunctions); + var docSize = newIndex - index + 1; + // Write the doc size + buffer[index + 3] = (docSize >> 24) & 0xff; + buffer[index + 2] = (docSize >> 16) & 0xff; + buffer[index + 1] = (docSize >> 8) & 0xff; + buffer[index] = (docSize) & 0xff; + // Adjust index + index = index + docSize; + // Add terminating 0 for the object + buffer[index - 1] = 0; + } + + return buffer; +} + +var Update = function(requestId, ismaster, bson, ns, update, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; + this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; + this.q = update[0].q; + this.u = update[0].u; + + // Create flag value + this.flags = this.upsert ? 1 : 0; + this.flags = this.multi ? this.flags | 2 : this.flags; +} + +// To Binary +Update.prototype.toBin = function() { + // Calculate total length of the document + var length = (4 * 4) + 4 + Buffer.byteLength(this.ns) + 1 + 4; + + // Calculate the two object sizes + var qSize = this.bson.calculateObjectSize(this.q, this.serializeFunctions, true); + var uSize = this.bson.calculateObjectSize(this.u, this.serializeFunctions, true); + + // Update the length + length = length + qSize + uSize; + + // Create command buffer + var buffer = new Buffer(length); + var index = 0; + + // Write header length + buffer[index + 3] = (length >> 24) & 0xff; + buffer[index + 2] = (length >> 16) & 0xff; + buffer[index + 1] = (length >> 8) & 0xff; + buffer[index] = (length) & 0xff; + index = index + 4; + + // Write header requestId + buffer[index + 3] = (this.requestId >> 24) & 0xff; + buffer[index + 2] = (this.requestId >> 16) & 0xff; + buffer[index + 1] = (this.requestId >> 8) & 0xff; + buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + buffer[index + 3] = (0 >> 24) & 0xff; + buffer[index + 2] = (0 >> 16) & 0xff; + buffer[index + 1] = (0 >> 8) & 0xff; + buffer[index] = (0) & 0xff; + index = index + 4; + + // Operation + buffer[index + 3] = (OP_UPDATE >> 24) & 0xff; + buffer[index + 2] = (OP_UPDATE >> 16) & 0xff; + buffer[index + 1] = (OP_UPDATE >> 8) & 0xff; + buffer[index] = (OP_UPDATE) & 0xff; + index = index + 4; + + // Write ZERO + buffer[index + 3] = (0 >> 24) & 0xff; + buffer[index + 2] = (0 >> 16) & 0xff; + buffer[index + 1] = (0 >> 8) & 0xff; + buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + buffer.write(this.ns, index, 'utf8') + 1; + buffer[index - 1] = 0; + + // Flags + buffer[index + 3] = (this.flags >> 24) & 0xff; + buffer[index + 2] = (this.flags >> 16) & 0xff; + buffer[index + 1] = (this.flags >> 8) & 0xff; + buffer[index] = (this.flags) & 0xff; + index = index + 4; + + // Serialize the selector + var length = this.bson.serializeWithBufferAndIndex(this.q, this.checkKeys, buffer, index, this.serializeFunctions) - index + 1; + buffer[index + 3] = (length >> 24) & 0xff; + buffer[index + 2] = (length >> 16) & 0xff; + buffer[index + 1] = (length >> 8) & 0xff; + buffer[index] = (length) & 0xff; + index = index + length; + + // Serialize the update statement + length = this.bson.serializeWithBufferAndIndex(this.u, false, buffer, index, this.serializeFunctions) - index + 1; + buffer[index + 3] = (length >> 24) & 0xff; + buffer[index + 2] = (length >> 16) & 0xff; + buffer[index + 1] = (length >> 8) & 0xff; + buffer[index] = (length) & 0xff; + index = index + length; + + // Return the buffer + return buffer; +} + + +var Remove = function(requestId, ismaster, bson, ns, remove, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; + this.q = remove[0].q; + + // Create flag value + this.flags = this.limit == 1 ? 1 : 0; +} + +// To Binary +Remove.prototype.toBin = function() { + // Calculate total length of the document + var length = (4 * 4) + 4 + Buffer.byteLength(this.ns) + 1 + 4; + + // Calculate the two object sizes + var qSize = this.bson.calculateObjectSize(this.q, this.serializeFunctions, true); + + // Update the length + length = length + qSize; + // Create command buffer + var buffer = new Buffer(length); + var index = 0; + + // Write header length + buffer[index + 3] = (length >> 24) & 0xff; + buffer[index + 2] = (length >> 16) & 0xff; + buffer[index + 1] = (length >> 8) & 0xff; + buffer[index] = (length) & 0xff; + index = index + 4; + + // Write header requestId + buffer[index + 3] = (this.requestId >> 24) & 0xff; + buffer[index + 2] = (this.requestId >> 16) & 0xff; + buffer[index + 1] = (this.requestId >> 8) & 0xff; + buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + buffer[index + 3] = (0 >> 24) & 0xff; + buffer[index + 2] = (0 >> 16) & 0xff; + buffer[index + 1] = (0 >> 8) & 0xff; + buffer[index] = (0) & 0xff; + index = index + 4; + + // Operation + buffer[index + 3] = (OP_DELETE >> 24) & 0xff; + buffer[index + 2] = (OP_DELETE >> 16) & 0xff; + buffer[index + 1] = (OP_DELETE >> 8) & 0xff; + buffer[index] = (OP_DELETE) & 0xff; + index = index + 4; + + // Write ZERO + buffer[index + 3] = (0 >> 24) & 0xff; + buffer[index + 2] = (0 >> 16) & 0xff; + buffer[index + 1] = (0 >> 8) & 0xff; + buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + buffer.write(this.ns, index, 'utf8') + 1; + buffer[index - 1] = 0; + + // Write ZERO + buffer[index + 3] = (this.flags >> 24) & 0xff; + buffer[index + 2] = (this.flags >> 16) & 0xff; + buffer[index + 1] = (this.flags >> 8) & 0xff; + buffer[index] = (this.flags) & 0xff; + index = index + 4; + + // Serialize the selector + var length = this.bson.serializeWithBufferAndIndex(this.q, this.checkKeys, buffer, index, this.serializeFunctions) - index + 1; + buffer[index + 3] = (length >> 24) & 0xff; + buffer[index + 2] = (length >> 16) & 0xff; + buffer[index + 1] = (length >> 8) & 0xff; + buffer[index] = (length) & 0xff; + index = index + length; + + // Return the buffer + return buffer; +} + +module.exports = { + Insert: Insert + , Update: Update + , Remove: Remove +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md new file mode 100644 index 0000000..7428b0d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md @@ -0,0 +1,4 @@ +kerberos +======== + +Kerberos library for node.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp new file mode 100644 index 0000000..37c3a6a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp @@ -0,0 +1,45 @@ +{ + 'targets': [ + { + 'target_name': 'kerberos', + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions' ], + 'include_dirs': [ '> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef + +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_objc = CXX($(TOOLSET)) $@ +cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< + +quiet_cmd_objcxx = CXX($(TOOLSET)) $@ +cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# Commands for precompiled header files. +quiet_cmd_pch_c = CXX($(TOOLSET)) $@ +cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ +cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_m = CXX($(TOOLSET)) $@ +cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< +quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ +cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# gyp-mac-tool is written next to the root Makefile by gyp. +# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd +# already. +quiet_cmd_mac_tool = MACTOOL $(4) $< +cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" + +quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ +cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) + +quiet_cmd_infoplist = INFOPLIST $@ +cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" + +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = rm -rf "$@" && cp -af "$<" "$@" + +quiet_cmd_alink = LIBTOOL-STATIC $@ +cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) + +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) + + +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' + +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain ? instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds until one fails. +define do_postbuilds + @E=0;\ + for p in $(POSTBUILDS); do\ + eval $$p;\ + E=$$?;\ + if [ $$E -ne 0 ]; then\ + break;\ + fi;\ + done;\ + if [ $$E -ne 0 ]; then\ + rm -rf "$@";\ + exit $$E;\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains ? for +# spaces already and dirx strips the ? characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word 2,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "all" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: all +all: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +TOOLSET := target +# Suffix rules, putting all outputs into $(obj). +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + + +ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ + $(findstring $(join ^,$(prefix)),\ + $(join ^,kerberos.target.mk)))),) + include kerberos.target.mk +endif + +quiet_cmd_regen_makefile = ACTION Regenerating $@ +cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/SEmmer/Developer/node_projects/mongoose-seed/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/SEmmer/.node-gyp/0.12.0/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/SEmmer/.node-gyp/0.12.0" "-Dmodule_root_dir=/Users/SEmmer/Developer/node_projects/mongoose-seed/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos" binding.gyp +Makefile: $(srcdir)/../../../../../../../../../../../.node-gyp/0.12.0/common.gypi $(srcdir)/../../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp + $(call do_cmd,regen_makefile) + +# "all" is a concatenation of the "all" targets from all the included +# sub-makefiles. This is just here to clarify. +all: + +# Add in dependency-tracking rules. $(all_deps) is the list of every single +# target in our tree. Only consider the ones with .d (dependency) info: +d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) +ifneq ($(d_files),) + include $(d_files) +endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d new file mode 100644 index 0000000..05a7e3c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d @@ -0,0 +1 @@ +cmd_Release/kerberos.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -bundle -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -o Release/kerberos.node Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -undefined dynamic_lookup -lkrb5 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d new file mode 100644 index 0000000..6c9c264 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d @@ -0,0 +1,4 @@ +cmd_Release/obj.target/kerberos/lib/base64.o := cc '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/SEmmer/.node-gyp/0.12.0/src -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c +Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h +../lib/base64.c: +../lib/base64.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d new file mode 100644 index 0000000..9e3ee3f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d @@ -0,0 +1,42 @@ +cmd_Release/obj.target/kerberos/lib/kerberos.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/SEmmer/.node-gyp/0.12.0/src -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc +Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ + ../lib/kerberos.h /Users/SEmmer/.node-gyp/0.12.0/src/node.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_version.h \ + ../node_modules/nan/nan.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h ../lib/kerberosgss.h \ + ../lib/worker.h ../lib/kerberos_context.h +../lib/kerberos.cc: +../lib/kerberos.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_version.h: +../node_modules/nan/nan.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h: +/Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../lib/kerberosgss.h: +../lib/worker.h: +../lib/kerberos_context.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d new file mode 100644 index 0000000..34edd99 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d @@ -0,0 +1,40 @@ +cmd_Release/obj.target/kerberos/lib/kerberos_context.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/SEmmer/.node-gyp/0.12.0/src -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc +Release/obj.target/kerberos/lib/kerberos_context.o: \ + ../lib/kerberos_context.cc ../lib/kerberos_context.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_version.h \ + ../node_modules/nan/nan.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h ../lib/kerberosgss.h +../lib/kerberos_context.cc: +../lib/kerberos_context.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_version.h: +../node_modules/nan/nan.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h: +/Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../lib/kerberosgss.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d new file mode 100644 index 0000000..904aa16 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d @@ -0,0 +1,6 @@ +cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/SEmmer/.node-gyp/0.12.0/src -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c +Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ + ../lib/kerberosgss.h ../lib/base64.h +../lib/kerberosgss.c: +../lib/kerberosgss.h: +../lib/base64.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d new file mode 100644 index 0000000..54dcf69 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d @@ -0,0 +1,38 @@ +cmd_Release/obj.target/kerberos/lib/worker.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-D__MACOSX_CORE__' '-DBUILDING_NODE_EXTENSION' -I/Users/SEmmer/.node-gyp/0.12.0/src -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc +Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ + ../lib/worker.h /Users/SEmmer/.node-gyp/0.12.0/src/node.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_version.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h \ + ../node_modules/nan/nan.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h \ + /Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h \ + /Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h +../lib/worker.cc: +../lib/worker.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8stdint.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include/v8config.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_version.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_object_wrap.h: +../node_modules/nan/nan.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-errno.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-version.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-unix.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-threadpool.h: +/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include/uv-darwin.h: +/Users/SEmmer/.node-gyp/0.12.0/src/node_buffer.h: +/Users/SEmmer/.node-gyp/0.12.0/src/smalloc.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node new file mode 100755 index 0000000000000000000000000000000000000000..f6383db31c5b99638db6ab20c5e3f8240e23cc64 GIT binary patch literal 53020 zcmeIb34B!5`8R$i8(~ebD5y|_1_1?<0D+*OgbckU#JzVGkOH-IqiGvB1uYw z?YxM~97#N0>5G#n?4v%cDjBd)S;S7X6!$BU7m$1^^2YNi!!==N$PsyN-A70z}{y$pGIJjF{&izO`a zw)JUs)PFp?Jf3;wt+fzoU!t-nLnTSvu8-|^W~(`{ue8upwPfL(@={NQuQDRPZl$k5 z6+UshKIYRCrf*?6E49SunOj{}6rnF(bwSsBlH=nvJy1|LVJF7^VVdxJ2!5RCpTx(#o6O? zrYcH}3Ux*m-g~l)XFb?;vATNUo?mMi>_a{7fo~mX7@ZNPRm?{`?@@^RGr}1N+q*LU zVi-?=Xx?cUoyb&U7_$+aj+^Q9=+IOd@{IiW-fw$Vuk4$$I~j2z&#~a{)X8ACn~j^i zvMI48#u_OFOR9X{g(F4X`68NztkXeu$>@)9ZOG{=! zOFz$C!$>&8Xz6z)fN5_3e+u&5{%_0=#u-L!hEe?scW}&Tbn>(Yw|}1*lVupq@oxWq z^K;OjL+drny?`j^4owt|G&E88X?Gwt85-TS4T)}lhgpsFZSxorJee~xr)N&foLb;s zd3YTX$nk$~j?09m;4|))mKL{vhZz`)bccwz^as)P(q2z{F`E{K%#9%B_(Qq=7V{Q> z&(cK3S5V{|Jlw(b-USqS63U=0Wd04Y;HTm%$n|$}`5TemY{9Y5JRLDi0~ybSH3!KM zO!r{!nfAI!cfZ@e%}f(=A+s~W9RGHj&`W?XfcfDmwlw#f9uU%A%=LeaRCE3BnM)`e zOb>)}jY4d$|9x6EMKB19%$qKRl_`u6RxVanRwLSGu-u*ItCm%1Qy! z%0A)gKS_-?EB{8>VEUJsM_T2#-~26Nm6aO>!!xwVJbVGH^fQ81E~{tzc^z>!6K|FJ z4#T0^O*Fwp6Q4(@Ox!I%nz%MR@l&9}ZeprbIX9f^2*j0%9R2KvzrD}rv&3wcv`$`1E zvJK|OF|aR(m?*yn+IJJ;Z1!C)l^yCCZr=uQvHY$@sO-B@fV8hNJmoj3(N@JrC>u=A z4d>c~SY_Xff?-*M*#&@kA2HY$7}Jv-xvs^RXr9lwP;3+;c;zATB-L}y7VNRjm~fkA zgoEifVlrZtM97>V6|(a*j+Ul(fN%olji9+#Zl`~^JoAdoS(#U6dS*3> zlB$!vHe@aUPje*;;`Fn?%~GtBeI;a0CT%)tEoUlPHd<)N96`buLWe8@nnuX%Lqam4 zS1bbRBxJ^r(3#L@xgF{jC*aEG!IS&pGB?N@ir2D|X9(RqR8@j11jc$U}OkgRK1zC7)y@MdqBdk|rE zfNnGbcVKBEtEa1Z8*NfLQKxihH!{kfmFNzfJfFJ#AvU%Zj13^RuE7^mfIXFm3<$Nay8Zt&uZK-d z(}deXrDP-DA@iB@$g$silw|>YUSGoyV@7LPRpj`;HAgbRpl~rPt{RAC)?SmG7+rly zPT-nkSl0p0*j@W>w7d2zS9LFUU~Egm6JtB~tAPn)_(-_+COqA>p<`wSl&xw=s9T8$ zp(SehY^kL-bfme^e2GR0-?hU$1+e*~u(Hv7SP;@PkS|-~^$V(%7ut7&V1&E*7iP>& zy`xYWftX}>U~xPQm~B1)G7MPtD8?yafU&%TFrc|h7~j3%%i&P*rFkd7mIimxF)_B8 z1;_#hJoK{aE*Ptub75urv6hynP`oW-ScDKOxdL)x#D12|$vj=i?Z~S;D&!ue+;?AM zPQb!+E$^(0;h4jc&QQbp`4aib^vC7-m&dD;gUEQ4e{I7NEi#taY`4Fz0=7KI<}2z8 z=DLHAGmgzRigxWJtyri=FWzq!U@fqtc0FQ|*yU*6Pp<};>wmPKF~Qi-DJ0Zxk=RT) zKwu5P%s;~}cWq<5J9zRcMhCkF1XVQYH6Z2%h9{e!WRSG1fmKuo*gU`pVQk2}hAI?s z4&(hCz#7aX!gX)^D&2wT9RGw~&H3hij0!G;huC3$F%o*#Nq)0l5Yl^I9M(YQ3u?%` zO@x>=>@XJ!M)>=!5LXS`+(fu`dxh1jasm?)n*(S8=q|!f-2jf}DXfSKeyN&9OLH6< zP(i7c@4wzAO&#{v8~xJyOlk zSS>lI#r0r@^)pea%vI9}w2r{U#M)y~)mP>OJa8EM%{Rfr#{O5<8t`3|@i&^qLbmI_ zJU{~-(^}khFZ#N<18Ge3k5Gh={^&`7s~UVhsW&>IZW=mGbI00a03W6qDw%SX%%>_D zuS(`SstR^p)K)UXT9cU~l0lb*IFoAn2!Pojgk?o{0c`$NNHm)F3PSqYoUn>sA*dnq zQ4xxYUL_b&(SJ*aC)fs0U@nkRsL&ne6Noi06YPy9ZNS(#GF<67f*LZf6roU>A{gOb zmQ!gdl*-a^E$@^Qn2heX?N~GVWrFb8wcBQ+eBJ(++_mq)JAUn|PC`7qV@~Il@75rf zE5G8isuM<$%X0!N;+toiJE2$ig&s7KcCym`DhTN}yTkH*y`YB7r$s1CTq_vSecm1p z6JJD~<-kR22PpLW8_}&2R*i)DY!@d%qOKv~hN;8@(e8k|C1Epc{Aw$#OQ^dGDslrA zJ+speX4bBNOL}aDgXLdJ7`xPg`2@{MAOD-wWTjA~A}EJyCi-6gDzvIlg?$@v&q?k9?eQ z>{lI`l5l(r0MW@H@0Xq7aD0zS$M=A8eBYi-R_*wfoFcFWl#96m#j6}&;3R;-t~W7| zedjkI<^@KYUkxMW8Twu}x-~$}|1eIuzLiwcN-rh}hRGQ745Dy=Bb5VG9o}>?e&u#r zYMYIv9c6|t0S)_lQ^sn$l`_0EeY(7cYDuy*ysnoF z>k(QrK!*>#La4BO=-p7Eedrb1x!nXFIKlI2##-{DD<%uMu7A1=sMCL51|>+J{&NYy zRSnfE*koPHi*=`I_QHeu7Mc6VspdN805)F{qK)PYf{=dy_^_V-CqWIFuZd9f^g9J3 zoY5z#D7=Nys7_l?ZvYjRms{@p7s3_Dq2Xysyik;`(Aa3^33Xj}T-rvqYLSA<)|~)3 zhigFnY3Jv$oZoCSPN)!u+8CK5Y&+Ql?X+?UJ{J(+@}I) zx&>aTeUExdTOPHtKgK~i3E`%W&?C2czztB!QSn=4Kb$Y7*>JvLTrqYH+Q~=QCCu2}rHa~gWI272S58LpQeIaM_le>W0{A4lZ9)g_Z zC&gqSy1Lak7_m-UqYeq#=GEJ!lt1PZ#=&{E!5ulKN4d@G*6=v zISu^|+Z%99F?j8%nrt+P^u`Ndrp?=aI~am97^l4PXW{fWLAQD1-w-}GllipZN6n{zDy^8iSXmFxiP$9_J?=u?;B8X~6-b-xuJ{~CIbHE$ z2-sY45m36~OIe!G(v{XDj71nRpIs+x`o`QNbXdOlRG?T2!&6qz%MDavLGq>90Yw6b zmYu_i!41 zK<9Smgvaw>*hSz(3m#0&%hV$FkjP5HswZ?lViM{u7n3wuQ2PYkDyY8$WkD@u80>ne zfYvys{eL-!JYv{-9-u0yXed<$)yXO-n9^QWPHW2@e5JRReOg0_%gm0+Br%Dpch4e zL82ooBgen58A~NBNB3D%>S|$=94cZl2y;w*4mNR0eJ1h9DfRWj+Oa*|ezA3xS-TuF z1i0$uVp`3SD9%#fTd9ZEo&arQ$4;QOv12xNa?JbRZ)5EE53I>f`;f`RaP}^eIbuGK zX!dTbD7X=&BEiTIX_bKM`i$Wa#X@R%P>a>Icsy|RqT0~y&&ffh=BOr=>jZ?|hI)A^v zKO|#?B==!L=AXmqt3an^YJPtqQLe;-v_@`n=sA8L(jsDc;J1dW zjILqBRXJ(*G8f2nZ_rS-9noq~Y$kV^f_A z8p-@Hm|;;fhb#N2bTf#}=L%b`1;Ts%5QiQXGS{M7Wj-2+HiBRqt{wx*;fi%f@|B_y zgv{v(t(Ak=I~Mz){gG4Dk=)qcVOBs|?#ESQZgmCrqoqj{Pjq`#68 zmhh)wVM(4XxJ1HVG79eAoWO+VIujl$^@+al2#74iYrshtx|?{U3q4;%&+I9^PdvNq z7HEM_&|9qe*oQLz_#Ru#FI92EvC1t|YnRp9Ip7jqZkgr@HTEr2o|KTTB~2L$`;rnI zuEnus`aEoEbuE253ao*4ma#CTYq^92L9pvg2C@On08zM>XU`%@ZkbL2Y(B^cHB-%@ z3Pns|Je>;q^oM5x#vFBMt2bdwHFq=KzQHNGeX^-y6XtQrd`lngUs zCWE(ijN#eo#%7<}KWisA zda+k50XZ-5>}msACM#C-?0f-+%v6NA!R&@7qrd=TkW(5HB3WtpJz#ju9%iD5e4J`& z#~2&Wser|}iHdA6sOig=J!oy_J2Xe_0961sUuJ~L$vjADVxF*@J-puREZ|w2a{bG; zz>2--A?Cw~)A_hw@gg6q1sF2tBSbznIr7m$veLkk5&3Y7$j7Oc`KY$>Tml$PfTcwj zbFw>dKHqT0nor>!2R(K-m<;FZ!>cqgZxb0s3Nu;Od1MO2uFGOzxX;htQ+*QVH*Afz zJxuc>CgR6y7i%0p4T8;=(wOZrnx>2SS<=QxKOp8PAL5-!^B^++-eT5y`3;#9$qZZP zAf0ARWn*A*FT6TIdyowA%c75;bCK%@xebb3vmDI1!b$$*oOcun?>Ai$ zIsX{;hvobp+NyH?DLkag`HdnAbRjDwWWFXsne*Mkm9~-d&4RGs+^C9cHu`$obuM1a z<1OdrG?DE+Vop*eT7kLZe=YZ&nYcPI5Nm!X?A~vFfiS!k{2MW0W${N^ugc=kX;xX( zicGOAsw8B-AVOIdjbLoE72Gcf`_1*j0JMMf&9Jh_3p~O0FIT6%%=&mLY79h&HTK@R zu?M16TgRaW-PYN?`pEp*T6bq>zMiKgDqr1N^Ywr*kome*Lgt4el=*7L=3$%pdR-9q zn>$ruT!TD>6=MOlsO0WY%9etnANlt zy6eL)rY$Tt-vp7^tfu7(%A8)n?p;oc{QEhaH$4GZd995AS%lv!ZgF-{x10ns3&yl$ zVet&Vf&Lwgy_{Qc!LHuH4Eo%R;HfKNAiB7EN3#%$#GYK3rVG|g?3|pCu(<*2abF&4 z58EGeT6X%g;;Vb(%*tb9sA8Y_YA=M?9I+0pv?l!FAg0*$un78`&V&~t;pP!A>NQD| zJAQq7l2%6AX`nqWX^%;{lSnHMGk7bqXthb@3^7qb4eiPGA2r|Yi2_1T!aJ9Eyt=#v zve@yag$b+ZcGtK&*Swohv+cWt%`et|6_rqXE42qMM>kGo!QKja4sItgPhGj8bbh?A zXVabJ!a}|74+6m357`e^s53rWAeN)fV{#IS5m3C9#H68R4{b9iQ88POb!z8AnbjA? zu3VoBfIY>A*;+TRv3P^AJtg0tC0~E?Eeqqj4}47-9K(XKAILpEpJYCT%qzl}uOV}m z81T?QviH#2KXM9_-EVGSg21o920&|zmF;sM>=)%O+vjd(N43wM5L4~53qTg*l?Zh$ z$+M-khX>^OcVzl^=lI{q@qfWK{x2pQ#4H9w*slSbyBHDZ9DX37qcAR%cGO%32q!r4 z(ipR_@&2#!{71~)l4|y+JxbRZB91;`i}^41UNPbgu+1{WlrS3!hs>>l0sdcPC}hsY z4g)Qhr*hAODo(ZE=2Uwa`L7oIoNBAa-da$AtUQbTg47)UQO+7d9Z&^^`5{Gv%Qi8; zqX3)l2wj+Wh_KPzg%GpnoWO;gS9LMx5SPNj1aTs8pLvO3>tOzgV(JuIQxE7{OF|$a zy!>7S1%~GYPC*goDiQNJ#=;hJGlAOesd`C*-9WaBoy_YWLBq~7po_ktGb91lhs>20 zAx#m`dVYnnV*b$zZyn7vaR^!A0Xr^Z)wAg>SkzkH2Z8BR(A-Our=Y(_tULw%5g@VP zH(ytB^p`l*hxU{(qak4+8gytJh9#sQ!bnatDiaZvB;e3Ev`aLiU}e1dS191h2kU{o zn3u+n0vbp}nH+WptKmyNF*||-p3Y@do*bw?jBEojLI(N{PRuk^pC)%65)o-$KxOb4 z2_dip6bJOM5<^+MB=&zoW>1J&%|k53&?WrUTl~wmhO+lS$as!Fx{!y=K0*PbOJOpd zu!_G~u#x`83PV+J+mMObtk@z*s3Lm1gV2~8T=qt8(7Pu$xUk_V8pe~SErIH-dHw@= z{wA|81je+q7{*nz+=1$yPtgE&-#;K;F22lD06xW%RH9py=pk&ZO3^bdQTmW8TSean zOYO2fM)j)aqA-(|IqLzsT4`rvfEYUfnvXt3dRhaLM4!&VfyMVAN^PGaq(L7L4`gr3 z_45_T_OQMjjGZSoWpEx8e#>f0?%MMW^xELE&(mJ#U^S2`YL~_vaO*)#+dwe0h1#W< z#q*$M9kEcBXd)O>lVohUj7>rj*vmSX(HtYJ8dpQ^Tgf1xvGiBQ=;M?t4|B+H`#;0V zUN%)W*G<@rR|&;IV@_y-NQm9NPYp7FL!Z?fSrX&K{t^0RQ8w`G1|AH}4opIWWtSYE zoCKhO09yO_GM*v?m zf;O;+2xC;glxa%^)7Fb4li6u6n)g7F>~0+b)$d@Fcd|Q_%`!vHSFcy>^%(m&x7Z%uol>hijK@X%*UJ4x&&1hl0gY zY%wsN@wE5ynTS(ucR{wlf3E)+7O=Fi)p-VH)w_dBUFL;?bpl#egYQDvzYa~p?SD(e zqaoL$`g-k%aly)2EXI0P@dGF*!0R=P5^b76XA_LAI};={s@K16bt3e88TR(H2ki;% zLbs>QP}gRA+A4Zh95rU|MSB9Cy$5xL^iXJM5z{bb$!kEHV72sz8e{@4@E{C0Px|{% zG)u5~Fml$ADLhcx+iWA49pa4gS+Q0dfwt-f^R)zY@3&D)J7s~(*ryQ-{=KrmJ23Zk zZ-*85`{WS5&ewgsA7^m5fXir|LY4I;9jD*EYAqJ|LzaAI-v19-Jh_2>eTM<(L11KA z^uD@HAGfq546Iv^pta1dMS}J+8^}JG><&JD8`xNEPa|t?f87?MMRhV(sN$^eGIu~w zc7P}F40!@)m?=={|I;2IJL>p!xr5KVf$*tsLEt&zLCj=O(3EEQK{JuDwGAX}`L&kYJPf1|+4s_7;wt5@K05>Ya1P%sx1{Fs@nRY+C;gZpS>5qZ9)aE+|IhO zdW`uU6$E4dqV`;l;7GJJOv+i5sKjrT&xC`{5I!N4m8wGJ01Szl{-c@Lb_~SM z5hl^dJ)ydt=!48lZt%ff0CR(PGsYeK(-s8QF#qv*|MwWHX~lW8LJadbN&R>Oxj53J zCih^FG9Lh0{4#2vIRKzF+C#%prQuj-ts&K^0ou%xRt<;1S^JDIF`=#;`Goa%rLaI- z_xzYO+icwY8ZzyU+rI|UIc^7KT%zzMRh+baZZ45=y<{AJEb+PNk#R{fE=j~)%(%eP z0djQz4Y5#`Y(jyhsWNt{jFk;6urx!)dS$F=ep@)3Lj7^jw@f$tfkRJUuR?>C)7J|T zE2pn1faLV`7l5o9pIVUV{~XhTalx3oS+VYQ?vjS-)24x8n|oVRl6#wZVQ{=F7QaC- z4|M{a^Sd))L1yi@(Ftq+0+H-sZt{1TPd#w|{rBf3{Pne*Z6EZV92`F-dQ!0WEhufY zl`(Omhdqx~a>C{d-2SiJE8qQ=iEV3&8n>p)sMVdey&qHierm$zNiP4(+nQrKelu=O z@AFq*=GyjdRPDQ?6E-i8@_)0fIj-Z&U_XELMN#hB_b&u^;p&T`Gi$eh=dRs>L(b2~ zz^JGdw`DGP>AOtVi+QdcIj+WR|1R#eHfGlyTs}K9Ve<&L{}ZN*-Lwj9_^s*EJ#%&E zu?>e}#?~B4g}iHd61XP0R=?cP95XilvxLo`t?7MA=IYB`_?=0@njUMKyN*rR{Hl<< z*!9Sm%+&=^nLDzg$K=#D#$@h@Zgns4EIDdtW*WA%MUnI63XaNtlNrJoh{^lim|6v6 z#`?Ey`|6BsO}}&@jB45DF8az`!bukkdjJZ1P3KiFCagLY5L`e^ZZP&_n4aU`hS=3# zu^rRjPJCutBxkD zenN0;9v!z*bnb*zoJi#+JX_F`Q~NcTvRA#Hu=*y%WhHDL9i^F8B4XQnQU2ZAK91@5 zkIdDhGF#$MGH+63^0s$lghPV<#qqQ(Zrj&UDA%t$zLdH85*Ju&TgLbXKioiu4yehv zhIiv0X+cVhW3txth>9m$R8H--Xs|YS%xOWR02Z~TGYbIOu5)n`&L><*9{>{d%sf+#x4${&uY37^G?>@tfr|7QafeYKru3low6Wc zwG(kIK&~9#P~2kU-24@49A4l6m*AT*l$)0_BGC19q!zwxzDW%9A@d;>ZXlzaiez&l zun+Or6)O_E!1nX<)ji#TnLU|^d6|&ao6ho$>mwqrv3Vbg$;9Rx)<7YaR;G1zl5t}lpkA&fs?NsNKhO>t7fcyV-Y*f5x<1{76UpwaFR8ZKsg;21=O_~ zQvj6cpMg1k3AYS+b^a3WQ7S??-6yIhWX}2^qMWdk^SwEkR;hAY0vWTnh)BN=jzvzu z8d&Uq1WCOEtpzA19E`t`B29SUh0)Wn%=R{P8)C)g&JOb;37V4-@*Uw8De%W|fqKU3 z8HifU!I?gZg4OFOOd{FJ-@`y}R!L>})o9bX5X4k9(To);V&6anFZ@u$cam81A2N?{ za^R1B1|%~>rr#+%{Y1w48##Fjf|+{*`d6bLi^xPT9VoF%zlw*$4oJ}4PgI!w|;6LE-&7ovbFJ@mQtcZ_sG=Nv&4sRu4 zq%r^|VTH^Y$QE-3BWt&h6`oOgfK7;M;%{cfdEmdJ)gIu6Ww7gW+(ZiYX$I!#-Q3D* zI*F4he`9lkNKo$Fe$NsJ%AL%^gi$)IakjVL@!TE48xV$VQrh?XV~_O%xBP9Z?x^R8 z-TxSDk#qmQ>P%B;wtmmLi|MFdtY$#S!xzH%uHRsL2YKL2lc&(1X^48$5Dl{u&Zt3L z*y|Abbh+31Dk$N5t=$kKk2R=t>RbBFhrKQRekGoz;#nr1JlWLJuTngH;<-pX7mMfB z;(3jDE*H-l@w`?%SBd9!;<;Kp*NEp@@w`Di>&5dX@w{0)evzj*RIS4+Q##B-B)J|dnxk=D|0vv~4MQ%k?6#B-~7J}aIL;`zLI zZWqrT;<-~iUlPw<;`yq0?h((|#q$mEd{aF4isxJ6`Hpz*6VC(U`JQ+l6wgEAX^Q6u z;(1s+KN8O);`ym~elDIz#q*eWel4Egis$#@$&akG^otVD81ak~&v^0dB%WQwvzvG( ziswn<*+V=}!4qyX*k{^V=pE~}awXK~62faGoJY7u!a0O}63!+(U&5J$uaNKe~(+OutIF0Zi2@fWmB;kRCdq}t+;dlx6CH(Ev!nQtyk4X4b!UrXMGU2@v?oN1@ zgu4=MkZ?!Bk4ZR|@CFIH2;U~*@6H5VFX68UuafW=gcnQr6T+nu=2@|(*%EFdJXON~ zA?%j$yM#we_+NxmCHzmq$rAoM;a(Dcjc^wUze3oM@QZ{$$8;2R^a5d1!rKVHBjINV z?~(A6gttrhal%_9{4n8-5`K{IdI{f0_+|;;O?b70|4jHA3IB<3g@pe=xLCrs5S}UF z-w@7~aFFm=3Hu2TmoPWung&RCCE?x@UPd@k!b=Eq`i=Zn6F!D-PXPWk;lmPMNcez+ zO9;OqVK3pG5-udXRl>6fZ<6q(gzu8@G{Wm7dnUk0Lx?!s&!FB%DTgkc0;lPLl9I!aXG1k8r$%`x5?ki){adk4X4b!UrXMGU2@v z?oN1@gu4=MkZ?!Bk4ZR|@CFIH2;U~*@A?9+m+)7FR{?IhHF#}JjS;;nirzv^b|g@N zi03f@G58L+7Waijeu?23ok~(Nfsk@JDcgZ0Y05!Gxr!9dDf(y%Q=&{gDIKD1lw=^J z+(*j2K(0n8Ea;1vzCgq^4hVMti~@wND-}{sTea34nGFAjJfNeK|?_0tk28Qc2-t zY^0`?07(Keh7>;#S}L?X420=SC*^%0Sj z0ezHNO3DZzoj?`ZXeiA&O3Gv)EGj{{0tk!hds6-YWR#}74&*E#on!I%0tmA$WL)6I z+g5p<3&hek0SMVZ1MJ2U6EhSQ{kXj;Dc(h+`>prTLr^+`(o40f zU8GC`;=(N`lVKYz;M(7y=V5*XWdRVD&SX+H069-n-UGtYxq_5fsAPVGOm`qdfQait zAb2MxDfvKX+hWRG2c);AJPL#gwj*@yR>%P&CLSy|q1ppM8d`zSwGByH~V;iw?gtFumJZeRJ?IJZkqQg%EfpCcNT6z>8YArH?rjc`KzXU3xpQYKNwuE zvgm{iiP-QceRSz&^5 zHjn}!TooHjfY8qi%Kbo+fN(u(yaa?Jq@a8Rgficdl8FcNASi`EP|tE~xLP5CvH}R} zL|iN$W@raO*J}zH!QA}^2(^7i%J+Dr0uhuUAV>J@oajs{WY)w*0Gn&_>zjBPZJZ*a z@u0m_JP)^vZ8PTV80)h37EqYm_ z92CW6pQFsskpyPq&PD?gT@Skr@@hn|47Z@TL1x-lAawB%>yJ)bwF|aoaS@n|n=?hD z1~<0;w6jx*v~-w2m0j^Vwax8u?(2XQ;ue&T0niXS0oOMG zBJ$hL+>%;22Qu!%ZOtv;1~NcXI)hBzXHYj?ZG`SN`zsg=a2sRrz&544rURj_UmKRxT_1lUb!R*@#RH@j7geXSW@aOwrfWYlJFsNej9#JQh5cr3QLoU=0nI^ zHqT0xNkk@KvocJNZ@xDP##fj6lIB*HFH9mHR$NoORTcQ^FkXotC|yx40@E35R*HBzQQaaBq|_QHkU%9J5xpbVb3q#`ACNZQaLsVP;J zMJbH)l+XER&^zJy1KzTUa^XTj-k)9sI!dkcnR3^up3=?|^|x z5LlFP-g&vG)zZ;~CJPHMIPbhk-m3g~;TPA>!N63-p(!i;4^l8zR+yRfCfHRaw0W zgTRz2lc$`AI1VpuT$$st#%E8M=+3$5;@rGRlk+c`QZRMe^cgcRy{vFfQL%UKy!j=+ zT2Q*Mti0mamG}<=i>_L{f97Vci1f1%26Y-?Wwe|>u{pi1z@~T z>OJrL(Kw_bF3iZIV`Aev#CPn}xl7k>35nfL`bCeEPwCm~R7pSW^xl1bc}7y-GtWxy zcXs~)1J5~k(BL5{G*QsuZNvnP*&mOaxEnX7Lx5dG@o-(zy>rYZug#3Tq|g=Z0_^H* zL|ua0g*aDg1y<^CdcD9s8v<`%gaX*{e74yCBh4D z#K3sbRc^A;yQ0AAo5<_;@PxUIuT9;dUm% zEeP*IcmTu2c7!vBBfZP9Vn8?+;nnGeu@>Qb%;XhFHyd<>y(hpPgySa~#$JS*k@@6V z7_-3E#TaJn6(wPGJ`Fg`cKs2bk6#{ZMBg80M33%d#MC4hF^{&Fp7HVc$MB?`$J#>)A$Zzy3xPeu*B1-?h623@|!O z$HFmtdG-*Jf1u@q&1kL1Kn8fwIP zhZ%AGMi?EFu~O)nVZ`Apit*o{XSk-EZ*;(cw5YYCjcEJ^Bl_$MjSlr=F*v)TQ5*Qa zJ0G}QS5GlqixXXmT{^_qqrQ?6*BkducgyCJK_*_A-4d^h%IX?7jxQ=DAB*x%#dj7X zd1*e034Nu2Z~p;4rpe27b$+g}sKc$dbVfC4yHJfn*VRhT!5G1A#9w?^8miOHukEll zE*N`5%#FfM%As0~v+tK|=dwlPitmpPAo0?27uUwEwWP2i0iK(2pZ0)c6Du;xUHrpx zyTIprNXm`ploeNe=Z|EBPOl9+V_;j&qmnIP$>Crfuj9y#hTI$6zr^)WoKEkEj5v;* z4{{ehC)wT*rA0eG372z}3){zNIEVQ!OSWz@xrllng!p3cJ^Q@myTi#hF}%E~_h#@9 zZj}64PX4Ugm>Xat`L=@3t@zqYpY=Btd_xr91v-BhI`ZeJ2kPe{a`+BuN5E;vgj&%` zn7_xM|M!ZoT=B*K!=XRBwZHhF_stW~+XZ~1LNa|z@5}A$@5c0hfclE zwXZih#xMr$ly;OHNAFhXU8wjhdmn9EFU##P_%|wk_Dx>#yW8exeQ?8iuj216xbe{K zTH)m5_Vqr+$MH;D4nC$|3cd!#r&liVw>r|dwKr}>KCAe1lv*o&n?IZiz5|MHQ#*Vj z|44uSi?UpcwLd!Fk$#SBXUx||=)LD9$$z|j(bue2d{(}k?Oo-I{lf?T>lFV}%HH@C zhaGw0{*?BNhL4F?{U5`UymUFM@}T}Vp#L<*XXt#M?$Gb>FFlmH_Qs``ls-%&?{?gmydwFyNhvO!{-j91{y7*H z?Uwvps)zBbc22#$LG$jBd@nos9D2#m#k29cH8{@!6 z@ZbD5sh{h5acTXkJbtJ?6W);W?bRpkVtYM9@$tQcxO6&gjFUbv%=x?28^N#o_Yc|i zyEmo$87eue+!U_+(G4fSR|=Wy6kmJop89Uaz3FY4?h=)bm9EW?vLB880e!udyluYd zMbTOFMV2emj8b|mf0*Eyzp3&f|5WN!{M=vS72o2RU#jtZIB2VIzoYp3YyNW``W@|% za?IbZf5>v+NibgVlaDV)`##4V_fILu{YqZ(MGiUD|C#p~^vzvwN&fcyw2|20X;}e1 zDilib;5v$z{{LC^_C>QKg+2NI@OT|lVN9OH6IIw-g#%PLT!mv*n5)8>DlArEg$l1x z;c6A$titsw+^E7WD%`HZJt}-hg{BHWSD`UU+Sx^gy;PX2!c-NGR-s#kQ&l)yg{3N7 ztin|)tXJV}D%_yL$5hy$!d)udtHOgSJfgyHRTw{6+S@~gNh%zq!VDFTS7E*iuTbH9 z75Y?Iqr$Z+T&KdjRJcinTUEGIg>R_vfC>+*@R$l?@>Tt-u(t{asBpLn$EuM3)P&be z6&9eAI9u>Z$LQ{pGtC0T^hF49R44u#Q>P6B$)(fR@ zj=ke0F7_3|N&mlK-5jaBI$K6?U&MaBJKK)^4F6mLKbOGICGc|z{9FP*m%z^@@N)_L zTmnCr!2iS&;JaRI$H#Fw#1OAsML1i9^Ho@(!o@1AQQ>M8)~j%x3fHS}g9R$;vg*Qs#5 z3OA^5lM1(}ut9}8Rk%lmdsTQqg{BIRsPLEynMsjhdW$Z-JXpLxXSVOCs%n%`4vgsIt{sK zlk20XPD7q@omUf;m>3t=DdS<+zoUY#zsLMO>gDJ!TrIArT^XN6eIAvR)Tz^uwNV?Q zK8^YyYAvk71+$G}0m%p7huZN6fX~H2xek5Ha0)`?MV!LEpNGkCEr1%H9MkwBz^f!l zJef)|?hF-2d=egZoTs|qQ~LaXsZZm#0=Dbpm(=YzP@$h`@FGtAcAWa-)CO=YGEDs% zCqH@Z{B6neya=zJN?zl+z*k9a*jthv!asEmHb4uH^?2z{P;_cAWA& zufpq5C9m<8cI>$c?TVMyXUD0J=U#Z73O<&P#=XGX%AYf`wtUMrM7jgy~c zy%vq0mzKBVl;^n{Uau&5jca**o+b32}2|U ze}F@Ijca*(dXo@o$0^TqS-fT_d5vp%dwP_&GK>KuR}^+<68cQ(%1X6UGM^$<*#uq ze}zkbTk>|C@~P^**DXq3 z<63@`L*9;4UcWcvKLBEVYFx_~6Trn_5*~J(@{{<25LZ+ODX($zC*!u47v=3Z<$3Or zS8pY+aV>8zFUs3-%JaM=uMtXK<62&y6CqA{J5KqrIA_Ugt&-RHcHnKb2j#x3^04F7 z$8(#!K3DoQ&h%LxLQn;?N8|nDapo^Zo;@YoD24M3DzA$b&a~^r*NKS<@Jfed8Uz}~en%`cn-mCo{4VnE#C$Q&{;nke+PJ5^Umbc@S|5h1vnv&PJmJdqxR{D0F^8Qhh zVU&{BxR%%Fp@`FdJ5Kq1=S%q+N?zkyUZ0QB@^+l^UyPRWS1EaoYk7TcO3T}E$~W+L zTexmf@*3CjUr4f*e>+b3$1ju&k1BbMYxx$3yd9_fV`C-5^GaUhTK;K=yd6JYdwv)C zij^#b4}iDTp35^O(}u3H{b>9l;6J53->dXJtMqAH=SQER*?O`*&W`HxpVhrn+ypRa+pRX#V2m-?QE?`MD4_&dPcDxW0DZnYOX&ip;3 z^nI!HX`J>Zn^89@Yucb;}-K9K#3&g7z z@FW4rM~VZdJ@)>01?c=d41X8Jt6JfADSS2XZlLS^j{6j@_b*;mxZV%=SmAno-{T}H zuh;7%6|UFcS1Meur&lOkuaECixL)t>P`F;d9#*(sPx2o!|I$@strzEb$e`7xNeVc633oHQlTvG1H^6P!3V^<@CdxdT5mt3aJ~M2N#S}uZz^1`kE41qy&7x%-CN<>UyTrW>-u7X z!u5J(y2AB*eXhdw{C|I}JGM!%+3%Ar89U|GrJ*=g9Kjs&KvkxliGG|Ne-=_4|UT)2Xk<+OO%MaJ~O? zw!-!P!8OD&=SZ!R>HSvWi3(p&yjzWR-uSNy*XNG;|F~$sp0B^JaJ_zr?JengK7N+M z_53litQut?=_z5z<=$)*EsOMIB-Aq`Jvy^$N$4<$N%lX&pacXUgW@k zpn_ytMf@>e_X4G#RD4!lp_aQP|+euo3!?!dot;6u+0*Ei9D&v)RzbKuWA@GfVC z>zm}j=Q;2-4t#?H-|xUzvO6L%BtX55Eye~9}d+#ln96Zb!G@5TKV zZhourZQTFDy$|;R-0$Lk4>!-Xe2V)s+@Is-*BkG|{b$@f<8Tx1-{O7;_kP?T;QqPn z|7*)W$?99&dh=?$moPq(DZsV*rkPEj9svA*asq^RisPD7`7@e!peZwkKLGsIU|InV1$ zv9eNHGRH!Olp7w;Wy6X~y!jUw8Et&K2GmIz)(2#UW-oH&H{zo~#omglltmdSC1pjW z)x}}ghqKpx4@$sOXNd>8%5%N1f+1c4A znmEi1Q$Gx!63U)(F%=I@ouIxbr9WSkQ#Q9;q?0Z_NyKErgwsZ5IzNu}V|1Y+#D|x3 zTP`asOTq0l(UA&2xb-7bv9|?}`U+M=Dx<>kB0r7vW70WZ$?%g%KV4Twm}TO_VLwt? zZd!&X?BiQ(Q~4uilvkp^uugM_4)rW7tT;YXYZn=rUs+z{t*Xk-A631`a~0Hhs=}K_ zdM3a4<)la0!OHwWJ0h7{6|QG^WPaLUbCwG$DqK$+=-ekp7iz8uybEnR#{tvzbmQ2R&ERNG7&VUHY-Z=1oDq**Qt-b=ZY2t!0R z*qtIN+W3pp(k2y_X+M=tz>}R%FE%nqeitoU_{TPVWl8>|f?=LW$2I~g;SO`CMteMJ zNf%#W%b5y;?Mk5oIcUd;c}f;mlzJE9>v7_Xe4ezSo|3Xs<#fV~&l;)<%D-J#uUc?`A_&F^1qXjnzfI z@=EkY)HJ$cwn0DWt^990TTZDGq6@Y*OCfEz{$wt` z1Ir1tn2X5yhnRa5_$o`v=3!O5Ka&qsL8_WWa;dHN~4fe|SlZ-mWicf=NxhBl3|b}S-NvKAMS6uk_I82A1+ z?^XQtO%p3y5hhyMilpdlwX^!N3emCJ(yKK~v!-i()^hmAwCYx&|FwN!)_QxoI5z&s z&CYgp{h!{2wHfxmb+h?+UEC_ypVGB0;kI{kTl4e7`@vSnw{%)<)rzrtL~D$87yl*u zeN(4L_zgMr)LRp1m?ySV^b=R>az)*q@PFl6zP)XPu%*6Q-|7XeW4SAKIk?v`G;HHS z<_Z5M#FOQjG}YstTrhQ9WM9#CI%j?bgCE19c*m4rlrZf+JYji zXVQjdRpOswcx4neb_+Zi{9h>iUli5`FJfD_lUZ?GD}|{+qob%L(I%7S6P?o5x|4+A za-V#v+U!e9EAaXey;uG-pPw0ZOdC_5XX z1?iqi1;af#1tXQ<2v5!;to)d583|o!!=x4buNRf&r8Fgty-}vFb zZFE7&JiI`tuEbJLY;}slbL4U;a~b(RK(b4$f*hgusap#M3s)VfwgOpxZ7{kEt8%c7 zT3A*@`|KrX6~l4T84A;~N(-y1CgDHEIOJPv;5Z6K=)|?@$F-Ja>MQpxsqmf%yKuH) zO%L^{>RuO)W5I5#ds|_k{#oIfd|TleWv?@<4u+;?R}~dj@Wp_w2aOPs-t7FazN6n4 z>tbnJw!LmMbb3bGu<<4Mw<=ZMiKXRp3QK=TJp?i&C*EG;^^&&|n`JNxnQ5axBRaA} zBhie!!UbNwOll{&{6)HS+kEGwOO}1d%J}q*QGEYac^tKxR~1@XMjJgrZX}_BE2d#= zmYJpKTi)XQa^bRa%EIKbOY$RxG73t|uR^~G7o329spJrKm^2JB*}rl|@{N92+jBC& zL`R3QIvn06Bh^0u8ljq~RoWw2nD}p6k)6}(OM0Y8OGU|MRac_9`dZzBMIAnM zer5Sp+2WNP{*e|7Q#tvz3da%~*{W38*s9xl;WrY+cS0^LLp!2jkp!~X3@l|cxh-uT{B8Cl>r)y+GZKWbRXtBfe63s@KTHZDxBd1Co2y*Jm zm|EUGMa@@QWmM&*rLy=G$yn)KN1kOMG70KZ{E8OJpaal~&n`UaW^%n+B`2 zMqv(+RaiZ5zUpNKzERfE24PNdsq~g*S1m-{dobK%uiI1UDL$ADQ{xWvQ% zY!@DbxsR_J=VmC4;{xT#St}Fg(UHnZ%2cxIpPUI2E2yIfmeE(&04tWLR^_&h2i~ zI@^c3er>3;&$6hKg3tkpu4UZHN!|36#!2;jy_J)FywxmY7ziqUh`$(f`%=P|~ zhSYJpJ*}+)%^mc#!0sElzGunbFG&A5_`~A5kueHAZM=rRP~#4Lfz#Lb0IlaV!wuUq zmO3dI)t??;tH+z}?|7QOec#bv+wRs;$NLWXdy3+Div0Zy#!FX2T724ecT*T<&oD?| zkIrm^{}}mG;hw^Cdjb66R)^``P9h!9`FN~18TXkC#6h5O8P-9?f_7NZ4{mQdGSK_( zrCyEyqjsGdzj6U>qKjF3p4wB2{ds+A{C%A}B&+ei>%HIN>Ct;=r)*Ffl)73a{$FSO zT1AiaG@7Z8ss6r(`g%}EsELmqYT`m!PoQ)%|_;u3N#668&1VANVPlRP|I( zyQ;kM?6G6VR@;C1M`z-bscU;GYs57@6OZ5-s5SypmJH3xA*=*w_7E=SgOQoO-la?vD6toB`N(P+pKI+wkqzsPpLinrLV?cPfdA4 ztuy`wESK`SzS_E=M=Fme5|^eVKAtQ9nuZgq_fl%IXTfB5Te}AAT@#?E!c(dZ$If^H zxUow(k@k}V7501u~luy#%t;hAeVTjb1BlyScpU3w!Kk zU8A?eeE;w;bnRWwKwE7;Sv%~EUIwMAu0Pphhk&=j-dkegO7{aJ@qsD+R^s21<%|+r zq70j1X8w#OYZHUgE5lI0f2WL*nG=^yFt3*_Zz!?#0;ooZOWX2a=tG4}SV?o=p!vmN zcv7ddqI;Z4Mm3W&nh-&C$l@G^O#zgt+lmta!`?4|_o1wQ*oekdZdSIAm~y;!jbkpu z)L|x2h5%(PRGo!{=^QjA$eC^t`OPb;z>rXHFUz3|c)l!D(D!@*t!fh5Y7f&=4 zaTheYdO6E5gKM*pX$26*3qtZii*;3CHpokL*@s+Y$wm4OL1znG?^zOqeuXZ-2yHPq zkyV}i6572$X01kY2^xQhWF3;rki4Fk=X3ymz;E&$|Uw6@Q%r;Bi%G9(*%W5O6=dQM)3n3HS1C1-H2Z459? z3z?YX%v)+*W;MavPZR_v+~?9%=FBUE^~{(C;^kH=bj{ecT9-pNvp^7Y&}62q%r@UT zMi?uUgRz_e8pw9$ncz%YQd-WuZ|Y^?GgEq2D+D$cVzJrbsW9r47)CKe=do&tpY|`q z)5Q1YKHy{Fn@=&wWXqQ*$)L_lfF?ErT0yvylMSuDHz5k4prA0|Z)B{|6VZwn7I=-* zVKJT#2I5UZ)+0Zb=e{XUaAnDPrdfH1OmoH!ER##+_Gagq=f&Nxh!**YO>%p5dqece zhX+<2sup(~6sMfa8rZc_e&oozVz%rOBd)_6MC(DZ!zGSAD7LzqMZ0_uxXtpT1Eq)L zGw0>!#9gi}Vqm2><+IWbaihy*hcGFA{WXbwfz?w&$O=d%uv)Igksl*xQl*}Er;tm5 zZJkM7eoBDF9dP81?j(lD>JCescp=H$a#)&3&bU*NZ9FV-f}YcCm1O0^9rmvG~yjmZ6hs*OCgJFf16nzzIBH2DA3C&`!h;l1$Jv@dtzg+xQ7} z|CwTaN?neiWki;06-=@n)zuBF9UWRY;tvHK#RWx6Er?aMDNDk>-{SX4aQF$<58 z&jDgxcR|6TNJnrsGY(l{@{ASMN5D&AZBd&0nM!>hp`L4nTk`L+3UTe!8L7b51APt&RP;5Qw>-;#)@Sz{fZKs&Sn zEy%)Jq&?8aLhVq2&BDm^&ST#B%)5Yj7vi*6)zqx5S?ZV`$zrRumQZ-N!xIREyq-3k z`X-M*p!rg(13jf;MP=2Ucd5>mtEyM8S-Wn1O>JF$!v@#JO`b-tPit!4?%%O9&=L%_ z-V=_rwRi05+W6vEkHgDVwH{LXUf}wEpEfXhAp5mB#>uuAf&zL!D_MF@2<`)!VNV;6DRq!>+ zFq6bee{1yHS)hLmxNULokOiRL2lW8d z$Dv}@gT7}%#iGCM0n6w>VVZ;82B=u{6b0~@PC;G)LX__zn#W4!BVxtazK;%$2P=Fs z&WjwAQEfVUGW#`g$ROc*dWOcAC5 zLcv4BOu})L41dBfDjW~G`6XN+s z`cc9k65_uF5UwZ0{0QaC3GvSc(zg&ormEAhcXR~M5ziXzk2*rBj%Y#&U&$yZ zl&Xm)lvJV#b$j^4SBLh1x;@fpk2KmLO{m)=jrJ(-1cdu?E20^;Jo1r7%mms&G@=YN zJ|_n@+*#bvP%w)^nrGM=(L*H1^N|A^a~o7Fcr~E@dZMF9!zSh5jqsBUo&lZ*%^-R) zAQlkma-Dz%V$^w@cBIjZ(&+JNG(7q`dz>eHMzXl|_qW^a*23XXm_fDyulOcFqP0$c z8*>|(3V*-5TlAN2l1(pqH+&hzS9i6$06*WNk&!1DjCl;c+EYqVZG6Sog1&jIN;N*X I6=6*O2dx|hNdN!< literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o new file mode 100644 index 0000000000000000000000000000000000000000..95cafce09a37ec95b3491ba4ad84dda6500855e6 GIT binary patch literal 217144 zcmeFa33wF6_BUKT(@AC^VUiHSAW2Uk3?e}#5(5aBL_iY4zAr+;CWjjk6t0;mZZh)W{FrpwXC<^cIoT{4X?!@^u6&GSrm)%l%s z>eQ*KQ`OZyJ@5Z^{A`>MhF9Q#FP-y25E=O5QxD&Lv7D^-u7 zh*DD0p?^WID8a96PsOziPml%@rrAk3rW0_xc%!8`_xxR73MsStg^(|BSlsd6X>C<_f ztF>?Jwc|$-&!6eLK2d7W`W}aUN>TOtCX8SKx4y#{%lci@Lh5VZQs!TQzHZd%{=~lP zCr@I~t*>~5l=uJ4uy|^W%*z}ftF=!xN0s{a87SGyYDo<*mdbn+(ObM~o;L zHEqPGvdJZrhYc?&arWmeqb2)~HKe{q6C!@InHWvV@iAh;u(2iMX_&b6ZJH$Yjfs&m z88^y)GOdpXjOz;U(;z)U$OMPxbiC6X|iYJu*t*h_H`)e zQxJj0?3<)~sUjV`McP-G9YDQT(RZ=oy!nko0#%nU#*P&0x5t7v(Wh!Ugtu5`- zoZO!s`VK1l@)b+|To1>(MX=AVS8FIK88=}hqRX|DORkLK730t%YMde!y7b|8} zrgUHS+g-}PN2y)P4^?ZKL|djTVrEquSvl>$&PuY#W#!Bzy8rxFICAC^w|$TQ zciH#2+rG&7`|t4ICZ~NB93%?opPQV>K;ib7-_Z$ZaCQYT**#C7V3zup@2p@C4or9sjTS$=F31Og>S-e&I51AQaK zdRa%*XnT7ZSKIr@osPKb?OHL*S2TCKPy1{BrdhMHf97cRDJ$SZQTdj_iklLtc@m^r zr4zv=641)qCl*#1nc4uj0@*}=`Ec5t1%^5Sdo7&@N$05@NAgSjt+ramf=`9 zcl&8pHg8j4{u~fki)U7;)G~MbiOONBFp6FFNvC|X0-RA@*Fm2#DM%?eN`{+bX_&~1 zD$GWO71Mk$pi~<$?*+_LY=D>*#|Bi!SK%w7sp1zFIk%~B#A%+}IEx7nqijmNnyZ=i z8r*x1r$q?qM&=oN19c}Qx2@~^pPh1Sg)yt9cEjmvEYa;%P#)X0e3nmn4k8`k|GAq^ zXpwx%l@^xIFM}-`ebHjK7cPE@Xu8{O+@UcVSZaB(ZSERS(QO8!d%wO2$u8wDEFp^O zV&!vRapX23$Mq_lyV+N`SoUSr52^3TiM(q?P9w>+cqRt0yJI^e0z-49ZvH`N2FSzErQRB)M5+P4?v@8Uldey zN}PMzGi7K|MF|3iT+U#$&3l$wP37TRS=$O3FDm@m=L+Y)J-Jq4MYb*!XWe-7Hcg%^ z^?C#I`(n^k`sbcT@;NfYRm>0nC&dKjy#R44>ezQk{M8M83>!rerGHs?84IP-JI1UU zMHSsK{N6lWiE$a=m_7H+(!vUVVfjA_=N>|I{LPq>0Xm{%QO!AD&PFZg{7T2`YhV@` zTvTzhud-Cv+ci*hqy5SBU0no}!{^xBXtN@OXnO#p@iqUmz`T|)U-ygon*z7@p?rn6 zu%hr>U_EU7^$l1TnEwb=bg3w-+cEpAg1I*%@b@5FBk|l8L8^qwEnVk-d_}TqR6y?K=OsQ?6_I6w$SO6k^}ai5_xxCmH$RY*a21_2r3!#*z)Sj^EsJ2OZ8ettvu;ep zm1Et`o;$};Y#U}PM6pQtIkpXAdZkVw&bv{I_~=e zHLrGwa!FO@o52i=D$mCOEk^Mbkw^xz%4D{cr#5X87N0TzN(=Su7J-%Jkrm*-9z(Bk z2Diy=v>E?){G4(#by;K9NIhsOMM(q?|DKv@r_}#ewtm|AndM zTR8OpkH-4i*cpwFQe>kwrHaPUh`SkH(*cVkoGns6X2YrvqSZv)UjI(Sy;Mcqd|7lP z*jHX`v*|Ak#Z}g`w4$;(A<=$O|z9w2nozaFE%5I~sQ>KNFb0 z17)&uW7ai=6~%JZcJ18LW?t8;7qKtv zdYFOvgL#qm7dy%erOHt?B94M7e^!>!sY1xYM0b8n1uD5N=xd7l&`v^UdYzw*DWmPt*e5$v#>%y zsGh~kYMO~+tEgA&p#OA@-7)((6=Txsor^gk`+4;Gzl!Fnt8mxq{X146SMQN6G(?gr zn%X(U56oMP5yHLdO6>CSMZMHgWye*LZF?n>@E@!i<@I6ZlIT38 zI^(hNYOXpq4p%L5UiiN_UA>2W>+0vWYAz6-12ZhDr0J^4tdzyJIxY|@F~a1vfviVl ze*1T?9C+{ef4d**nS!;|RoIVX5LDS6og7d*qqqpd z25)p*_Ad+8S65fCUTr@QP&<)A==+qf8baGJc|ctmeSCV}#-(qSE!LuPE4s@nw@f3u ztdX4qx3i!w^gwQX?PhyCVbFYC>McjR7WbiCV_pb|qbP#Xdj6tz^Q z`XOA+^0Wbps-C%;@oth`<=ZM7;ee}q=Z0%Q+G8Kn|GTYJZE0jTpighy3)?aX(KEnC&ZCbSeLheJAhe_@p1z2rro1w$ZuC{;uU4Xc1d^e!;c{YmhJsaKoXX ze8D=Td56BJe8J;L>)i?51Jc{f$3Twmu1l}7dHu*VRoLdDiUo3&+&(Bt6}=O2Z+!l4 z+O)kySBq}KlW+cd z1dnwo|4!eE>{32T&RLittJ_a2(_${1;);||#SGbjd{B>yt`!>=MNNp@4AIKEEbh4J zRjk&i`A}1Bj9mk+Nm5ibUm~?y)XsB^F7wckn^@B?=XOP1l#>L4n{q z8Mo4S-G&+Z+%DKSK>OO(=h}4KH6^)l&KBy8wmnSN#pBvJj}O$wNX+i$%63e%-KJ^g zWVY9(GLe{-t(92DV}sbWhp4YCZNm{y$n@@kyDmi)56IAfJ#t(&R!j@x)`@!9q%hF& zq_)1GB6jX+goc9hg)hQemFWfB7Op`8p&=GD85yp`#l*tL$(eMKSH+QVUg6v=J`8Bw zY3D#e1DS4N2cy@^GY{(B!-{*UB-Iq|fh7CRL51#v-r!($_r4=Es6nc{qVqa#R9ACH zt;rAnAE-IsnAdkX108qqn&f)!1%FBH)dK_0;q>3t3%XXkO#NS8ovO*Gd~=1@(b>~< zXRq+8zK(|)bYDk(R4+X6|9tQM)4`+zMC819rW!o|^2kw-2FQ_n&-eQIWeRunw0a($ z@acswlPKe9j^u6k;nBl{6fdPcnZhvl-Xp}=VL~L-Hw+_&;DowJ#rB#+qH!yU5HviA z0>ty7MFGAC0PG>q0^qM`0LZr=`3qKq)_`bd#}cg#@(YO8FiKm6{MSUwjM9EZzQg^X zHHy;uA^#B3!cp2w$XjusH8BjYD&r(*$q#_mlxY27x$wQVR)|mVO=uROi5f?Mcsj8o z&fWz_ctbU5Tlr0FqmVO<_$0XHL*%@ZJ()gFJUw@Rh_drMnTg&QlJPcxEwS~bcl=m6 zc^fP5kV_SiPzOK@0^1zUfFC0g372Ug-vRhrUI#l8Mgd(!VjbhDfQXoHIfy$5C^ig_ zEJXQyC#c5>=@UUjt)D?ix*NnHu+0O&W?QW~04^bLEI_Xl^tA%8fWRBbZ5iasgw`K| zhOf7I9I2aTjlkw2gES0kTcB#qJhqmgf7Buzn{^<9H} zb0cXc^8IFl|61f*86r81Oal--y^Q2GNOz-jf1~!GFNK(guO|s!PFeI5r;Z;-b?dam zaC)AG)Q^BtevEKVQ80bUiQ3tI52k0?ojSvWC zyR=u)^L*w+k9Q?Dd&#ru*WL+WD%#eF{bM2og`_NrQv4ojJ!>);A4vi8T^`-3SU|$* zZ;_t0Q7K`)2TCK9XTIi1K&_%BSlOT+hzGJ&A>P;|>Zc;`3Z8r}twj%Gl?w4P*hE@4 zsPUN_jHHIB0x2>t_rP**=*#7Bax(H;pxTK2j;*&6RtPbIbnh|hs!~re5^4+NM&dWw zO35D@3+n4cjki-D2Gw61)KnYQ`V!QBL=AeJx~;k^g;+&MeK%4JWH%v}3kgjJlAHph zQM3$y&9UU`=K&2SsHuktR6SXVj4?!Q4FRvJv7cNb(wTl4(WN8&r%`DUItE4DXl>k( zl>)y~05sd`M&RHf^+g&YbnH3Q`FXJYLS7C~09cDquS#h;34SUWMnz2r(=lTFof)Ym zKfx06&n2wD3qo|n*EBpd_8`_Es#=6bVidiAulWy$LRB&i6#r` zb*NWc9Wg{J1CY)4>6Ut#dV#-p8;H?CSd%o*6)v7)QZ0E_gXf?4nq6Ex5k3Bq7?8sH z9!&LSfw70L@G{wA(E^2)4v67iE||&^RyN@ABt6ha>QLWUyYxIjTL>QNlICG=eE}%$ zX27M@7%8lpfLakeyjnO9&?JJdt`?pJh?QUCf~Dol0JHKj)xu8z-qRh*$GYGotO5L8 zdf+gW4(!gRl#=coJzI#pZjhVolA{{?uk585{Ujnnr@%cR1KiVnQP(jig-Cz9JO{fq zV~!B(@HOYVl)pU$+N}2hrQ8B|K{c@I7a`#Nh-YCnJi;0YXcfVWTn#2mco@)Df|vN- zN0AYmg>}z-AvWS`-sML2fO?XU`<*Iz6RC55Xj4JBn{NjeSy5@qdCSVldqA#YsCK~_wZQ&){rthg6S9^ zq(Fq81N05S+iWdJkn;B#U>7d}zSE~dg&H6%ZuJ7h@GcE=v3{xiL7*Rz@TYF&q)S*o z1G}&s_!lk*QYRHwTR_tZ-d`Tz|U~dwh5Bw5wO|+7#uIsX@WKf!b4s;Y(*#&tQ*om9Yj>gW_1E_9KPmYRk&hTEq4o` z*9g8!Im-cyw4Ylz%~HBW~Uh4cP&_I2x}0i6A9_+My7#!2O+)O z$eo}*Lr8x&vK~~r0b~wwBl|!-NyrE{@*AkB9w67akp`f)CS;r&DFAg4A(Pz52vBDd za)TS8oA~s*M0184c>+{=AijUl*V(H&P$e973LTBke%#PsmGdWEiNk z33=U(+z#qVbMWA$#0NFHk2C@`)R{3DkQCIp9Vf z2Xz}EU%Qb#p#DHer5h0#Hx|C;NjH)OYB3?dxRF7i-blzFZloO4wS;(MU1M$?sQ(}& zCiY8=Pzq^kG>$40Vivw;Z0xj-4rC#yYY2&p)yoql^8~1G6XJ6t`#?QOh(GplhC|zL zpr%X&QX_VLp#!l%ZAnPY*zEoed!86t@q~ zfEv6BNS)Z>2)H&MGy?SsLQ-RIq!<hvo))Y2m8mKD>3C8YlYI^|Gt%THf zTAl2MmbfR@3EUX65&okpfg?goI6O=Ck z<5T74hG@75T72df-qIk^{ZzQOZ4f+s<$VLqv z0_GhFylE5{p=3~o6ZO(4)qg7r7mZ#dve_mvJRb=Wz7I!3g#Llk4}@H16F5lq4JD7l z&m8bI+uNXT87c$$A%Y64KpQ~bPf)igBtqYU(&TDTdq=6fi6TO+L1t)x4LTjI=v3gV zNpz?U=Rs;c5AtUOjZD%VXA&9-)jA1ktIzY)~RYy+B?>&@>yAMv(O;$X^k(AY!NNczpR7 z`Uz0_wSaGnN(!q5D8q=lB8k`{T~ee|95U|)uUB?bMY$(R@$W<>MfywNLVAnqpMe$vKWP$7pvJ%0?4HPLeXKCB%4 zP1r4afn`94`JfFah?ztv7uYz$AF|;rPX`gAu(F2mhi&*y5D*Dx`_XmG?SUi{2{P3D zAV8B|(nUJI8+o5Msk6@SK|ax&RHE}AA|Lc7P0;y|kk9a@lVbDj0Qr0h)MB={1C&>Z z`i}q=WJBHt^(-OpxRH7Ym7VZ4-*qE{L7hj)PB*d~)V~w*o(mC;udj)68?U2dT4AYL zbsWG>1xGM6e~P(TPs92K5}PF7&hPLWQac_fFJZ z1irHLs$&+k=v4<{RaYHnFm)RuVclS~5JmFHszb1qzK;P!R~?G`42W{oK}yNlk~<;o zD!uA(0#-W!Y;cA_^@E7Lvg0+H=|s7*j#UR6;OA;uU9^kxlvEWb$W_PVu+}g~r&x7S z!HcPqQ&J9RNV{Jp`$cGSEo{BuYu=PXwUJb74Jd5%9Vw0$+5jPc`%D~oFDE+0zYX`u3I<1rh5=nhcNQdfD}Mzz+0`g&_n z*QKasjyC))AYb8YzMP_GQm&HRRSEqF=)!@3H$>Gjq%IZO0h>tpwiLY}v5PMUw4LCc zZgJukp(DV8gMfc-!{v<766CQ29ZJzNf@*;~K>do4V>ThVmzaq5%f;6eb!2V4vYu*> zs578j2sY}dplF9h+HkZYUjfjQ2JW%=BDcTwG?u5_(q)F~8M1rw!wJ?gjZSo;a-X}o z?j;Kqs=6WHrHkBEOD8kT1!!t7)96N7ESD~Czlnw`P>LR_BwKZ?-pj@&v_ltmj#Uc4 zhVWenAUakR_X-f@SS6*@)g*VqMgZ~(!3kK$0I0D_^@oVv8TGU?G7SgH&Tx!XHbB$6e5tb4zrXs4%Fp@40a)+;cAS0-EPOh zUA5i5oj}c#&^K{rihkwvP z$_(g@a_}|V*ktJG4uu~87LV1kd1VwAp%5s~5Vd!d>fcLRYk;3cc|TuRm%*`o2R}Qmc~c+ z(L;9y)a~>U@#McBs1HiVUv@F%_?~U(&X8gnWn-eb$iI^g#3@1_fN4Mm3>s}?;#;-! zV2hs*q)y%0O(_!MCw$FvH@mCFS*8q4ECsFQ=w*BZc}2XQTcp)oR`dpPR3x3MZQh4+ zyt0BqG&Hbw(xdqoRHEu=-ZYkaX2Sbv?$NxJ0pCvmqN7=H2eIgpqnVVFMVT3)Cz^dbp8XP9 z=8r|iWT>X{)ztqUI8PFHxr;k;^DinQtdu0&62RBI-Nl^~(cN07gmpPMONskVz1htE z7gonQ>K@9yZsUgonTM~r#*M51bvGfWW3NIH)c))We;IP(`~??aL6%A#@1fY5C&2e6 z>PSl!qe&9T<|DD{K|x}S9Yz{NItiGM#o{SEMY*656yAP%miY1bkEaU%3*h%ke*e`} zc4!8K_>%KQHzXSUKt-4ZvEgTsFv1&g6yXnu7(PfxVV%M0{JKb@?t{nxz@c?> zmL3F+CJ~S6j|;a&LWDcxXoQF2=)tBQPFwIbQ=B^f27~=k9o8Q3)IAS;^__gw5_Z1E z;OS0$;Rqj3#xf}N1G1XXiz8@Dc*;*bLs(A$`HIjsadknZF|eNerr?uWxT90}brx<{ zUkUeg2}^h;;QR44`#E6|dIr=)gfnwN9QAxT>Szr5Ewrr&WdoZ@_#zw528ZqenQvH^ z6C_(jq_x2C=Y#hwR^k6s#zm z%l=Oo@U;SPdpsohhK}MM2%=mlkWv~Xk~`rB0CJ(=1gw<+)Ixz4To924^XkjmtkF!v zfgXl-=R$!E@RM?3HALlDXP%N$PGB@Z4_nY9yD=}cg!Lbx#K0B#^4ZT=sfC`u6QZ#n zYK%tna5T-|I+rDn);#UtJSA1FlSJBiDBCb+*e> z^YG&me9eUk^r$9PsxSK{G!)b=gxt>8dQA04bcoO%V5bRRX2YdYPd;|`@HJQJYf7!O zxB&4TUvrgBNcNfeAiqG+{cfSHpvGJQWUWnzgLfzy$#ZnROYU7*y0Bh9S|BpmUAylPA*ADcTM;8pby$v>b6Olu4BH~zE%I0wzg{8`5` z)b_^<^ekFj)=xVB3i2M2$c1z+93?_r)^|F8jPhod=P_mQH%2$>PtB}pI&V-ukVU_v<^4$y2&PZ`OL9Hz{vs zeW3F(GJj0xV<{h#<$FTu^HKf{BP&%C{6v^-WHr@<8bp|DWVO_UnnYM+WOdMl1R}&_ z4bu5ql=n8f4*4%;pywr0-lWhr8>9{Rn#n}s4v%;YLc)_E){YV_3xt70te2_+oBt4W z32O|9_Yq*FQeP)E5?Bl3KL}`;nm}V8fDGz;Ks-Z0H%Uo z0hhRdRUqyppk+jrEaPhs)BXmaZE8a~#mX_sXs8L05rh_S4SAqat(1Y206jr)p+i`N z)`NJGfUZ$FQZGUVhA-cG=^gQz{ZWv1fceJF;8b(NH(NWfOqXn`RRVN&v5Ce%9)b?s z>TRr6aI`DxUcu#&vDkeIt7Sr&q3%k_g(`2PS~a0Tt>7GJV+aeYr$!elS+zLfhmAR6 z(tU&cht!U&?82?g5%Qt+wl;ENGCJZ3Xh_!4VOK^gFz*-GJEfUGa5V8CFU5#cM4wU`vSR}FmYE$BN-G+Hes!BUh4~ZH5BI^B- zqZy=@D~7|3F}tU0xW-k=dlHTrOmH=q6%yvliWu6WmC9+ylG{+iyh4jv0Rtqge~=a{ zVZNCs(k65Js0(LqAoc6Q+L?|E=jPlP*5#mbD@8AyFJ&Y&7KrV_S@MVO1=V)ptf(J= zYP)b&x@+P7iR;&eQn%F}i0i^xAya|4E}WG;4+F7XICB~5!uc~mt_x==jOuwtP>g$gwaB^rRRu)1q>p^{a0bf5|ZuE>`cd)6rgw+r{8s|?aba2TQP#7jMq zPKK&rK~mh&*gik25)G-J>XA;Qsv})+brSmJx<`5p1HM@Rq9a{#KMbNA>7_M)&U*5f7VNN*;;&MN1s#k>8yN3;KJ5 zNmvhpXAi#SACZOn0FsvX(r7xDjG=vC@*{4TXR!`9VkMK@m`eh=8A0b*ieP0y4yXeN ziL0T4rADp+wStfYH*ycCZxK?v1{H79wii@!0g#{@Nd>h9A?Y>L>PeT=4%C5!G<3@h z2X!GKO=_r#Q_HLZ^$kLr)@XHw!-7~e8gDvh)lgkY#`kn;P4i;3n^$^9gqnlGyP(a9 zs&_%(&Y?%UR(X@&g?@60`IHxp?@js)`MmbX{|$LO+BF}HoPQd5JleGyd3v7LdNS0H=+6&g-iG8hCH_Fel!}u>1;!=FgN4+FO z$`n!v>Qq7=b0Za?ZX)DyepK8h^Es%05b}geMl_s=;&lWVg0ibdfJ1CiLaP?;2ylb} zUkQL{1W?>_L6i}Il#(fuJK+%kG6FaOYbyX10aT6UAfpU^?x@jB!+|~v?aoa=Ho#BH z@iYV~$2#+rl!^e120C<*t3i=g6WR^)(>U*OkSGFJ@z{rC$g>G*wl2KTiEVMOJ~>g!L9Qu_?Rau9tGk6e_~p z&8DnnMWLghuqk`&rmO>%CqZ##)k$!TG~tg6l?i2r!vqo$R%>WrA5V0m3n7dfKN?-A zP}O#1tq4#<(Rx`l{03#{4oq0p4m=H1-0p4;e>fMbGa2yp0}$=NihDYUvI8sk#7gdj zy8*}!>;$Y=0jLg4^+QWYf6K}q(`csQK)JGxDU1#9b2Y73Q90FtrBoFs&|+1j-4DLV ztrYfxS`lVvIaY*AxyIHIP+cp+I~fVx2E?`^l>DJLK((z174;OTwiTh$o!zX;icspd zMgwuJ2o-WK5Z8)O+4D9K+lr9OP%Ag-w(N+HLJP)e{j?eCkAD&B$S976t;dK`9lSu+WLW_P6yT2 z50vg#Ky_UiNZr==KwSMmA&qb+z|{|wJ-vb0`T>`r`oUsAu6`he9Q{B_kV_m_29ms) z$f2!JWa|eu$T|r~^#f8t%ZQfOq1LP~I*~LUfhDJr)~qe{hMW9JNmv`wK8JZ9Z7zF5 zLFD-jAM<(TW{n58d`c>GxrP?lAP&``ks4ZPgLone-KwEQHi&1T&^kb$;%nX-g+%BO zD9NT-uAHSpHdeG(yZgPQ~i29rN z_~ovPf<;CKQST)IrAI!WAK5Gp-TRRc2k|xMk`>YI52^m4_0&c?J{F?Jz6ej``dIR; zMVnwsNWm3^o)VhCwyIOYm1MC<*xAlKB@{E@`x!uVN>JQsxY;A81X4=wklYD*0OXY5 z1gzlzxZ7kHbpI$aB~V6KD>a(wL@$AM=bDBM@RM?39n?~JN=kJ_MgzgFYFkJS3niT{PGM)9N)-tcYM2$nXC`B z`ZB|zURJg?G;rY)ohVn=Vk(OPctf9w1-PR0}*5v1_^2&@;_R7jf zN#|>Hq7&suNv+cwU8qoHP4tmbj<$_I0-upq(uu55G57db_)g8eG$ zRLp${kSpd&AxF%W666v`%$4NZP-zkR3W{to*9KYV!LKUjl8Q*oWqo{mdszZBx)Md>;@R_@k#@_s)S99pnhB8st7>V-h}s+1%kGKa4rZfG@7t9^@2v zE{HP7kx~kBk~?8I02$<*fOR_nHaNqe`nf9m4~=FzQLe0G-OC2}xtdl7?V>y-RmBO^ z_9AUFHHkUL7UU*_!q&{K<#0XUFi$6ba}kHOz3c?h*g{c8I+%~eC!YoW z8>QF9C#OunkNx0z^Y!?~sW=CY*BAU=5^(!WvqSbXv-r0e!Z`c!-}X~?DY@A1h`ARXTq=|sE}lFp_#A-t^*_1h0{ zG{T?b=m{Ue(Hs5=NA%tukZDM~=Ov^yFR=wB`mvD?N-tmK2udksP$sOeKy?MBdW?ip zhB$(f(0kDwZUzCoFA9mw+tTCR8Ter41<5hf?x0pxK)@2U=c0m!?A z-dhbS(k??cjm($y>wDcb-yG}cnhj7Cy5@JFy1Hg#Mncv&N7t16q3)pCx~8JiWwxzr zD&5;ab#+at+xi2Dt7|HR7A&s$QrR;Mh^=dK8LDgE3&_*M!0$e6i*3i%)JlX$g%)d_5(bb1zeSXY^$-Yg=ocSuB7 zqcu9wi4GtWt!Fg4P@yVzUrK0T!vH;j1=$YyJ_*9APGCiBOu|r{oD*0#27L2yx;-9} zN2vQM?#Dos6BsEaKyoK+M^;W?PQW?>fGe9}Q2iicuWa2(3e9w)Tv^8i#s>Jgn%0rY zN-9rDRdIrBjQ(V!`D2`yHX~^@VdaCu8+t#-(S;mU;4)$o>BMWE=AF3?Oc81CqL|27 zVkfG#X9=vftv!b`zf}RMYb=dsB=i~(+uBp|hrR*THkK5%!S#-@q;!{n>KaQ@x3v<8 zYb+_`Z6L0(r0n?xh;1x!8EPywN1a_`NeVf}l9b@au!ng`9*atg&}b;KjU^joEz`}{ z)+0O1pETc!8`W5%+rI9_;PcYyU*T4<8cXV3JhFT7onk8l4UA4S9O&I-qBTmR3l*yD zm`Z4XZavFQP`Vwh7lVXV9ZR>eF$vA4y2sKT4ETBih>j)2eLaYBERj;`ijq5F82~w! zoPhNl05z7Vevz>xD|=9*nT7-9$~wjp8{p?^S`TRl<|(NvPLN}%F|-@zG22*51ck>^ zWgP97Pz7${>ZTK~d7Q`6e5Q!BMeIX$9mh^oW9j@G9AoKW=C^u*>KaRrGZLBR^B zf9P3IZDUDMzXsJdFDcy(r&SqCQn%F~h-)k<olvX}pjVM~^xkuD7>H1IR zMMji*6{#FiB!VAFL4z7m4)g#SY7NrpLPMg;nl}gyT!m$`98ud*h8|IbRUJ{g*qDS{ z=DJ7JM-2EL0}vfiiu-L4<%lAs)FCBz!chQnL^%N~PFFU=p!!8dl&oy7Ml+o#SJpA2 z*Z@CQ)4EGbUcPT^ff)+RzFpzz(OsYF$Ga~sb@jf_T% zmVn#z`ohK?$c9sJ^n{z>=nc2U(G2&*F(y0;$Jp?VIL3vS;OGlKilaaLCXPn?T))3W)^uao`FOvrcAR7ez~Sz3@#n{ z*gf>P^8-fG^1JcMHd^yO#V^lFqL=I+&OrWe$m3@7eZcAc)aKL3Cwi^Nkmo(vhYb=V ze_sq3>*DW$>Z?G-cJWLwIv1j=8Sp&{AUf0)_q!moq(16 zk{Tl!20dj45!pce$eGnqqnS?hF=%&g7qbC=`Mh7=D@tdcl2SvRQQl*hJ+uM%A}dJ( z^;Ovt6l+^aKF2k-HiGJ!{nj%QItk>)WXQ`m)=U0SBY?KqPf>@0YMcF(?gv11tt6#x zYabBT?5B{x%T;DSWlug3+w8|>sM&7@AlK|Cg&eb=lwg0^XFo}P9TwqfStzp2em2PZ z3J}M=wjNRuxhiw}pPt*~t1@bA_q>+{B^dHQ>b5L1=wVP-|7h{5Druq<<^EyK)aXKm zR_O;c@5#qc7eKQ&djEw>m)%J;@B6V3lkqj*tEc*CGTrB)Em!mXdMWgW5P&FFWhefG z^zM3he@EkR&|!2^v#-}n{}4g-OX>;=-yEC3&(Wk4huNQ>o0+g5wd1}o(kBpkK$I-3 z`Jikf>eXJ7r)VYxC?}+zG5iWeNuCUCBD5V6+(y^AA?sT}{8Fm1UiJPJ_3EjFuh6Tm zMM>jG#`aPwtLN8vn+CpSiB~G7a7NHBkOaFXhUJ|7$HT?mt#@EbI&Ek zpVVk;-Dv(%D1>hks)8dC(QS-qRTr@ou?1D@75U#}f)o3`>@EkjSD=O2f{cKoiE zq>;!|4>B)D9*>Gm(D^*%@u=7gozF)eZGD^07a-rnoAd->ps3#Cw=|tzuBGBV?}|xdGI>3Hi#6JO=8UgdDG} zAApl3TW^E*DiDos0)by zyeL)Oj$aD$dV(6bA!`T7zYuhhez%mL`hW-}BKBod{L3MaY8SFoTSh5<{-d2x9vHc6 zw{k;Pe?T0LTB`!|JMyjrz+L+?lCgK~#_eE`A%b*2JV-xot>4!`m^Ff#@Iwpwp+Jyc z=5fL()JW5Bm9jtbUu;uY*&ZPmiK;QI`+WO96tr ziREJ)>SqQ}o)IKGc$BD|qSy5V;~L{Y56%Y-EDT$4ivDpXhkgaJH4))5RDV5Aah@Rk zWF_Z99O9D@YeMzU5^4mggdmrC$%Qbi5DYC|Ln_Dz%I0#4UiuKEL+*9N!dd#!eUM(+ zAP@5hpwff4Q;LCAl%kg=1o=SOAh*GD1dvVAd`9WP-QYh6;1o4pkbdVJ+)p%0Rv>*+qU;{!am77JWQ*A-x17&kLMT0AN zMLrJQh=o%u%PHEGtnWijOkZ$3;q=^HkPq}cTJRR4Q7ZQ~O2u>njSrN~mCne~q zr`#8bFQEuDK2SE7QaRKdx1oA9tl&Q4p`wF)$ZL<(w?yLMX(PO_zfl0BT;`4S_iLVvShgd=@uM1=PBQR+G3;{#=LIYsXW57J$jU>>n>iVt+}BiNg0l*%1K zsXvI150uU26x|RC($;fuHnDJu545ElTtPHS<=#)JBI4r%Wpg=2``mJ-qV2ZeHsa$H zA821I_$kpSmHQQ?VoO1zZKEJhA2gBVa_SHqnj1F>ES#c4kh9d!g7m*%xnV-rk^;&G zDI4VM*kM516Ur$%1SuOtKo-HPkjfd2!@9Njo%@%GkK#1D)(USDy+DUrtkz0epBqW% zJ%C?If{*j~SHCBaZ-2eY<6r&OBi~QwGmNB-$PcIdosiErk_JHWMKh4U3;9AL={n@E zr2H!6dl*T#B0qxicOyT*5IMi2u+>mf>#fVoTCaygNQ&@9I2z$garA`qarB0Za5Tex zaf}HM!!b5I8ppWs1RQ{L_%fKN$Xu zJS{eAO-H_!k@P$AG%z?1U&XCa`Ur=w>e%xGjHFEDf19HCuYoU-XM2dh4F8yD&rddz zZnVo!!#^k@|N2yx_hv3KjHE9?2;86uJ3zSPAvk-wCU}gbJ3tseO%ayhUmhO-f$Kay z#+$hcglFx9$3fU=C%gi}PCH=-2%p*s`#?Af!gO8iQ4rD|MqA37dNW^%G4c}Oqonge z<-SSvMSEl+AE`h7A2lf(gpahI9Wh2yiJhsW=p)Ed1m z;@35(Oz<4)A0*Rq0yqq(rs|bH5U2b=pZI1tF9A8wmpl<4hb&14`ccP>*BvL&pZ;kx zzBN$tQ(yr7v1WXM&JOfsHZ$T2k)>W37(|^kzF21m*h{Pnay~$E8rN}uC^z+eMYVA%;!)bP{cRbNy`Y!zmr7Z+e9tTJO(J=Lk?r^c9h4k{1v#5ddyDb zOO2#jFpQg$@))Km$n!9#{51IR0E}4&p<1sZ#62JW2K5!;-*Gg;F(7-wwQ%%?&%@CS zhjEMvUyNgHxFwEp;f^@^!d-FnhX>$TBRm4fn&ELc#)l{4m=Kig7uJY>CeCsJq^ChX^!MvfPsZM zZIGOVWU`fWC6WV>Oq`sbhtrP4A<>>TG}6EEG`JB-H9U49sfGuIxtxPI^n+yWQ2jid;(TpL zhnk~u&H_zBe5kcIF$SkqwGNn3{~yHmhTZ>^xBH*+cK=h}?tjYL{ZDzj|0!?xKjqQK zm%+>oidSDEUy5Y_^4zBnA&)-34*8dF1b!I#G9xboiKN#-q`%K$B8=W*&%@~V?0Fdd z3G%Fzlmrpa4}-uX?Xc<1#8X^JKiCN?a1$!I8T8)=YOMiAFdONX{&qOZU#tcxjt9w| zIlVx91kMc1&l!T`JxHclIoBY$5Xr=;!Es0yOhH;?B#w^ulWVxqvq66Z42jorqf>x7 zK-n?mYY}_`>HGoU2`09VFTj}|UQ4`;MT?Q8xgoI)i}uu-+OjCewkv3D@_k6;`~p4A zF%JY5<#@0pYJ_CnIXMYP29Zq7&IuyvMY2xEoJ=H-L0O#+ysxnr$(olWUj}L^7-}^& zf_X@{l>eBW+zaXHM9(sU{UdbgrTolmn z z^{3U3lNZ(Tb$CZ-7S}O4eu~T-NERT8{{aAz{xWgyv2j{kK%s{X>+OsDFV|ku;Xg3X~TNaKMu3Op`QV_ zcoy*Cs7_gwl?O7tsjJ@681*yzSe6u4DG<7URqs1zk;0k*gnouy@5dP02O;ZaY3w~3 zed_nxZ)rvm>twX?`~;rP>!7Tb;_)hFe9h?6D1w90Ai1=c5&R4_Z^2ngb?5;dKOkY= zQODbYp3uB<1SsS1HELpzt4}L+Hu`m%^CLlg5lY0u&Nxg2yJi_2VZHKZa2Blw|LE_i zx_vu;Q;ATk@M6t(ap(KLiIO`gvbRC;3)PVE-`ri^t)5PTY|SmO<|?HICh*7T_o3UG zu8lz{RXE(kAEWshP^%bSs^AIgY)GRu`5Hx5M!U({=xXRJ*ljtv`x2x3WMpSE2~Xh0 z$b``^^-*$p4z+2Irzx3Bce=bwcg*5HK{r~{zEIC@JX(NW-svSU$$wPGND`f*|EfL^ z*&flqQ}-@CIICCmkJfXkK-L3&!pO7f`5FY9p0|*7=s9iI^8iq(rxXbz-=?P4!_ADVi1vWh|JN2w^>v`O+XJSOpCem|-O-}}bkTGl<9$XE%-tR{72R3>i#cqC|+U1`%dIwGaI#qOe1At~6sDTry zD6RXqIOtw+M=TkD+VtymjJibUv)H4mloFjj=-)o{yM*ij=e&4s^@g) z>e`t`K^1ay9;%xBu;!M%UX$-rWYz24WZmnlp|j~->!7OIkT-P^-EW$UmnMV&8Pic6 z(Rn;#hDI%2>+YQ!AP9V_gpw55+r7Bn?A<;qZDN8YW28f9xDG2 zK*oKjymZ4xa)ao;2!|z#u|W+YflIai3~K#Dk=CCnAQ|LZUbpIyS5NRI0PN zAvmZp=!c1+1rpm7uv0T^3l3}z`X(@l;!z)BLRH8?&9OZ=@CMLh;pRbek?4X%@n#$6 z$C|TQ>cHKgUjT-_`;nl}-~+I4WSq>5RcCWY-J}Jm#WAYI1h9+Z38V05EebA+vJJc) z^p~i_95iAThTZiBUIzLyD)CAr&Cb(nhWsh5 zzD>a^qULOmSbZj9wT87eRF17KfH7=!6$WLs1%`;#Y#9BeAAK6CvvG$sY$0)yVFtT1 zRl$}zqr}pM+MQ3557?a=*4ngTG>qA>Dh$f7omC9WRVDS+hAo$d)kf2^VIDTDNWnd$ zhW#2bESI_o8>V5cO&c}?9Bfz>24&blDo(fa02=W$-xv=KU4#V+t&47=bx}>Umu&gf z#$%%}b1%&wOx^3OvdZHpA7hl=Z`=hzUYk5af?yoNPr{V)gAW%$51Zo_#FH{ZsoQB& zy5xR@yXH#k1L|xJuZtjaAIfQ{g3HwbE;bTmKA<4e6NShrX15&j`&5uQDTBlI5B^II0MORDfva^9vyEgU!Zui1Rm=;5!QEA zX7$vu@1wQl=tMUGGB&{~Igm=p!5=vX5=SM0h|!fsQ$Hm?T(3e4Q;6x;1kr*@+i3=!Ej>H5c=)*C17u9yJv$hmA`jt^_$!lv>2~TLVKmP1i z?X{Ok75jw#wT(V+N4Sg%yHECkvl^dhc2QG`8y~YzzEoN?+2NA{^f&g2n@juTxJz35 zWFZ9ECuhhNy_7aO?gO#&2}G=AE-vq--02d)V@!;w?#@q!s0QpE z+zkJI3UCU^iYpFrn?A!|b`k1+PwUA;v|{9_qVbK2&p6co4tpb#Ywc~1 zHIN*_m#7lDsk3o1I)q7?T}aO4?G?rFH*}xq}vuNe6A>0HSxWiQ8b9R^* z@VPt82%6$)eUGi3D{##kwfbdn+vj*%jq@b`t1|cxb;cw=1Cr56o;dBZ{HI`K``nV4 z<>fPnGQ_xS<2k>i7R14j;%K?GW4w9pD!)C z^7|pZOLxs0!qa}PLGykXT88k&MK^;c{vLIZ=c|jJ2F?5nkk96szZL(&Ae*QD)&|Y} z*?g_h$=HFx(XR}?98A;LQneOYsn;ag#=}eP4!)VHH1f(y>;{wnvkiN|@h;^hKq7@% z3On~GEstt#ml!7<+8%;7dnbd-X$_$HKZ(lmg!h`tYr12?s|k=NJU5q~@V2?6G2zJw zwvd0A(GzfK2a3oG4f;{SR@gSAi1PQQQvN9AY0Y8Y$8SEqNU0l1HC;!}xWtHd#K}PI zHIp-7k3`w*{nZ&`!n54&-X}>Z4zmtu%B_NC0?jldB}!X-Vf&rVaSyQl`CP=&2c0@*?ZgNOI2uT^rMktnXQPxKttXo`#cmxNAHPmUlI{Kmv`X4Ao`_vg7>=%c^BUCmA zea-TDl+_*|F07;aVii7TU#tN>cVFZ+(=M`cs4?|!yVKqPw;XD6UnH_-T8LJoPlY;T z&9n}Zf4*iqpzU)@{tIiSMYkxTTuKDK?oEFRlxe*Hej*0c;O?YCTnk3vurMVWlNo zYg=Lz+-uj?3)<}cAKiu4Q<{HtRE}raLY3Ea$1M9gbnz_f=F+olAD6UimNkOTS#}Ea z*=N~Rl()^Y`;n&)52o4Vj3u^N_A1h5n`Ijz&$H}0aAHIiVMi@GCocmkXW4@iwvVE- z0C|>8gkN2=><(bAk;Aj>PpYo<(c9>QS@v~ZBG0lp^-vqzEPEsJJj%dsXJe`H{A#CvSysdA(ggkw?Z*C&LEw%N{76?rCzIg`R+&5292isBi z>-+64yOzQjuK=54cgnTeI0KOTW*K45sQx@KSKk~#n_26KbwjZD0aXh3#|~-E{?J8%6qgI6pkfWF zGukWokiBVtg_vww&7!rtnl=x<=ccW~=WNyoKA+05)fcxBWMKVGNzhzGA7i~y^I?0HPe4)zRxiyE_#~<`SaTh$wKJTB zcx6Lq{-#kmhberW6jESgb%sBeJCqkexpci|(fVAjzXOcy`YL=**N-J@U89QEris`D zHMSYakJ#N{HTaXY=_ktIFVq=p(=L$w^R;OKG_ied$$w#OdbbMy52>?Uo9=^W^qO=s zH5Wd5ZTbzbO-E|$jY_pPJv~eA=bce&Q|vkN+Vgi_dyWia4D;Ia9Irj^L0+ysf3U4R zPuceGem0KMdUG~>$BW1wi1~=!RIq|Hoi9&thM`m53IKL6!?u6 zk($32%@+7TjwkBxl^#uZOw?@~LYnT(xw-U2O%on{w6trYz6J93iTY>QW}m3*0k==o z^aoY+krOpJ<9l29Sqs!&GZ}tvQ5CvXozb!HderWa&qyg>pJ|rcqpbFoWrIxB$Exr- z$G};#!!-uD`A$fS?bD=pDJ{vkK4oY^;|E)PI-opzedJ7eMj7X&2@xOEXY^zC`rHUH zSs%?37iG2AXOpf^6+UNuR+AmB`tVE{P|vvJBkQ@+$l&6G`CZ1$P*a71@CGi4WO zs5(<-DRmdCvup3;0tne>%4Nv&Oj$+FIa9`huezBs&t<)9rkvmsqlnKl<+VzV7cL+g zXKYQokECofhwQ2|l*l|?vmJG>c*5SaXCNkWno#Z#s&nf7g?p*ZGJ=HcjC8T&m89*1th88m+MywBLL=rLA)d{tLnSHdV$lb(Xx=|(|-~k20S0ObMUS0p_?a0U(r1UQkwfA8a4Q6sUS<;KvMj$ z=y~edtbMbxSxY)=>9-~U1t;RrpKtUu^8A5-jq3Ja^b>S7_KdiOo*7#;D|;E`8+hmk zx!H6fX*Bd4&Oq_Q4r0+x&Tiz9u6>A~UZGu@;w%UkAtchLt2)P=mBl^MLvX#7A{{bxtV=Yn<6znb=BGBizPQZI+^x` zTk3!E#ntddOI1P}b%sTwHdRA6zkoT#Lp~Sc?}~G)mgwl=4GX$)XV4oEiYHaWg~#lB z&j#IS4Gw-P(ygc7hcPJP>L=ELsWaYMcBAs{UUfG5rSNmjojvqmv+S$I+*dtIOU3AC zAh(TVdw2{jawH;p%|#yER=geu`b?H*quZODIYqZ}C;FkZcUlI5 zW88)6aWwCZbYt4Hv`5#yaBiZKsjJT3=^wz{-Uk60?I0q$zKLW=p_!WNreBEb9pZYF zxH`{4@*;)y&|EVItpqu6k#exc+bG=Joyt8#=LwZd7m(9h-iW+LD6 zEk)tIr;-^tD5bdlbC?AbbBWgGyh%J45_&yK51qV?yk3t|{#(l1Hjes3FX~56OD|Fy z@7Lzc=6<8eOLc)?W9w?{GwwzXW9%C8xdUl?N(aP6bCU5SN)=<g*#dfLa`wgEMNtaQJ@n4BV&(-cq{>otf)0BdWd>jJEiES z4Ezv4<6Mv!N3>Bc+QYDHuBNdbG3E~FZbPl*w4y1MlFIHlH5zc;ZRD9B>5W@;cTn;t zeydn6y~bwD=~5xM#o53xiHb3oA%a$rVkXX}VU_(lN$!#3V{E(V5G&*%CWlfH4<#`s zd6*E~o9#;Xqa+>(c47){z?|hOG&k_j;62JwJd#tMqasi98y{2Xs?hw^D1l}XY>fDV zAA?RpdQ3ZLC_+B!gvgs7xgeXWKWwVbN>yX}psG_zJX%#TW(#^-g^M`;Z5YT*GVWZH zgs>2+f?IcWHu}8@v1l}WG)v6{0mV>ToxMZ9aWH-kM$x&|i>RF9NY|VtQFZ6Q)upH! zCcK#toqoS-kc^oC-wXh|(ZK0hF<~%@>kA9^O@bgkx*|ruTfomH@^7c;Z`CCC)!=?l zace1~-#T#fs#X8e>I)EdE4DrAoDeLlBrC9j6cefB8=#9R>`xXI6Q;wzivZ|&`$Z(~ z)_KY9(;E>&`W;NbRCtr(n5WJ>=emjB^ZPi&*U1P(5mw7BRr1~ohS+-f9x!r1)okU8 z%|t-u2)0TQp3(AI(WW|0(lifhrU$h&#WPvk2LT^dF>R+t6Ujz4k z#jT}`e%avW2H;-#zo>f?IJv4SfBaQfI&?MyB!mt^ry(Q(vUOE2=?)RnbSj~ zdH3D-UR8DU^ZR`MXu9q@=X=gQcRP1|_aTSJ)}a=B2UyPAq2D6k1?^N6fkE4U(K?J& z??ulK4eqC@7|{<`Aw9_V=t@MVo<6)?Pr>^40p3iZw!0~`X&5yALyv6~V$F9!^An&{ z(wzGQRB@!|vhUgdD8~CA`y5`?#lYAS{$EOr@Wb2r%15W3t{P;KXCbnw8j=0=NcYM2 zp}7#+P40Z@midz2!npukg?}eM`VhhJId%*;=~~gbbk6J?a27lX?{xB`^ytid2SHC< z|6cq=PCiS6Tj)sQ=ZJTfv%clOi23g5=b(^Ywk`e#7<7;3$+w9(B6EJND7QtD@hj=&dl%nR5*OvP~aQ z^t*K=I$6&8wKM`pLg`W|%9R#+6Hq1el^EhjPTm!LAF2Q)bk2K#W~G;Y5+s~aoN>kv z)N8x^DJ`wXS^u}6kZ?BI2lH9@T_CV)*je1wvWll0 zwTktfR5MS$CVG>!x_A-@Z1t-@AgtDMXe3lun}3Htr6P*0^&uUjX^w@i%`F%Li0n=Hs>mCwkn!Ps?FcOy;H*5ZjS$7{HUo;Kp?mymDx zIG&1^;As;78b0+R>x|5~7EgB&{INztd(p+cGO(1@f7(etdI5$O>&iOpp zKOo36B3~k`Q~cpfuX_gEC^D&mKlZ^E3fa12L0w6l7j&FbYdfeH66cSeh@Cl?f_R7+ zfA=tiMVuOE{TWDoeZ!5j|A_J;Qo~JDF0=ox9&hHi{$~O8V=9Vw@O=dh{{pSIlIA6m zyHJ#F3AYr1`aW?EH~b7gFHrC-3$*Ajpw9dXI4hBs=ya|-PQwYHEF)@5ge=iYMgBZO z?RQZV_&tPK$C6whjZ9=v!{q?%C(wo_Li0 zGz(JBaXE`V57uMEzC4iqeXxE*?AsinxDDXODQx(W!P8|bh2KP}{Iv^k8r}s8 zU4Yu~Vq^}v8=Y8ARl^4r`(=wQO6XIHeN2s4n(I-+m%!dV7s}_=h*qdFx8Y&MX{ez} zL(xjt{S-JilFU+D=I4qNvt?ccC;BzWtgU&+{YE03mhI?#E+x*9hB5pwsH^4+5+tH* z83gEi1bR)wukrH|1-Dw78vajl1}*W1*$==o;a|gLHI&~*S{8x&g_FP;wmGZ8`5_up z!yb#Xs1uwEN!uiSy+Bk(QH?~~+^P82T6{ESunv*v8*HUVKz$o=-eU_bx)tOP66*sl z3tx`{<%>kUr$%@mT|Qq0bbDOj(-iOTWrxjIutt=z&2Wc!!`w6YXNopb{dijbAABEX&6`R3oW*8<<6p41M@cg zYe?hTZB=_jO5P3fM~GFj#6?Ozt=QKFu+5ZwQvq+ZfJRE5QkXjeFz`T%{ZWf;q~v8_ zV&8zd4;v}rPRIo{v;)AP=YkZ8gl$on$TV;DU_FE}Q}-%`t`9;RNh~Vh*@a?4p(%_4G#hHB>pw*4O8Yc{6t}{2+-p+9RHwH@#X-w=-eAN0&@xe zHQW^z%?y#R!wUH2vOqI)uTUaSgo+qB{1%1&RavytaHj%BY6D7`v)Rb&&nWaf3(b{_ z|A+)WuYgNJfrhm!zA5u9vie0JPxw!u zzh5in4RTyay2L=IVG-C(1o=fRWv1Ipac1c%;VfzeXafOX;A^Wy2Sv5WY3K%dC$V0x zrO34o45~q;eU*mk(=ARGoa;zt&h*nz7OqSSO>y5woC6K-#m^@xc*=CIaXO8hH%`O7 z3V4jKnSt<;OL7Ku8ER12)xxmo0 zpy4&g&?=U0qONCxuLFNCVQxG|%sl1rS9W~`#s0X(){aF2U#EcIEDJQFevcA)$`Yac za2h_T*e_UYH);WVPyuJvd6VD;iUvEE^5@5pn0pES#4v%MOaAH_EV4MKUyr|$Q?H4x z#M&OMz0~dn;nWezxX%C?aRgyh6NC@0EfFlMsSZa%DqHBKKr(V|b zE(B>paO$Pb(wUfTMV4Mof7dUfNE&}p_bg1K0c_**&^hA-8n~TAj=F`6uX_}XU(GoI zKXD5F@gxulM-YLV(+b8QF<%N`?gWF1yzy@`yJnn5lKhA4#exwKG@EOTM2JAjiR(1n z0S5W=#@YxG6obEBB%*HkDj?6|U*n9(QVF47Q~j^NrY@^-PAFtHN`Q0VcrS#^nQ;}2 zcN$g!vIGAbPmBi*#N$aQp2nq$B(SYGJ^IX;(@fQF=2a-(SG@Q19aN)EX|25;kEd)v z{L}x1%GeQvjhZmyjUYRRozhbnIQzLJ?pWqa#r?vU|N9mC~ zV?F=*254M)PQp6Pq9x~0IUb~&V4XH%)&C#CIYfWjNV<&#+o<}ror1d8Ord%T)ibS$ zXjJj)*CNzHpI`YONG;r&d+D<%1v>b$^vj|^(At)MncAb1P1YctbKeFD+R0czccDg` z=rq(x?iC{^{TTaO(KgyvbZTgG{+oa|E}kEyFfZpnek)X^a3be4DUz`po9csiRd zhpi>_;*%)D{|Cf~bIg-OsE^bfM%FK%AHoxADY`7o42j3s66ozC={L_JwQ7qB&zzklFhw6mjHx_{YiTQ!LKj zhqj=l5K(`;kGZe?ElBgJ;!eAE25m{>Gz^gIwKxOt<%J>7?sD!g=OQUzK306)Pi!S$ z9HAqo&e$pEVGaCou+LvF*c?&U?(Fpy&+%vZ4!Ek=$fvMY*q@ zBYE41=j8s}iNfQvYVTRd+t9g7FOi5oM(n+%1+@qoMHcZbZu5;p(azZKkd%*-Z7Pi% zx3O`4eS|eL@H^E2=fcQ86OfJo&^HnN8u`PIV+36KL}lRKwW#QPqakbJL^xx|3_H$Y zNHgssGp~ep;@=t0&)!2#z`Tb>v>b8Gm8kh6;&f7O9csQn&f`n5oW0i|TlqdW!=k;v zMSZ#jF}eqfnCq!|bcD*u{S_6Ld9uz9Ac1_BrlD@^E~q>C`w}RW9QQ|5-*?U6(^$;! z59jawFWAVplNw5|d?N&AKM8;T5`1AqZ=-X=SooL71qGy(4ni*cYlOb=!RGxO^GiPdx%c~&VQQhdMNTHD0kZE^H8}bx2r5$SF;9b77bz@f2=mfC+I%O$H1Ju z7a^LjLr~PvNz(1?y|o9&>NJrfboPD>#NTUTmXTv$PdU!rNDwFTQm*t&i~PV#I}F^8 z0NRHw+FM|_^OTeoDdi^E!KOQ7lk1Q~@OjT)XNh_KrS=kNVBDU{xZDKLY`bW%gJL%!zY#|tbP+9}18pb&<_y@ofR;Z_{w*EocE*-(#U={`SV>A`0MQP6X)PaW#@&2B zLdhm_kKGF$q;Ba>t#0WqQn%ojD9NQ4^BIe)E&=*2BvH%nPNBNcAxC!UlqHhvjNODR z`7m%^KWJtNeU(h$ep(rqy9a1a%_yfPw`ZAr-p9{Zo%mxMf51N&K&N?N7kL`fE+RX* z4A$^BC3ov$$)6DX*P@{@ zUbL~XeaN2NPbG~@%VF9Zy|k-8ezoI#2sF_^`LMmSpNL-ukx$mMR>7F}T@X8dhQfIx zcC_3ILmltJH`UCBe{ph$4$D|qlV$TCLY-UaOs8bde^i9YoEUkSg*DU3eK@(c1}Sp| zr)JM>(4mgNJ*JPs9gFJ4N8woW$ZC078CTDfmRsqWV>^yxdyJkr#^a|`j5C{H0Uh;U zICr`}>c8-$>2%j=^sV<^v!w%x+bSa)k-rNUPTz9I$NhAAKd%e)3oX3$e%@V((>xD7 zjA!#a^m=+WjvUjuDg3wP@Q;xmsrn9OO7nF0g&;E6`?Tf802zE%c>KMfM+onR5Jf$m zQ?Gv&c+DK@Tno=fkM)!vZHI_Kp{sw2KTXf53c_#AIQxlsA&9J-D~MoRRRHmm__xsE zVH7F}jXd1e>qOYE9sU+Dwa>yEy-cI6NJJI#-(+GVJG9_}?~>R08_8|nj~4Y)3HgKk zUHUh1W__G{tA~+;TW$z|O}l=M%Knjgoc7E{51iNHS*^55WYj#Y@XgqF{95-MkeeLGdwW z@$p`9-L8{cjhyj%XQ936*U;SeKghg@bn$MJT|lNS{l6M&u}x`U_T%5e_p0w|$M`yJ z@g|jX_?_T=hxEKGJhCdJvkze6i2qPn%16t>q649u8{jDBNJyjn^%mBZ$nY(%41iH# zb%B060K2v$@D(bfOAvU50=p4727?y-mwj#|q_Fs;YIa##v%Q5y<49Fl9QG7e55#_n zBzuRs*O7Npqkl0FCE)QtuLAfa?Cb!LOOzEkV??{yqFs!vyHe43aAC(bML-JP% zDiu$axaK7&X!r$;eVXfRWY#jyEJwZk6xs1AehKesevf+Da`ocVGyEPlz4-L%NE_rY zA{`G$BJW!&| z(yR1c$NJt0ed0x|*BbVG0P$ zVfhV^zl`rjn!)y6LC>6jb!^|q@GR_`&G%0_uZe7j;v)V<9wI*&St<3acyIwfm*+$D zX6CUF7k6X-r+69ZRnC#f>mmFhQt-jZ`!IB%|CACX{6P}F^i22+w(Y~Tu<AU(3BAEJVO4v*qe{*TZl*-rMigj_)5$Hga;p(oL7WAQ0ZH-b6#9gNVv2oreR z5I92PRUO9tzA~<9@vp>S8t#qyO>@R0-5Xtg?PMP$X3)Dq2Xn;!AD8X*5Ok}h@(>*M zc!)W0L~n-$-r3W?njV6LoG}7^ts3AT0DKWZZs6-+TSOf~7mD5qLr;57@;M@BjA)xJ z+D7OpDjMr?uDT7+AH~0g@0KoJczE#|GV0eC!22owMJBj@&1;0^_-{ue|G>kG`ZYmS zWGfo)=8f<$O_JNAPzSe+29Out64`tJ^i~TVUAOBEAitl~(HP6e@7#4Z$Vb5EvDP`3 zJjPnPx&e3)fL((KJcq!=DFlvPhQJsCF$BbaO@Bt}&iFNQK-^P?+9IaH?~J?|W#(kx z7D4Jc>(555!7TN|AiM_l8N>xNXpOGtG3${?JGAY@zsQb=y5B z#?biGLgTs#87tpz2&}e<6pxEOmAqLrO#PRe0V)UoJXN zcCj1fFEsO~i)_039!dZm1->4`HSr$xBemo`=$&I;Xz}`iSKB1vb&5e>o*DisqCO7xEqttYA%gvn z;7{apNdK-U5K3SQd~M`uglgV;0T1TymeOC7zYCwO<-xp7SA+SFTX<_Qe>x&C2lGEf z%;sSJW_mV!#NY8O{@WWt5wo>+=|9b-FB;=BoZ-%ukD?ZAK)sQxIC@&nv#h^FXqKf` zaoAyI-#i`p;PtAP{T3wQ^SrA#^ah}l`%Nu$@EVVI0f!cuJqtL62Ve+|Ay59McymEd z`kd<`U&W;L>K8Gw8>HAcY2pQ={Y1P2#IK-Ico=sg;$MRC1I-YY%2gPO-`U$S*Kz); z0eoMVv-i^Z*s>uH<*tl>RjiCNK&*y~+vuI_h3%AlUON>R&pTJnM=L)I{}v9>Va)k| zptd(uLz8up`{LU%PWHdOen9MoY~hT~z5P7de#P3w*tzh&4@2kN^Vb_IXzv6?y)Grz zMhNHpz9R1GJ&3ynIK$;QuZ?UYN@V@z_&F}JU^ab1m|kd!oWvUx7lTYab)=p)D4d#A zs69Ug?ZIWUXN}|cD<}#AMrL1)C;I5~vJ-eKgO-TMqb!@xUjm-}W<1lL!LkMXp~cy^ zsONfoV;v?2ww!Hp(iWHp3!lT+Jxu2$Z}U|1xeu}iF=@p|NH``H&dvM zLWho9a+=P*C5Rf9(C6+*=aR*2$;^Mn^O+sjN6tKF;bXYTJaXo`Yrc(~xE^1~dJ@`Wlz4g&C{GpGL*Wb7qe-=~dxaaU^ zADndkku?6?iPqe54Dz4qXJjESAJpGV#8)CIl>L#0`afapSpNtSM?j>^jx4VK5k0>F z&y=f?v+93C&tJhaZEGy8aOYHA{<&Wj#9Yu4IX z=gdMEdWzFMuYG15!D(}x=&{}Nh<@Jeb+d_7yDAbrmI&)+pT~shwSc$G#tc_+w$9o% zQ*ck6hnlo1@-OR;^~%g387y&iNL~06sECQ8C0(=Kh=nC{3@zRBRNTiJRBxuKakdwpOS;VFAOC9&qQm+G<7G=GP+q#3XA^blJ#__^d|c#sUeLMSzo9 z1ezb}=W-Gk(hu2j@`?QXiZg&Ych)S(o>F62cB;(0T9vd0H#WqssEZ7$qBVL&hmn1! ztwt<3ucKo?bc>42TkaNys9Y5D3Lg=Jg_SlD*Gs6%CUSuiz1l{dG8bchj{&OKVzQ*TT;s0XtXXqr z&7LKy2IlHis4cpNAP-xi(ZSvK#8`78noj$P5ej#l2>RM-5!Hmwi7O=!}nV}7jmyUXC!mT9Yg0I$5%&?-WEk0p3>sC*0t}T>1dxNrLcvOU1YE9L<~F6c@(LiWm( zfU69eGU94!Ch-rud>CZr<~1${#pveetMQE%?H*n7YYZ|pxr`$w!zEuE;R=QtcwJ-_ zTC0QcFlSB+_m$U2);iQ0>cQY|?TR^b9e?XmeP_B3Jo-<4FM2&cxqsAkPU<=f)ZD=T z^2ecTcdnm?PCxS3W9Q&6f0!6mGO}vb>TG7nSv^=x7mBO<6JulP!s=DI{78D`?nC3N zn^wi*tD0693&WKlBkA$t>dE%incQ%8VkGUXo+uX7!|G(|(0ID&tnM5i&t`^GrA$6o zT)lG`v8+mskFV~^=St~ZsknMWdNQ5OkHdt4d_Ft8CzVmS4e8O;M7Ff*;BZNCIEJB2 zZna3m>fvlEw|jLP%nh`mc&MoDFm1~;x3^W5xQWR!ipNWP3hC5{H`$2NOBhRGs0?!{ zf0JYRk%?@&xH^~0c~Qg5m#=PF6~{pbPbO;e>h!@<7;7j~vf|ubET+aYVfc~s(8O-c z4bz38bRl0{H9U;*y+ih`+Jid7p=5q&Z+f_tJWxoD3+iM$elb{2PGoYW=6JG%N7Sxj zX=EfliZJS75}dXc=D;N~FxIAk{MfFaTqOkMx&kF|4y0tfR8U&9m3zp@iAjLaL?$Lz zPUJEN#Y0jSgw`?xS`=+;qLeBmYyk z`<|NEyt-Y{D{5AGo|b!_&J25+HZA(yNZsAhx1U{iLiDfwch?>leang$rbWZp6--C5Kqc5C!L-a$@&C%WKYFndkzGidn+zU9y-(7ely1XVCA=T$W`kSkc zL|=~VjDGKmb+vWTyK75O@PR8wYiCEhHrLLIzOxqJBZ?k5d^c>m_rlE(_{ORSubs9q zdh1}_-4yxqnhlZY%U6-j?;cS6Xk$sz?ikp7UEN#jPON+KTA=S+Rd>R*(Z;(a^Fsrh z{{ZT}t2VpD+B2db8Q5IwOw@g}Zp*}$iHRqkj2_x~Az+WLLe4CVezd=iqd99Q9zM5& z!e3op_e^c;CDRtd)V~kb-2hwezp7?q1gy8Os%r%9ob-B;wAz``->;~nteJb?CCJ88qn{h7LyZFA z{i`;EFg^N1lEL!}E1@D(>^>#-{7Op8yI^e1;0cKN*|U+4Z;dwIj;tv~e>!b*c!AuG zSYC7Z$QH<>5Jn-a3ZVqs|BOP2M!$FXNZmYe-rIB}ddpSoqQ62-xcMrobJL?Q4wTr^ zU#=wlEqzC*facfz;M%%*TOjg-m76D|9e|$^edAzYX*|DDl?GYx4Nqy*ER9fcPzAre z|8cNCy|U)4h$sfCj_pXsBreWzUt>!4MY z!cC~@oR*tmw8)QVAYFNYPh-#r<&UzW|#2XiU+yCZzc;6-MuTU0yk}V zQQ7cW*f51QcwbP4SGM=a;RoHyaW|X$*%c3>(cOT`aXa$$lb}VTw**%Xc;;V6(Ilh4 zKU{JfYV@-^*wN0fonCi4QiRdtkSf9uxhq9kT5|xqNd-hxGc3sO>+w{07M< z!&SYa4(mk~x}MLG1rL2`*7 zUQYF#dnV4A4_+g3=EiGk+Q}jQ#yJvw=qhAI^R<^u)}8p)*Ix04Yw!8|>!N#Kh%S6) z<{j6<@B}(wt$@GJeE!VMH8e}bqVtRzHMxzR6q&g>x~DN(zjNj@$lC{; zI+W7P=$~qCz|$M9rULx}x}s?G>wP<4xj%X=IYaP&&iq@M|D)x^|F?mi*G>Taj+Le8 z!-LPzKn&D-1~%vG?!o`w9G%6AKV0(y$WL5N#qr^qBOInko~XGy`sXtrjJ_c<8hsSv zFP*hH`sBdf?*ZWYYtRs)->a!>q~RV2xAq^Y+Y-Ivg_<+x)vTOX)3hM^Z`ah_J@W>j z?ukAQH8(&F+4SAMBcOdKT9Sef^c~q>gL~dKM=x%SE=7ueg>rg!)(bQ1e#KSl#l||W zQ#&!HioSgLsH+m zJ@JL;zPckdr=jT7Is~Rn{9nWwRKZo6)GtH&XSS5PQT|38A0#GOofEmY+-3pTZ#{ay4sG{-O%0U>DX2 zMBJB)fcy6&68#k|<%2Xx=`vbQlaTYmBf3Gd-lrjhDmWKQ7xZ7mxpYJZeqLOvGhWM)Ag36EvAH-*F6_B{pG8k@4cV)-+!tTfVpu=uMo zcsy3$BxzIzpT*juByGc*BK?%l#sv4-v9@! zs?0HNm2pc)gdUeE`I%0UFJFG-gZL6%1w=*gjE=~sMX{c*4EbYah@0rph{`}z1TTe0 zq*~wp@Z24fEEnSQu2n$ZCbit9Bl0<-n|u&o3z!1r9vxArmNJlAr1WiCi?0AaCRv}= zkV}6igU4uJ=IhQB`WsrxS69!L(j8ihZ-}@`vU)Vcr=_bhWU~+A%c?3MLsHBA+Lp_4 zq=^4(l)n+jmx99*{WUGsuh2`il&^~XNTQ9-!gdBrWv6kb?mT>2Mr8z7>xc$b@UNPb z>^)AX{*L@bFLWmF4q;dS1i=DHePq2jPm`XKLG@+vfbQ$9GMZc6=4EdIXJg#l=)um@8>rWb@^Y{`skL`R=#ZU%vk(72JJ`Ys|WRKLc zKin3@x;h;4F3I|shWN^)3dnmZYk6N~$onPa9&JmnoxAr-)-GAIF=>ma@bmKpI%p!N zzYDzvzSbD&!O(-_sF=YAFNxij;mp zYw;Dp_a*Bm8gl836GWR>Eq?>nOBDKdTFRHaclu#C zigTMnku-`MXBHensn*4Ckq|wYtsP* zb*fC@5;x64#{H{Uv2aMAWbM|FK386Zs(@TnS<9}Aas z``bZ%qmp~0R;?>Yt6TJT%2gfuqbqf`M3<3zUZP#8zL-yH(2ncqq*NULt1a{upJLVO zbcRA^REDU`4(J>D*9K{)x674!vkaC|^aY=yzCkJF zD(bt*r^r|N|7nU;lD?{w)~77FR42_>6%_h0S4yEXm8I}WJpK<&LP?EPmQuxQNL};K zmQt2|-?dO#wm&?sGF{u(w3KgfbiZV|5ML=*0eMzxd09u~YyH3QL43_=3J|AW6<(;8 zW5OZ7mbUy}o9nAvN_w%@;>)^v$tnX`N1JGQ%m(L^d>FktM*@zXk(CQXXtb}Xq+v71NQS(XYvUh(Vz;h zJVoe3h8~f@54fbi%3x!IMqMF;Z*)nvMcZZf zM1+@D`M+7(7GJG6S+W9h>&;r~Qah0zP;$qdDy#}?0&=F*a-O!uSI?LGAigq~0;Eev6sn~RWVMuT)>?dZb5yeSYltsJ3i3J) z@zsy3B&!VMIv>QBqADQomRkOzZAqTBNYsm%{0&$myjPkpgDUu#O4b$)@#V3C^!!7R z4k_(wxzMrxs{*1@Qbx-T8PR3(7x`etzzC@^t=eCiBPxweN;mRRq%OD@+IN{#agD!@hMi<5}u?XgDSX6lYCO@ zv-STize|q>pn}h7QvV-haC%W36AWl5K6w}K3XL-LX}84kHxvdTnsoe$!xZg2EKeC9eOk@v^RUzC&zCN;??r68-qA@d~5 zh4`FK6_7x7*5l!+bzEZNT3y1uxWW7QDMx9=N8r~_HWup3pguEbsVW0~BRg?Oo@{(Y6 znRGzwRjf7%g(4N)p-H}!Dye1-8BoD%H0d(8R76Ngt&|Wdz-j71$wi&yjnl#;&(_L! zs-Th!=xnx2w7SkZV2Rqk!8!nwz}L@idq&*&8R z`c@^iPD2J%@LQVXbBQ07EOoD9K$TGtSBo!h`?kdZEz0sT5h<4X4JdOs29)XG5x#a*`MKY>7{{x9&(~C(^N4cX2R>>nbw2^hjdTF`k?u z+}7Ylw{;hLCbC(^QNYI?C`_c8O93x;O?Po)Dq9q64te?Q-Nk;s%Yo%Z(2qDYHk23f z_jAyTh&3USiQF*Vtio#4gBJ!m)@N?IL>(~f?fnlwzq(5L}W#kVJ{|zD7o64KQTHg%h!0ez^b+h@QzIS07q^J z5X};bcNYiHjz<{9c=yo{r7~}Kq3)vvMdFy(l}(L#l>4ZbAiM-Bo)Lw9vVh1L(iLm- zS|gt=FcJwpCf0qlpi*yh+^bhUTVSEr#6oW{6m@N5HlI>l&S{fiX;$#I7S|4jOM(SQ z`zDvG%UnHpVI2c`*O}y#1 zLk>s^C5eohw1}~$P3cnCM4^CNY@pqJuyFA;{pnKY5H9@Lo*T>!rzUpqDJ2dLr^ngt z_HG=SOgLo_PKrd6`CJm7nuU{TC7nc1CXyo!ZB5`39%|J5YcX3A2Qy?T{aCCu8#2Xl zbj;w&kPU!^R2+%Dy^~}ug`J69F|!*TVI!)rGl4&Jsgo^;d=Y|_LoDVsIZoLqz2PYF z`?L8{QDmr(Y$=bef$Rn8)ObJLBUCJ9hKpR7u@;L+aeGNlDPKY#zX!s}V&)3;`dJK4 z8a+v3ddY`OA50HVlu|=9R1jLm_Z-6IN>C>>O<>SuYIY;ZQXNe?mMJ1bY@=hXmWjv{ ziz2hbmW;PqIMf(rvR{e84AB?s2uP+@#zmlW+FY6i>5e)_mVUvB_G>1 zW%ENk(h>pZ0v;X{iU!1O;;|dPvrUdX5-5bk*my~d6geby27z0^!QeBTx%J=W4o6R0BHM0h?XOWpmkWFj#oJ-rZd z24wE8n`~dZR%GY7&Q@IK#*+q`fAE7RxBW?=vXI4M+EJBk<>XYQhEuaqnC?l8^!l=L z#o`;%C0vB3>zMf{vu};W`qN1rc05i^8$D2-TEJ*#_XMg3O=OHr-~tl4IgrMUbJV{l z0BB88M#_N!iYu2IOXC7NIE*BRF&Ct}@X%8R#X#m!3kb8Ibtt_%Lo*%zt%Pn)=V&I0 zzcShF%G74`vsP-_o43K^*G zEoCwphr{l0qqqknA|7zi<&c(OEY4^ZSMMIJK$)ofcrIfax8PDqOG^hUp~NS8hcms( z1|krW{GTX_R^jkGLrBMTeMYNMh3Bu(Mx705xZ$#u8?MhuQFKaSYhSvEdN%3sugZq9 zB8Hn6c~KVK!T$ZCbZQ?W(P5d3WhG;++fs#n-B@oKNAnQFY>QHjns}UqdQ*i`26ti} z+F)t(Gpfo2n$>zu^E_9l0~5s_bb=ewDQ=L)Q&sXZg$S8}V@>@#8J1{&`A|eK~&-_GTI8DP0 zn&mVl+Y>q5hK&1M6Et89N6R(PGJwNncx6}~PZ)0tM;i0Xs%5AmY@xByV9%DG?HBbV z6FptqH+1)Gat1Eio;-ioK*FVT_IGu6yN}y@5*9$^l%35qat}5eMHI?&Lh{Sj&O;Ph zuJo2*%LvV+Cms5!Qlu@bI&Bf)p^0C!rLCFf)+%|ORPnrqc+(gFa1$ED^j7ltnldq| zBu_!aO>!B%lwh|rZs|%DOS}Rg$94`8yqH)F>pL5&si(GEcg8y>VoAZZ?rmO(92y&kf7ZQ4`T zCN-$>rU95|5Y5t?Us(z~TpR;3j3TG@sn8!neN$D_!qM1owkV0rPJ&8pzMD{Sn$ z#NgRqgAgd{& z9^U6~(~9cI#-%dISdkE%gt;OiTSx#%uSAql#A^^`_`L8C9)*8Y5xm@>?Dpd;5A)U3 z-yGfh_3*$*WJ2I@#?2o&we*eljd&!aOa@9sNcKr?aOO#-KM8?Z7m6;IaRCEFnoq0Y zp+BX5W9$&Hg-R`DifNEha7L#bhOvZHy=ijAimYC$*D)8EOhZxa%*;y4i$hd26f;U={pL=QegsL&cNay4k1XN zQ#n)Ib)Bk3G6#`IYNBD%6I_<32_689qb1b*I#1-9YHv}oF@>j zJ7_sV>C+1(GJDHmec4qG>{%eGY)8XYpd2BywDgfTDkR9V*uxc zyO`o8fLGKjdj2-yZh4eUe%INz6-TkQkB%0xiJUKO#2UU{M_0W_KsHXTr;+LEr;aA0 zoMgLF&oiBFIPFw!n0B8qxlm6Puo>#zRdFDw@?Q7nDhkYNaf~bkoayav#vBX?iVl-u zZ5gff^IXD98evm`Hq1VVVz6CHCJ2OvgVtV!{yjnPgg9WcnI4!I%* z!7oAUVEw~|%y@|kS{w)v%N91(CmWAx*{*zcVl3yEHt9ZjI<a8=_2jjnQlpz%{1A!xCq8zN}&DUA_asph?;7x>#-oNZCU|z=-vYI4{bPcWJ?oJo{MZz6E+@ou)!X^@abj2JiCtNwpf;^C` zu^JcTqO0;jF1$)7w)Vq56<;iRnxH;R>UbRoTVMcM`nx3JP(1BPLT)M$;?Pnj<@AV7)4E`6N{T8 z=2%>9jmQay`KW4*CDN`i?%Wcibw4p!Jl>>`Vs;@Wr-lNP9HL^4Qh|3nI19Qc2lO1E z3^!PznxkxR=O`NpX--l6Z9`2}Y-H7~Lr;IoHxC0=rhOQwkOpEPf?J3IsIrNal_=Ln z0(KTub}GMVG@!E4*e%G`y8sxJP-vLiy16)+l3FL4poIxi*V(2sj+o=)ZR)l@;aAz(UMlY#-Q3qh6B^OYktL9b+bb zQU~v8<4qwdMoveb%uOy)8%zqiI=vlchIzkOuGp$}OYK2z(K$iHazfHpchk=Al?|_j zpnn@NfhE~q>{3cqt`l;V9@RXpym&cp7~uK!rlfNH)tYHJOGA$iQo^l4scE}!mS^-j zCaz4!Yr;Z$UK0}B^_mEODF+Tu%ZrpN0@0#EQtFT0?qGG^s^aojyBMu4tLiRVka|)L z(6^n=euLVJ7!4N^y;IwUQ0YNt;hhCEc|%udq;wKMY=C3yLWe`)u{O1Lp$`GjdqrY% zLy@GkTZv;W_DdH2Og0*F@LEzeO3D>_K)dr=rAl*Zc3Vv_Sf#&$U`n(H=d}C>=8&7r z2rmM9jRP;-;pm~ta8xiKEnJ@ZHa^+SGae(~DX0z@i3&vLzX=tttR2cO$c*6hy|w_a z$oh%l8Zeg;$6#CqG?}t!;qqA38p}_nz0w{^xNPi#6b|XjtvPQ_xSMSTM)zPU=Sj8Y zUHxTUes&XtFXL^4;2~Z&2pa5tgOL6v8t8?q6D`*;<@m;aQx3%uq`R6$%pf^mM;EkK z8YEcd!e)@@)Rs7dG#uSxXON~TEqewksD1%7NW7Y*&>*=fFNy{#nac8Lkb=q!r9o2u zCd9o(Ku@Fw2g$wlzoUkLK&x7 zm$)c}4*Q|^8K*ZZ=_rMp0=GBCP!6XsIQ8)+1vckK<~%wd&U& z?z%eJa_uz0eW_ZY>sXNgsxD@GvK6Y@ZDz6RG#k|>WQI|lo^p93YVnj!vz%CHnzj4k z6WklpxR4F|9||7ke3UPUx7iXK(qgj&7d?f(BCezZbD5$H@+5Xd#tZ*8%eCQLM|FQ{ z#BR+S{dK$?P+iDlPaN$7d20OWox1U|nwhgkSM2fY$N^d2Jn^2AkEhe~@az3+q>pb? zJ|0KznHZ40M4Gb0rx}?_Oh}%^Y5A5Wdn2lUGS(s7L?YxSe@clpJGB1xr0nEK1+oBY z-CaV}0UA7Yr4#C@Tow^Rt>We=QGHbramPqW4oZ&WAzJ;GhiCOrDqB=1M{gZ)SE#ov zJ<=CWqzi`>Hl#zuWgaqN=X%W&FM(9*Pa)39w}k0c5^))djy|}K$6Jv^el;Pm(DzQI zc=x(hgxdj?0ZNK>h!;q#@-;dB(iI}XrK{Grf-T1a3f|yw6J(XJ#kI=V;(E)_V%lY7 zv8yiy+ApAz>eRO_8ZA$jfg0DU5-tDAi^`!uts(6{)=t+Tbn^X`>g`l4EcuBc^6Wo^ zkCE@?iIsm`xwUb~tsLY(gs0^;E6bU84P+nGB$V*GwW1acVKBV6zb#2mBrme3n-5&` zVpCAGPG?tFqQ5`6DS@%S2==?d3p)E1bwgrn0+RrV*^<}=4!;{k7KmoqkL$6pSm!op zS=K&!a65~&tKFB4nRIrfi*AxZ*7}KIS!-_b7%F(hHb9HFCks)kJ5#+~ge4Mj$DNVK z2nG+ZtzAY{CWNgl9!L8k@C$O&^(`}* zW6vpCVvmiz<*dfs>RzN+8~lo@p#%ASY5VRYcZt&m%8XK);?0A_wA=yoDx7peIF<%J z-)@V-GkZvujJ~W;l$tW8MP5_rrCQtI7L%`Wz~!+cc)^dR>)7i+OrYHmhEomsvIu{WQgjaj-Xz?2Zil*iaw$su?px^rHg;vU9w7+YskC+@&I z(1jbBH>Gnle!y*6WUJT`C}LT^Jiyk6+dV^-u_k#%awU+Zw}p=x(B-t-@cwFQcY0&K z5URrLE~o%K+Z%ktZ52u^12FeOK3VmLcF+7&OR{;5#CVG(ph8rIql*4WawRI*=0 zLRDia?|WTT8K3KdLVT?Y2==iq-|r#=eQP;^%0AWSa6Q>k&GvyCe^r|XF1*UE0#{&a z8w9T0(QOO3@>ALjFvP0g0&s<@S@?I+Q(o>jM5nUI?}}Ak+IO-33d~({z>1h`nyODW zI{J#*L@VZ*rKQDPS1PB(=%~!GMs>oK+gEjZtQ9RQA!=+TZXU(d2bWYy2u5jetu%3Q zY08btF(*s$4aRAVrP&1vDKE{I!nwdg9v8c)tCf*YZd%;_+>5f5#ABT!Bb&Og6p+pD zo=B_N7|nEhac2r;{iZISxgdzw^STsbV>Y$BD6Yc^)ZpwBa{a@&8z8qEFRqGbntt^k zNTa7PIRT{n+0M-Nt4T>jYT&*3=Lk* zMLgS?VP{#3*r4|VtIjnX2cQjozXm%hQ96n7%s*H`?rW7FUy^~O$$&3m8!7#@X4~vQK9~v3a(e&d38rifF8ET1Wm1s#JC~9ODDyr(J8G2Xt63*0yNfNfx}h;q)5<8KqYO)N`R%sow%wm6&=-~y>h~p+gEi) zSStZ$LddI&iFf-zUfjumA({#*XQmPQb*h292zn8*mVrEdCL$xRQ)X2r!3#%}qW5B) z2zn9tk`&E=Xre$?$*>m#EraOQ_-k=0s1R*}BbOGiRl-2cbysU8u>4}J29@#98WZB6 zH9y!tYqr032fF7n_{y~>$bo8w)i`GjuF5xSbd|1IU#cSBpNrwiX*Bn1#m0M}JPli|5M8eFdtuArjd3Ky;1da5zN@>*^JT&ER_59IkM zBp=M;;hOuX{TH7yi^b&-RGc}RRC8y3w4gCDC{;+~$pXe<6b%#=(tNa_G2wL;(s;6f zO`K4Lb0560w#5Dkd@6Ywf-#>>5-sRhrA#`_br+Y>4v*j|}fjPtpIq=E5@vw>CyD>E$e|KHwN z@Fw*C=^HKncUC;D>ZrbtVD5|=ZI=%z<2m@9jY@_zp$_89)sysPN<%4vcm+g|;SyYs z`I%4&(1QiB#1W%?H6$pk*kg#;_5NFLNZa=`m~)ca{=+u@P<(WV{0HAGN6qiv+*L z_h}lA#G|9?yVBIF5WZ=G*-5beM7jHvm71_wmDCV2tCC!Q!h>g3q409!!hpk6tVh>l zcil`S#%~V~8I3`&M}ym6gex#wM(|`kT(n%`gqx|x0Bg|eNr3EVV|4ks(JLA?-=JJwj#xg(@(vQ@RS<9An8}T(OE$XQYeKsA;KY%oF!)u2atgeW z#X5wOL&GoS)haR47eKWH+mQv>l`Zn8Rq_SON|7%X(H5hDK3%+Jyp^F}Gms89=;e=) zI>N(gZ&yUF%@c_@F76>&M$vArhhO&ax(Dgi)J(%J|5;^^MA+$d59lb=mdPRIW!2c4 zF0}Dl*`4!5k1N3V4z{u&uZ^)5bgD)xvMQ=E(DdTGTH@4y<1U-5=gq*fx_oF$V_a&q z-!|JzqW}`N7?yauX^=WEq58?{46~)YF*H+!^(CT0yEn448fkBgaT+}MVhm495Zcn% zid^C%69;CvGSRV7yeEzOA;Wlz7J9l;Pe{5}yE^-DUga%xMPy~=Tyulli!TCy7PZiFUgb#2HcMYL0_{x= zeczl02J}s1_N?l`f?-ZJyNbR??9IhH+q0l zebCOOY+6`Dz$Nln3D!4Jmj(M4CCZ|!+`QDLOl|j4iyhter52yk{-rBb{RXC%sb&XL zgQvWO=}Jyz4^vB3-o(^Ue=7>x#S}B+a~*fBM^(utmqd5MDBTFg*WjbMUHS1tEf|eFz|Csf>=(dmB zU3U&!9C9tfDU)t~OHk$JHX}a`#)`&CTohBKlE!o8V#!5?)VOn4sOB)z*pkD`;jt!{ z*tRE?!_j(VhX_zcgo1i$KMbBi+%XXdjWvy@3q`zqfO!j)x(|V9uFnbHWz%bdFQ8|S{I~DXM?{y5()oh2}h@g7R|(Dkq0Ooq)a$E zZ82VzRLMiGLwm1!bj;kK40C#YBu|~Es=9WqTUF0>hTY}8WGRgoPOzy$)&?}(fOW{J zdZ2%{VxI$2`E2=|qc@%1&&F6qccWg@QJ1xy>uikMp2x;i=YwpibK#A)qzgl7eBH)5 ztV2k7yL!O5GnXl4QrXNE*daqvy4xX5x(&b;xF{-eS9}d#65F$>zrQP+fzKfndJxhR z`o)kYV_4}EE~mV|lpa5753mac>0PtRY`|)asQZcJsa6V?A}I zxue$3(jMD+Br=6^G^+&Ntv8IDMH0Oo6O+jU`NFjza$Dz42Sydr`;%-5UI@=jrjz^@rc=Oxy)cPaw6ppAxFcDj zUoOi2St2D5YKjhC^czo(;_Y;Y{uCYRrP8^Px-`oh^SR` zQ8JTHA~c?+muQQQ{DF?bFui%`91uSeSyUn=Cnwbwo!sb1(K)am|4)uhU~LVrj}E!q}b_)YVyq+o{%30Kk;cUK`rsBw@ z50;Yjgi@p|mmto5B|vm7z?njlAnLHFU9vK`9M&R0B?lUC=iYEKn;+iiE2+W(A_oLi7}^CNT-u%c!fg_I?H4>JzC-bK8UwRgeZSt z0&$0Nbw$A$PECMEEeuu^oe_L=o7?w@CLzf(A}(neE;;G3(F}4FMh}lBMO#E89VQPx zF`mS?6sQIy@fv9f7fK+MDo`V)s)!%?LZ~WkQ4j?yeB!1)lc!6>_AS*aZx1)8dKv~FHJ)YWmS3% z0g6fHC}`w|(RZj2+zxdnq6}3qHA+Ky^#rJwzzq0l7RC3tk)yyco&wC~7&rv8jj>H@ zC+YTdV@&aY;!Q!r;)JvB0@QFZdftWrey{3L&oQ*x*w*t6M&D-oQ1a%(F$oTu(i(A1*mz=1q1l=r1gu>tg! zdW)d5h_~Vc_-dkSTr#Ip**Qj?;`UJ$NhdB|!;9(Z5%I!#m9Wmz)>N^yDVs;uZt7A( zGTOd;zNB+if60tzXvC8FLI+%J+CX7K9P~AC8{s2-MB|HQ2GmLuGI?ueEQ5P%dN3j5 z&(3t~IzS}87)KdTgnnwgq7d|Bcaf%lVt&br7}QUIjSGXw;({k0 z$nEPK&&Yd5Mek{~x3T=lL^kc@#*&k?(wfHzc8sTgn1GEXM~ZnlRAw^9c{waLQn--b zP0O-{4)MOXh)ZI>Mo# zR0F(G+g}6p0lfQXUSZxbEwi*mo1T0k$6T25#UQi*Yb}wvTckdbR?1jh;!YyElCnF$ zfLHyoWbHZz`pjkzUN&K(tCUrkgGqD>+_xt$ZXU^`=`s`iP>$)Pp{_WVem#U35t73P z4<>i>U?(}5D&S5T3@Z3f^5R&#Tjlo2^+Jf~I;&_-KPg6X+yl6(Yf5y*#2!-bfO;Dz z2o$$LZiUdjTmmWJjju9si6n+tA~V2KQXcJ`KeWgm6nlEVuyKe^P&OsI2k2!m_ck44 zkzAdqF1uMvAJ3)1S9j1xLShox1s@i$pMg4w8`~4@s&(>pL8NFMHEi$7yu!%Rsm>lm z5M~lz#28@HK$uCiK_(_1D;oXgiE=D!mAj=)A8A6S$PGeH@Fait$gI*Enyfm$f$O-@ z3O2|};M+|LXGooX38@?P z7MTKWCD-n&lE~DKZkUlB-RTWe!;}ticm%6I!(ob5bBx2pPx&N=M|diSIZVOI=Q&KY zziNja>CkOd^(sc+RE0+2V+|QKhCsh;RYRN^Q{7s)RJ@GTRxGw;1KbXpfZOMnw;3iW zThR}pgB6xkD_*&=SF0&-pfQEKbK}uM<+83!hKn&zXA`ob4a4r9^nq?3Y|4pf?{K20 z19Y*Lv1TLopz?)7G&*T7@aN={rNjWPHx!~=IznjC zz_7BLqlMjzgCaBSNpRKXkyLMw1kW2E`LrPDTS};)O zg<>p{XXpT}}os>?OC$Y(G*gh$x#5eu@C!JQz(52DkLmvI(jE#8r*PRg-W;JY%2@2)COb>{vCJ^-I*d3;EO{q~ z&;Xref6~p=ejKeSU}G$mB|1*olnzle*pkT?Qn=Qft!W|QSlk4V9R^++ses#(nIf#i zp{)^Nuzm~z7Lm0EP&}G3HzQRz-0IQjKAXr^i6kBJXtPBz&~eIBp@;G@iCJ<|3u6B% zlxgUQH35bkr;=7>!w&|A3K^I44q;8AKZUl=qfJ3FP#wt6VR|RsgDUSus0CJSH z0f=2=rIL)5Bp*`NZmkkXRm-WWi87PP7{+-`oeX*~w6!A+Z0(BW7fJ_b5mUH!5fl}* z1F*~xmY;I6=s65OiEF^eu#1;Lg(DBit)%hn6^(GEYuBP?qNbwpVWnQQADkspP^p>n z5vP7sl|o2ZM|7%eB0dU90k)Vnm&u8tA;ErnlH3?o7ADAsgnTz)l4|J6(xe9{(!^n< zDFy1kerQ@IZ=5k3y32GgYK*N^+yDT09DN zteNTvR3Ry;0#3mUn{IiHFWbBOll}6;1|Gqq)CPN59nSFjqFTo;Sq=xvm9yxn%+l^J z`qKr&d8sFeM`qxXa?WbB56TgIegT(!Q(@^RH$$<}EE*b@gm{wDaVlKYAuOyGWL49T z8e+IU)H<{BI)^<^Y!Qv&Y0#h^V66_zP^)e++=$G_{$jJN^vrS}&?(@6fM{qUfT02{ z6Q|uqrhDkMYXiy$Ni5p}(FSdeWH@z4Zp>4QlD6Y2R|!NcDn(HA@L4z=L1jZf(jY|= z=C#Pt1N|tAMQ=$?f>U4)GPq#cFzBK&2ilkj5s*?U$x2T3wa}!30=WiAI?)BkC_{qY zN{1~91gBrArj`3z5cyXUGY843QmiV3td6JPbDR{9W7HF4#I6;nXGM0vP%!4F0mIVTzseLp}b!kVF)PCxcsbNl87`g1P57nlZ7kiLh zJSu2aU2+RLRaupisR?+wG0GPYO&H6AGKDOrMyVo-a&y5%mS~!jxD&rIO#FC+E&6c znJmDidiYWU+}fB!L8Y0=RIl09dVn5?aK+%a77P&%E6W8#L?Mzbu_6!Ic1h9NV$Gy2 zIZCHxlKD~YAcTRMCe_lbd8bRT;7gZ zWP_k9O#u=f8$$SH#9eFJ+$``L!`a}q#gF%x63kYX__^AUw&KJPYCH8hA|z$jsF5@~ zUio12WM?62oR$z&(MzD#YB~(|D+nW^P2lFC!T?G1mtrxRA*zzm2 zyNku-aOq$&gHatM>7aZCf#LLa}# z1wo2hy(QKqP0;Ug z%es9A@i__JXwm11THRwVcw2^FX1$j2?k@=ue`2Oc~$xyk0RZkQk_a1l`@Y`k)=30}?~iE4E?atk^U6J)12ts@TjOj6SI5lcQCpp4-53NI^LY-p_iw70;^obd`s2JEhouXH*h zp$@GD92`4(rKoJY_WI9N>K?wVwj{eetxXjia>naF)K?O!KfV$uVV5Vz`X6XbD;p!p{L&)+88B7P| zh&aO}QXRvvM%iSgI;P7@+;ON3=x;@;d-~6(qs_6TX)QYkTbpMfte9rW9g$$JNy=+*wYN?oRTkLG?~=GGL*vE=S3J?7dZ7i03QZN4 z@3YYZ`xv@6VJdn9d`r(#3l|<(g@e3-TiSx_d1piQUS6W`8Sy5xqYdJmgEf#)!<2t; z^gx3JUj%k@6%(YEjX2G}Q2r(#@4Tlc`6X)H07OAP zE|8Q*sQa;ClXeb^+!haVFoLNpUC_j|SgZJc&Gu12#NNI+>~JhD4cX`*Hcf|J9dy^O zdSOZTzFvg;cA^zQkWF#EJ~b_(V7wkX>H!hVbniw|pO|Kw^sv%2v5d-CllwXpMP{gV z89_=@-mfov@`OLZ9FR8o>E(10ySiA(z?+>(CqWN%kjOCDIUGn88skkt%r++CdgY!_9rDuXo{kZE&F#?fA>P=R#HSx|O=?d(` zC!NkB>rev|yX#U_hzARX31YXRoww#J)r znsXeRs>Zcge8Ez0+eNs(f=-$S^HF$PV;yA${YptFj!h3cM!GPnOoZ}2sjYbN&!f{T z=3{YeE&kZVN@JP$^z~R<<4xWeZBb90hFCxv=}NCMampLNd};KGdE%2IZh;ndTOvw5chHK?+vUeT(`$^|gT%x7{MW z@p@{jjI+lxR>ul}7z(>3(d6mN5Q!xbuPhP1gs7Xt|EqOFxBH`J8nnjr|B?45U^y$9(SB{XReEex28LUe|q1s7n89Q-tXST)TyaGX1C9 zkh)$={}Imczg>E!=lD;F{k@Hg!vCNT<&g2x#~PerqB2-79ijf4iNtFri2iqTO5f`K z<4Q=M-K$bf8%Mi7g9nUgGI;QS!FDJ9x&RxQ{)SSu#=ZA7ZlX8+>Ap^z``X>-UftKE zU7SL%-#2Tbx@PcHEI3D`3uI;e?`G)&H!RR9b^YO>dSm-(f&Je7MrVmPPUBCo{NtHr zsPWgn9$0;+{Z-Qz_cd(LB0j!Ze7C@`!F>Y_t~<5RGf#o|;RA;bF2(7E-gY%izbDYM zu2JIpqQ_wU-**k~)=w`4>}hMkea7owz74UTm-u0Nf-9kCFs}dI-c6@>3hKu{ zdS-QSfRe^Q-Oul5k5}}(zG`+fwK>A;L)|gm54Ri8?tb-kO|m`b-_!Z$P=2ugR=z;b z;H7_jfXc@Y=>BlJ7}8^K-+{Vfe0Yf6%hvns+@msf?HJE*yRL~mRBtfSPqT)k2kFsV z7oeZY=)QV)dnKUy^ig}fZD`*|hxuxtO}hp=FW$P$hIhQ)7C9vNJ0882Dn1aLmI#aq zebczI*@4iEh5avvM*d6Xw9Z4{ZCG3vtxAgKP#U>no}3n*S%OL zpzX>MXqPd>f9scRKH3%N)o;pSNI=&#?hV6z1NZ3#gM$MD+}rN7v(RHo`nNX$o4X0^ zkK9R-|F}xu9{v+5{>%BaTd^lt6y(PY4DF*Q?CnD@EFByeXb%m!os2!xVpZy?UlIn3 z_BTqsIVTX>rTDS*LPz})Pt$?6U(?n(WSAZz^Bd0+xw_X*+CIPv=s%>l%IGmXFho(^e(lyw z0e^WGzU?`E3_6wmxs!N}GrO=8#QW_A@e_#m4g7<65n0poy!M-y#i_~gCgPR7LHy;! zD?`2&h}ZB2@uRZ4{M*B2Ih@`GudR!He>s~Ac@zHI^ucuBll}_KOZf?KAk0{P1L`#b zo`qL$P~TvA8S{Uf{Qqr!r^8&0VkmDud=8#~U&D;`ADhdCY=sl@IK3EVjNdY+3uzDk zZTfPQ(-roioF{HjUa*`Ml=pAbmk4+D?Fg4p&Z{>lFIY|l^?L_qC;h+8FPP6Q8S=?T ze!buzn6bY<&+S4gQ{Q;l6SmLm{9Rzi^x+XMq#^wECa3cj$QaYfhtKRv&z;X80T{r3C~`Y+f|8QYsg{r+u!{V6vQegu!hjQ#fr}$iXu+G2{V=#Nxa+PzfC`ybkpFsutuSbB{?1R|3JKQ#H(_H_`!I; z5I-32M*08S_&INO^@@c%>8HoeMA9f~Qj~m2KCEf|xmv|%o zhxi9G#P5HD_zf8sBVqqr-5MGNXTf|7Z$4ZGyHl@+ zZ&1H_MP2%#a85C&H^7YTd5?S!z<-;*2<23S1r zpQnV2e;e#TzVSE6KbY^P|1$m(>Jy9~tp5=5UjUcgpuES1xeKoia4Y;Ay4t6It{dUv zAAlEOwvjG8J*NA1H~zH$GXB+t)5j$x1+q-=vnwCW&b|zk`Inyy^<})QzFpH5%M=J$ z+k8(03G;L^&n}6mpyxE65$5Tw%xygRX{;nmGs`^Lvs~jTC1IX5=2;~%TJ+NtS4eRQ ze`zRTXPa%sOkEHIOpMltomVHDcnY!9#5%-lCf?PDWpLcYL49y8DCHM$b>ZP8b;-RZ zO8OyunIeW;ob|G*GJiR#&uE$N$t$;2p`@6}F6RH1_fJm*vV3cq1mf+(7W+~~Hb89- z%#ziV?TF_JxBG$>K$#KGZJ>K;Cp_NunWT&^Hfy_-x2imm57q4Yn~JdtEr!6 zlZ2Ji-aIxPU{{R3=b}Uj34h5iw>2nA%oK~b*Te&e-X;d?!|Ik|;t75Ht=(HPXL&&x z2LiS1!xsCJD*HjJAP}Y|Salkis3&1N5a06ilY+`y{NZd{1Wy>#D!ZGhgD)pyy+Wk`lRWs^S+3Yqp;zlj4?>@R#xuq1^74uxK5` zOx+PfOpHOyH1Ui+?pHKFw>-+<>Q-IM6p5%~!X`@!`-SL3P0@07;Xn7=qw?LR=z*0o z>x1bkB5+)`Oy+yW&~N_cv_)cw%=eU0<19@n%itl2iorBfB&=?A&11b|Ep_EcSidzf z&nXG(H{VlKC6|xpLy<;$RzVU z_o;$bgQk{&?Rl&{zUL7M>z(_|vs$8d(DS8)^-gE=WL1{d9zRV!iAoawQeVO@$$U>M z39H*kOEXEr4$8jgB?-%5mze28M4E{+`mlcUqs1$sRdk@3=`np+nrBT+#y9#R8um4u`iFvCTPV6o|RekepJ5%4$2zIe9z4cxjYuFrNoOt&lL%)k?kJ>xs=el z&QD|AZC&@IdG436)#Q7oNkmCJYo2uywukaPTP1Fn@R!ddLb?4SVU5kEG@0`0!$b)a z<@8}4HL6St}7G@uhj*m#`zG@A*!`(p)xA1ASN)2fV#ugQOfB^BxBglb$WkPy9Japw zixFF+c2M+}YtKG{sgFg(O}siZuOEE1QCQsgU16ObdM9qWt-?UublXV@ z{^)qEi+xYo9hY(-F6F47VwRPAT~76;G|g2iZ{C-8jK7q5Xv?XM!Y1w*)BWn6lty90 zipEX#TNRgb!cQDGwUG+nG1Nt)Q>(>Ie>}BC%CCNvTBtu7j2{~o$UAY4(l(pg)M}V_!bXWHak-Md$eXnD&%7`1 z9shggyyI=;#7*rK7B@8}*s*aFj}6UlZOR=tHCNnSVMA{|yUb!uJeGIjeE-Xiyc1{X zOS7qC{f^J=7u#%iQ-6%L)T#(?HZ^eAq1I zV6&88Lfh2z$G63$yysV!I_Ii#HE!bGp?Tt_RtYvA*6U;D|c?6m=?>QqaQzcVgn5B(TgG5>93 zzfb%giD{PdYqONA&360u09{?DKfdw${s`6a9X~>|lwHlH*0e$A%l{m1@oHnk94tj%LjFzrV7W&Exf>pi!n_%#2GpX+n-pZd|`5rc;H)y?{- zZc#iVpqG@|n@OYeJe2=?FZ&T!l>b_bDE+WS@p|y|Q&cZ|2dMp@9{0cDq7-g#gjPsY zuWtGWJqg$5u76}4WzYBMQGyCl1N>hWb?awuM|6)K1WUCd{$9W}wY)ALJt+|7o;`@_ zHF!Y(DAU(9yA6*aMEU=_@Oq!?rfVu=PdG%`vl@Ow|Jz#JAhQ2(m;2xAmG4)^Ln^n` z3x|3Ru3X9fi$}%YqXt%vsZ^zErI^Y?2KT7!|3@MBIyH??=)f8@kVbHl$wd+WPrPG|#Y9h`KJzvRdiA0%KfEf7E4Y z$F&7AQj5FlT+>JwP_bU{K_36r8I9~;6RKL)$V!ze_v_oea_}jYN9iAM(>|@E00El)WX}Df3RvtvI(~-a!wa`+mXsX_Z=Md+Xzat#_S!`QpSC zpPq?+VMflil|OHO^NIHgRonggs>8`UChUE=(C_Dl#`mulAd;Dg`C zCHLF4aB}>RFDFgh`tZsIE$22Xx3}Hp`=5TPNtxHfCNzHiv$`MG=-z8z=kWO08JTL2 z-H`dzuvVkG4*fBFN92@!O|nPjT2~>tz|*B_&G~NbhbMZxfAGjn4@T9g@#EF;1NVM- zDe?0mi@NL_wsc0vVLki2F*asIiI2itM*jN3#6Z}G3sd*s)S`IH%y;K*)c!=w^ZDQ1 z|8k)TQ{FGuWnQV7B_fk^{Wbe?<@LFLKC*YCMod6tx4aM$s(BbE+( zrr)tE`HLnk|7vSYpQ>J-*RyW#9G0uh$USc@Ih|0b;46O?xzP5-sFS_tRv5UnX84m` z8jKqBY^K6h$5r}q#rHoP*wTK}{tqvOADRF9)!qB*75X-^#;n$6oAE-e$zwq5>8*biU4 zoc&nJg@Zk}ygR1J-WQ)4@au~2pJ`Y3fp*WvPX4Q6N~^x_#$4Q(I6AD=>5d2EzntrR zbbsol!*6yhJ!IsMMUz{E|Jp3J>w z1*Xo&;PkJXWTpj-YH#J`v`RebfDXZ(X$^T&L zrIOK4gxx!H@M}LW+uY;(a=(8}#ELC=&>AUAmMxKOl_CR-%4d*u6M$7Sbb1&XK-WYuMjW$k1MvZ1mGvPH6W zvhA{cvh%VlvT#i^Mag1hv9eaO`_8)Kbe7ZVdoAHdoh~@e>Ce_Xoy!hnTF!2A`hg8j zfAy-<+h1_Hrp93=eLaZ&;wg9B-=c%xmmAezTXkGI6!2!>8+(;mknb>)C<8Cr_*1a|3~6^K^_~6bKx8R(B7VsEs;Uj(A=- z5LW8=zA6wXy~gFc`Fl6ZwjoJ3jAZqm(5$=cfXtS<)cJerm0jain|xqOiq_qfKw$Ed zTGwhvyvqA@K_D2qHO?*G)CvlLbRKbAeB`g_T$lPvEv-4Ibb zK2|%r&eA!L^88V48LhTto3Aot9o3$n)t(khbZ(~J zVr3tH(Um=f{@l3E=~c?l{4e7#6{j1r(s!#(52{a_t1oM){Dlj3zN9kK>;yy0YcIKU z`CoQAFS^(kr)M2?{tAqdWlC%1yrO#Al1=MAhqzSh@guc)_zaE7IT~-z=sZw;H%TWr zC6=m7+{Q0u&__cPx(J?Lw9 zo?1-xFGn99rjOrGba6_NW{%?8@}$bJwgB|DvP!L@O*`f4TpaOXj{jb_q%`b_=2Zi)Jc zzAZ?5*3sT^YENcmwPmdOl=UC`FW2|lv#ySfwe8qai*Y)RaoR(DZ)H@_x;(1>wdJVR zx3z1*T3-fUQMkqVQgOqyu5Ia%q3wg^%cAhYid$Rto~m_k%ajb|_tvd;#CwK|kJVKH=EQQVC6Y`@vX3GN^B(YD}th{@ynI$8CZ_qo1nJ@!<6 zY`Iz6h~<}Az69!;%(nL{+uqRsi~E<~RX1yIwJ)u9sxM>dn^{ipVQfrNAK5bMklXG* z&~}_-dLXc2hK>VjQ?j=E+Df}w+wFr(b&Oi=;{T;^TR&|yma-?QugAIY@9DF)>IYjQ zwe4gVqqI+`K2_I!+Hd96Ha|@JgM8Zeyr!{X%Nq87!F4!I`_ilmFRlD-yr#))%zjNd zPqDq%*7&`f_5R+S?i%$WjlKJ{%~Vxed#OH|m+N|KjbBXQy;`ncy3+2d)OQi%u$acE zl{;4buzH&IS?YtMs!QMJNY6OUcFO5z+5Wy#f4!wXc~X7!I(>ANxIKtl_h0sLL5*Xp zOJlY9pN_#p*cO7v|J2)E+j55zv|c7m(zu$eW25Zj6vffl+N`nFMdP;4OpPtsAsu_((pY;- z$DcJCZ{@Uayj^8Yk-aUuUE?pW*6U78rfM6lU#9l35#T$gG{^W!BcaXz%^(6MC>uXs+>PefK@< z;QUvA&)>EYixb>`7J1F-;Cb3i1&nUaD&BAzi3BLM4Y8Gb{^A3 zX6G`4Wp+N(LuThREoF9I^ODTYZSIrV`OPJn?R#x}+WyzZc~#lAG@Vz-Y|Pp|*~V>f zzdY|ISC4D=%axPecr2rBHj}p5PnKx^rFCq}$!#wF@)vXtF0eLswWZy~n0kbE1jpmrH0QVDy)C2IhOXUr*U>t+Jbu^qVaue0uDpLbulf8g z*Dpu49{0~uI`!*f?c?uR>(V}4z@`1C@qdJT|7m}n^($A0;QD%x{aA4S_#E4nZR56m z+qNCtuB++%$LgPheL@cPNfv24_MhIW?c-%vH(P%eZ*Y>+1GGMDJF#n!;JHbUa5t~o zS=)(iU;pOZICvd2Qu`Cz*6L1D-m+<0f48f@w#e?#SlT;15cos;$pz}aJ2jT`XlyOh zeyoy?83$xTRnG{Gv!P40{Vmf&Fwbj$s6IZhQs?*DRz|JSIgk2#ptg}j*6So~3)Z&a z`D!n%OVdxP4{XWP=)c>J`qS^hz`BmHJwd1bjxBuPwRyB=J8+UeX z5ZrF()N*+R&yA)XaXL7kFiGRW$_k$AkIJx*$X(+98^`GC7hPXwJU4B^cnn?(@23y0 zJw`QVKN!3wd;Lxw$JOTllk*zEYx+kUyZ&sfZQPdDrJc58nk^4#`^qZb=v;Iu?Xmrf zEhlvxvh@?Z-d#cdwjZ%&c$^y>cHFgNt{rdfSZl{wJI31a)t28ljs>ri-%4}&2Cvl` zUvN5j{#Q7|vE}2NoIiL@^9%dN;C1vGw(lm|E^S$({fCYHjMsW)+3thKsG3JzzQMT* zy9T!Q2G7OkB)a~((eZLC>(b^{MtE$c?z>Ko=DS&meKj04j!jo zVEYSR)Av(4;6s58H71VLkmTzRH%i4#Q z+eG_%%vQFRM9M6!GHeOZjW%g5?xKHEmD4|2$I%B=5l z%ks)1WQAn6%8JRNWF=(U)ULb#SWddUEJjvMW=+zj@85&GOLRSb^{Ng%{u6`s#72Z` zGYd46wLrHN@0HyrYb|Rd3#Pwc-#f@U${vt)lEurq%MxV0WPN0PWe>~x%Ld2>$%e>A z$VSUF)B|H=NwV>>iL%ME6q%K!O+27YJTOD1&D_6FsZ-s+e3=d@ejFWg0!#S5RD52x zTDC^EPPS2Id2JSL7h|h^yKINd!ru|!m3<)FFSFJ7vFwn{{5pIDj>?`#Vo3GM|kV6U%b+F?L@mDcQ$9qBl*UCQ}RH`nBHqMSFQeA#}?!2 ze{klrOXmj6E1c)E(xn>xR^-ZyPZjMsvdK5!mWWThb$8Z2&n^4#=#vNgZnk@m#S(ux z^!CDA<7>X%GknY&x5xanqFCUk!nIy&el#g*-NdFdz5QjL@B3(jzYaC*mHVL_uXN5` z;==~t=3aO5x!W(No`3VV@|E9Pdgb{0_w9ai$yc*#%=$fT>!$MK2jw16<;hcfrat`G zu&FT-)#q=Etygg0M;&fC-eP~m_J)VT`Ud8ERd(je+`7Q-I$zg}Xe)mr`Q(SDjzE zcW$3kFVw94vz}T0=9Ca((`bhYB}y&JZnVxMQ5A8SpU~M&RlHvT<6H+4?OwO(}{cg z^?9w!iS8d4yV&-@5BuKM=93Q1hd)>TaHojy;ahg4zTP%R>?{=2)z{PDye ziFb7`*!9kYE7Sgno&Vrp6>@Ex^6s|po_T)!v|O=$UVW@rjkTRRC7wR>=E;u|_5IMC zQ$^pMT;j1WvJUE%zuTY19u05z-l^B#IM%Mq@ZY=*pN9WYYMFPU`Mpy|XaC_qq0Wcv z_lTO4_(o!l%hR82{@mQHgL36O^x>gD#(!P@vxD(58-D9HBYWG2hi&ZMy!5(dm*Wcb zxug2xqiIdIR=Vf)k8;+3?bZ38^tb!do8!AzPutVF<*t(re>uMJyN~uiRcG@ru`w;$ zf0%UZvk^J(uzTNazL_|7^t(;wKbO`fU;W)r5^3+{Ql6Hw)xgScIfh^ z@?}=dZTsQD&6Rh3(lox?)XNP^?ascg?WCeH?W#^|^Xl^>tB;+LIro`)ANJaIv2g7T zhoU;w{rwhk`giw~oFR*u`Ei5BTTi~zbI{MHwoa*%qlta5y7s>A)xTTvXk6Od%I)TS zTPugI&t+X?gJctA&&bxw-jLb7)KjuwWjVA1E-I@mYbd*4)<^c3Y=&&9Y>RBS>@(SA zS)N?F2PCU5yI0mtHdHoQwm`OCX7^V=k$o*Is2zN?>@L~8vTicFzdBjAK(=0H_g6oW zeJ%T4X7^WblU0>9k#&?kA{!%nQnp<7itK%vz31VgEK438J7i^Lb!7L+y32;i?B44_ z*#_B8*+JPivOi?Gb>NATRg<-o^_Gp6O_wc^y(D{2c2s8fVXw;a>p*q8td^{~tcz@r zY=Z0=*;?5fvQ*hA*{`x3`PA1kdrv_tSr6H8S&D3}>|5ENvWWbei;~rpHIsFg z4UmnK&5^B^+1&X7*%vaqXPaH;az$hnWwElhvR<-LGP`g4oNTk~UD-+5kFu-<+`U_S zZ$v#=Ynk1<9U+?{TP)isdq;LyX73lcBFkG)$7Wd#ncc(fBzsi$gv{>Yu9Ceb+b>I# z{Upn#gZnMA3bOjLHnN_wk+P|>XJy-DAIR)?+CRv=n|19fD<`WfYbCSacn_DQ$QH?7 zl)WuGBs(L!EXz|^<5X5%)>QVOY^ZFqY=LaOY=`U<+1Ik)W#PAI+{voSn#elJ9+8ca zJtaDUpvSYHv9o+d)qmp*cW@kl# zvYJk?Q>{{;g?J1lE<2Ace>&Gfk-v!;&B9w6N$1Z5LNM6+mI{Zo~VYo(3dKt8;ermf3&qM$!cj^{?c=(- zSREom36peMXO)Pn9SW+Zvm6WR*DVwjv%&?PPp|5@9WH2hdgr7}bU`0J6iV3oHWyU8 zaww=hy;?Cf6jVaZwGwl-4b}eS>+Vdo>f3%$qXRzXDvgGtEq}@^&A}{MXBMCz7k%e~ zHoqEb@$LyOs6&@fVR?VBuiCyY__6jY5n0+yre(Q1Ar$$-QWw;IWGL3)WiBWteT5`x zH*N_ZDjG_-TBoTNbh=n5=ue%+S~!wN~e=z=Pp55-#ioD2G4aHzyr)x}wr@O=#@ zRrMvM7j9Q8g&qzo9TY2&Nkv*Y`O1VcZSj!{`aV6@=0{x6qsoI}+j*A@dS*wc=n8dQ z&{Ow>VkPxg5Vy)`tg63-Ud2U0oyHQpN)ghSu;$K`)k?%tZCogwF52cT*{EX!M zw}fJCsOw_&Y#GWcS2Y*ZxN#`xk5(?IW1CRI2Yb4p^XXf~tIxQgFEwmv_5{{T8+8ur zrTfD!R&@GySbDe%%Go)Tup^!GvMNJf$!x%V3xidsiqZLDwwSIhWGw^`lmU z1r;k7>cVigio@v*8du!K+LkSp*I~M_WMZh<` zt6?bUER`snKIE$vbg`gx5#LBEuUbD_c(v*q+qHZ-p$ReC?YN(Z&| z`JJFDl5;6WRoL5pUbWo%eqY-Y&3K1>SmBnTH2HpX+4Rs*BAcTd?W@i&wc}F4d*mVg zpQMhN4Cj-Pp;9)JFgZQpPL{+rzS))o&`)O5O(4PLGpp8pi(7_R*p!=1|65gysQz=nP z@+=n=-ZeDB@7>^n>}UUEKj{q@bZmd967fx4&=dEDf?m4A1=Xz|3hMK*3wkYmpq9_& zf+nU{;*2&ztJiDkBdKV27qq!us9qHa`k-*AUbX1xg!GOcMNdqO3svIxi}qC~)))Ma z-u7K6{R8YPJ{=eeTFyXkntsH5ls)aUMM8CXhu!L*ssKYP3qw11VkobxD$v?B=he^} zZcMDfLqb7wmbh5Qhlhd&-{OMaDIY5FUJ~kksKK?e<82o!mj)#(sw1^ulfG{sr4?kA z$X+^B)%PgzJ(WnpFDkiM7aE6R*>$BQJQWoR8o$g1-JZTHdSJW@>a5Lxo`}}*!V?HW!o-6KYWL4KC=`^kLSOHdadS!jk0mY5Hg>$jRWN=|Okqa(Rtb5DhBT-UaQG zrd}Nexu7>YhJwES$OYBbI3?lCXI#*@uAx|)G?uJElT>^1D$>XWRnu@I=vO-D#q`c; zqj6;k?X`8ps;ym)1x2JE*OHaMf|_*>#oEZ~7}+Egbb_Nyl@6hxDnHm)9ev%v{`|X8 zBkWly%Q8kE6#R083o4`wBsTs9jFvX(WBuN_F4i0`lyFZ`5=MuDnufWc_UWtO@DdmF z`tVRCGWB#pY1)SA+*J!)(2B01yzFr~t7^mUp`d}AU69^K9!yxD&b?cG#m@3w8k8&j zimyrom++^Sp}fj4T6&}pjiTgLWJD;hY|UK4a;-w+bB9)t)hkY&MHku=v=)?C32D%; z9ID>Z#zL%5Uw5&lriNn8{=fwl-x~_*a?uiKv(%M|8uWbnx(nXF>GXIg%ckt7z8n}z ze?m32y0mB$3VQIA3tFXqr!EsWxS%Ig6y5e$gbS*eJ`UQkI-95WQT^v#tTgpEqh+`{ z)k++wlF9zriY_Rt4h9768|s4oOy9^xv02}pzFAk$W@CBfR=<<*ots_IgXKa&rAYW& z`uHrg-NkwE!*_0GrXC8 zJuO{l*%G3aw+_-0HZw!I=Hs(X3#HOro8mkz>q9jEO*EFS!~dLapW?+3t#MWfEn&B1 zNcRu*^i;P?f4O*5gXz8@;6Jplj?(QQ+6L{a{PJG>pVJLhx@4l+1dyL@M22)3`o-2k z9qnf>(H!j&-4d)HvVxePc&WsDj_}YpYI=QtTfR>#esDcC${4@VcyEU4Xz{iy-pK!< zd|Q9*6t5NW>IK_ZpMYR}Gpq;8-(H?mm}pZo*5mH+{wT5bZBhOg>8=693p<&i|C*$4 zFGH1Ya6SE}e8UxQUdDVU-#FiWir)wK;{Q;c@;&pX z>#$Hid`dvDpXmqdxATg>4YzHZwuG(v=lHfh>_vUaxbyk3^%2Y$ZSm~2eO-x{^9J#( z{Cy&RYZXK!J5{!3E`3DuREAjqg`xUPi@zUF$p?unJ+tDJ$55ujQ3x5gw z?XqiVupTY1-|t$z6SOZ%C7RA5+!Bm`O}(cn-s=A$p4Fq2;w2H!KhP;GY(R#3WY}Mw zDx=c?O;CLX?~7f;x5Wf;9eiHYMNY+qqK@empAvhBlf^OOaM98~Dq8wp zqNQ&M8;H}T?-X@vSFy5a=}L)~PhoU+ak=y_r5)cCwe41XRk7l;X+G~l{-bWa>t2QZeRG2Xyx87 zTDi?dD>qiOa;u|Dik5#qm;=7ALY64}4N-rQ^Ymfm%@VD=WHCV;0DFj5UMJDYYb{!N zcZ*hDZFE_2x%AC2FH9}z|0cfTZc#yz&x(G(idNnXF+m(H&Jp{I6U0uU#cM706k`dm zM0hE}^NS1R|FML&56wE96D_|3qUHCVsC{9@^`hmwR7@6Ui`I@5@hS0fQ76$Adx?o+ z7cog}D_Xp!;&`!|X!R*0_7`sz8;W^Fi${iqDxm`sox3y^HHW4jetZ3y{K}U-^Ev{HZwDp%?wDlK;|Mw`} zlb8NhRFxx7iI&eXai*9mP89cu7Vl;J^Ti(0Q_y2X>-VN&cZF9WyqMTcIVlufk1mh4`%e$>IueplIWu59}&-k?trah|NUnms+B&?_0%Z#4u6&-pEX1 z4)Kp-{<(JKccS@^i3JsYP&EI3{O^fY-m9YJzZSh1og@xZcwcmD(aLWk+IqQDY$#R~ z$B5CQt(T(co5Z!!VWKV%BJK88Tk+RO|GBG*--_y@$m61_9=TmiQT$EfTyd4yNSuT2 zE?WOSBwGL8D=w2RDh?6DL|dOf7Ip18D~^>uA=>&qEZX|rEvhP!JH#>4+u%#0t?yOn znc@`bQKI$FK+*E+DO!GZ)6nv}SG4?^ik4q}SX;FGDxvd>eWbIC-Nheo)v?pIW6{!` z60QE9iZjHwMN9t@{zYOZ>8If|v5WKs(dsu0_QKy;wDlDy+IT51+IT1|+IYz)+IYw* z77+i^G^F{@i8fwNi{}4aH2-0-ll*%{EAKV*dUT3trMH_cJ(c45Dck4wPcPm93 zcMHWe3ZE%z6+}KEs_Bv4L>qVQMH_c5#71Im^y$KG+?^C{+@*>(?skf^#dY{s;h%>; zMSN2JG2$$-w`lR(h&GN}ik4qJ(ekS-TKrO?#Xowp8`tlOHZB&3HXfUZ)-QEL>)$G( z^>10x`nQOvu8X`$wEoEjvx(Nff9OKp!tK2PHXc*N?&46<#$$i{_H2oj+g`NsSW~p} zztG^Y^6fnXR=z!>V&%UpTKO-FR{o2km1EDc7?+7w{#^7UqLtrOwDOyaR(@mrbwn$_ zqG;vcB3k;K_%CQsc9Q-IelB*AJ|tTG-V<%yY!>H;&xsa)4*o>(8R@>FZ4cc=8}FS& z{YBoV5A)X%Rb*rh(fpM}{Y941hvip9wDNMH|GLTPFT`OAx95e-zh1QZJS*Bbo+&mI z$BWiKV?-Or1JJ!i8^@hR8^`yHZN+;;8^`rT4VB0kQL8pGLbP$5Rh%nc&hN(YS<&_n$}cZk`9(!lC9!WBqLpv&8nN)tMJxYf(aL{AwDMoZzd@X-@MWTvZ_mtG`Z1!V?=IT-dJwh|yGY+7 zTK(=4Z9J6`ZG7hxZM^=L$Bk!uM~aQtv!adH&qedUFWPv12mf~bTSY5xwP^XzM^8gP zjvk0^E86(J1AUul^@$K|d}k6Hioa+OSbOX_!$-w0&__iZ-v`7ts?Tn*t+-vZ@x4*h zP>x(CY6wM+6K#Bt5N$m77aNJ4(4|Eicg02hMdsJXGU+VhZ1KBr=RYf&|1;72ABazi z_8jFbagu1`aKT(tPZMT`HaXz{y<7QdNj<<-U? zDcbldD0UHZi`I_I8l)EfgJ}9o^byg<({9nm_ZGtKSzL=}?>I6h!XcvdM<3DpqpN8B z(OT3hh`dL%dNzc0MXO&GbTQG&%P;m9vxyDGKf+wPUqlzha z@xP7#CH%`p8_)Aa8_$EpDPkwl`m2p-{nS*neyT58KgEdFPh~~xr{b`vX#Es{zL-tV z!%A-!E&O@W;!hQAJ&qS`{n`uPt-Ri%?RVOVTIG=~MRjfD-J+TrSyi-nxy3e zw|{_O`gZiK=x}sq^iQ74=d5V)KSl3HuYrrj(em5BLg+1y6Rm&!|Hq*A+FYR3tGC!n zx~pjIY~l3uCZe_XF8ozQi(f%Z5KD?rh=oPVH;1S$i_9#Jlm0P_3qK`V_)+l@g&z>D zKKA5QKk;SpUin`XCrK|6dx&=5!OEK^CWzxjD{rJ|<@FWSC6V1lE3XaVjR?O}wDRm# z?p9uD(aI|%wp6;jqLmjAdx$?|cIBNHt-MpBm3Kt6^7e{qTIAc}IB9#ky@fwd_(s5hx}ud=QEaYs_HKVG&;ILym6uht@@&4culP&AmGiZzpvaS=`9BkTiTlNe#kWPv z_a(8l;;j=c-YU`ZorfMQ+V-Zgy!_=v#jO}6t`-Z4T5Pv(zs0IJ_^ki_qiheu z2Voo75Zdqeb7|;aIpg>n=!>e0d zxqIPGxC}0ULt#Hy9+rgJ;9uH6t)Gs=gYYHz0?f9_#rtccj-+`~gnQ$`vdV`C90v>?x!8LFxd>jsgyaIh7zwYe zcjf;KKZfr^dzXUs^HMllwC#He>;UhBcfiW9Aj}QF*ACUve*+J}{qPOA6{f%^U|ZN6 ze({3K?RUK_JtkbeXtZP3eT-^=}*B)a187M+rw(G zJhYQ$>z_-j9rwT;@JW~gAAqf4PM8^ytP0D)(+gaF$6+*#f_Y#zcuXgKnY2BB z0++)1@Ge*l-UM^OGdkh4^l9)JI1~1R39u?G2lGLDKau4VfR}VJYI+~s1?Rx&@F93V z%mcH*Z*;L~`J99=!c}lG91Azr=3G0t@a3JghJHl45Dl7+!!2Iw_O=4JnpTVc$ zH2Cu@=RXfWgCE0H@HyBY_JrBt)tN4zlkiix1+IhR;Aq$kHh^Veaab5ez#nJ0a=wMH z!8UsD_jpBgF|3rSO*q`1>g@; zU4CcbTksV)7LI_uVLWUA?}X)G3HZ|#m;X7qAHEA8fjwYb*c?`bx5Gj(4?LOT^8XY* z17|{;ytDCmDcSLBcmnQ(ufk-Q1gpYwFdxhTzn$#z{Sv+dUx)MIlW-&)2wTHuupBG_ z?WHMx{UK;+=-a;ZFD}d=}1ykHI0Z59|t?z`C$1EC=(# z?C^XQ>H+t{op2?57LJFH!LG0)tP5+vA}~MvO&w|d^*uZY_rXnY4V(e(*G`u15!eI9 z!B}`ZjD-1NPI#fR%jYY21g65Ra6McG7r?P_1ndVBU^CbN)`XQ{Nq8#^z)O`}y^g_8 z;5KN#!Ls(xfz#nQI2y*o4zLca4sV8e;m;LazUSdba4*~dSHh`qJnRFz!X~gTECGwa zyf8aFU%{1s8t#QV;Y#={91kCZU13L97uJB~UeR zN5BCv0d|HB;GM7-ECer?apnI6kHA#86|RS~;S@L)j)0wEJ7~{i+xn^k3&A|_r_!_^ zrougNJzN2&z;UoQjEC)D3s?n~g~ebYc=>kP5060Jt)6WwdOchQ7r?P_1ndVBU^CbN zmWIV(7I?Xot4A6<0`0kN>%XmV0h|p-Kzn}M;}DS9lD50=L19a0OfpXTvGbp4ZN#{6@fjFab7$4Pa?l3}%6sbt0BY`CNo&;C}cn zd<|}f&%l{*DC`GY!)CA&EDdjkH^ED{Q4jbD`~Yr*tKoDw5k3sN!=|u4ECq`~dtTex z{d+OT6Ywy69liwT!C7z^><`<(dthZ)28Kfqo{e;RrYYCcw@x7S@6lpgo^$`Q(6^;MX_1@Dq?9 zo@aX7(n0B6F< zFcI2w;?|D7up6}J#4Y?@*a+SQV_-Clgau(vm>GUk(B*d$?tFiyTmVOu94wu6D(4HT+c*9{QXz#JK@LJHG7dKrH=7vA!cj4c{58-ZT&xu>Q z<{ z1oy+ua4nn(C&NTI6g~i3!yYL+)jT9KZ9>UdzY=nUj%t~T(%VS6R;QT0^7poFa}1$+%PNrHk^9E z-S92A94>-Sz)`RZY!92mM$q2#Ywd`FS>d0#C>MSP--55eMeu1j3J!wpp}lw5%CYCe zjl4K3TLd}`UdZYEU%~g`+i(?p4o-lHup4{;)`Kk!-zH$!{= z+x#=(WY`ZTz-F)kEDh~BZ%dyAUJi5Gp69mkBk&El6)u3Y;RrYYwu3ET6<8MLf!Uxv z&u!(Mf_vZ&xB@PQv*8pt7LI`ZU;=yqwuUufC3q9e1?{;@lz^;&7wrm#M& z2Ft?;7zY2$?CSFi{1$!*cf+^fa<~ZEyP&MSqhJ@<9yW)KU^I+^S>d0`#PazPeg@xy zufRp{X=u++>o40N*dE>stHJUx0*1j00hj(O_&$6au7c0O2`~|MgAc%ZuqM>ynqNPi zZu!)1z^CA|qmFml^=4}Y<6ta|hEdRtmlofSm&QvvP8lyk`(N6o)8HOaP0h9gZi5@) zYPbX@!z4Ho4ul;t>Pj<6N11!G_| zjDm$>1iZv?_98q3)8G-93irSr(EeAv)o&x52WP=#m;^_{fv_WN1>;~WjD}ILFpPj1 z&kxRU{7!>=;10MAZiMsTESL=)j<6MsgRw9gM!~``0$vK97r-+x4Q4!F*+%$AI1kQ($uJ4_ zfn8xo*b2tMSQrhXU||>mFL54`@jNDt@FOr4+Pk>@@eEhPB`_H#!I5wv>;t>Pj<6N1 z1!G_|jDle>05hKd9O3*V74CsM;A*%8&V#eyNH`Gofn8x7jD@ve42*_RurQ2(mpG5P z2+zRadDI^C4!8|&g!AAmm<*HPNH`F7gsos4jD^uK3KoVDFboFZ8P0ps;1QS#GoFvF zCVUB;2WP=#m;~+jayGsO!j7;NjDxW-8b-mwFan0b06fF_QW~`1%UOA;a2wnRSHmT6 z9-IY7!hx_4>cs zt}qV9!dfr}M#Cr=1_SUC=V=$=5ts`1z#VWkTmt98S#TsA2>ZaUFb>ATS}+C{h7m9f z3RdN8y|kTn(eLg$iJipOVuIKZZQHx)qVOh|Qyiu6Kee577te@e#8YAq(SG-8`a@B5 zueePdAg(5Si8w-f9@?I#vUHQt4~Uj;Q?&iA)pQYbxM=nDM63T5jrX47G5Dd_U-})f zf%v*OSzIL!7wvk<^0V#H>N#F~RJ7|P)AoB+%l95}j%e3MM!P<0CYFM?h|fr86V>;T zS2MfcEngDvkhbe0YxhBMuxQ)agZf?M64B~!+n1GN+gE~^C|Z7f#TrWAUDT;TWGAtz zcpv^cVs+^n_$%QrgTH`SP5#{Yv*G_)E8WWZShRXA6uXO^#2%u(v(w7A|4~>)=}U-K z{;gtV%TLtUip)m%RgEJH|3R!Iek)r1Q-tpk2PwZDVq>*?s%ZJ!xVHH6`SBkXD@xmS zk@ZtU(fXyfX#K7-e3lfg|26&XQ>T6QKGcdDj`rw&#g5|LdQ`8K*hIALqp27x>U*AO z(fm=O`3sBfMcY0);IB*gLxk56EZw+Icrd1&Z8jfUPVH1wvSp_hz?-UKxClF-mgL_=>R8hS&~&>M(`UOzPS`k@8mwL(L$1sZyBXy`RYLoXH$y*g;<)j~tBIvRR0Xy{cyLoXT) zy;5lCMWLZr6b-$?Xy_F{LoWgiy>K-2!qCw3(9jE@p?5{+oi;w9cL@!>pV82}h=$&I zH1y7(p?4Y$y)-oRj-#P>1P#4|Xy~P)p|=kWy*+5??LtFu2O4_Y(a_t5hTax5^fscQ zw+;=x)oAD~M?-H38hVS+(3^*b-qUF4%|b(O8X9`ZXy{EqLoW#py+kzhMxvoN6b-$B zXz2ArL$41SdI@Ogbwxw3Ga7mw(a>v$hF&W)^je^y7l(#kV>I+)(a@`dhF&c+^s1ww z7lVdg1vK=c(atz2j);9YI6yAR2n9Xz1-jLvIfndb`lj+kuAO zb~N<1p`o`04ZV$M=&eITZ#5cv%hAwVf`;BAH1y`7q4zWzdb7~bn}&v7G8%dl(9lal zLoX2xy^(0>4Mjt5AR2o8(9r9HhF$_1dR@`b>x_n8M>O=>p`q6b4ZRj<=*6L-*BA}G zSTywNprKa_4ZZ4U=*6I+R{;&ZXf*Unp`jOrhF(!L^a`V)R{#yY2sHG<(a;M+L(fA) zFMx*L65@(6j3v)6g4=hMumKeLwX2p`q6Y z4ZQ?3^tz&jljJ)4I%4ZR9z=tZNUR|*ZiC^YnnqM>K=+m=7{3ZS89^WNr% zUN{IcODJBGid0YMnf+R4ZY)N=p8{r z?;sj_sc7i!Lql&58hX3X(A$BA-gY$fwxOZ71r5E8Xy~m&LvJ-2ddtz!TY`q(A~f{o zp`rIQ8hW$P(3^&aUNRbb6VT90LPIYR4ZV?Q=nX|fZy*|a{m{_sgN9xL8hTyP(Cdtb zUPm3Jtv$Xz0bEq1PAY$-l3k|*MXz0bDp;rM7y=XM_N}-__g@#^H zH1rCip;rJ6y$Ce)!qLzRLqpF)Loa}a-W6T1+Wr7~m(bAr84bOQXy~0sL+=b4dZ*FQ zOG88NI2w9K(9k=GhF&Tfdi&7O+k=MQE;RIZprN-N4ZUq>=+94C|7>yL{`{2bjp%j6 zhyMJO`B&p#jvxB-Q|4cSe-VD@&rg|u9{#8CLw|nC{Il>+!w>!WDf1`epMW3w^Hb(e z!k>sA`twufABle`e(29nnSUVue)yq3KV|+t_!IC$e}2mRUGaCu5B>Qm^LNDG4nOqg zr_A39e+&H3pPw>+9R9}mp+7%m{#g8V@I!xo%KWwPSH}jvrp+7%m{xJL=e(29nnLmL4imq2pLw|nC z^d%SW&rg~D8GVuX(4U_&|9Sjp@I!xo%KWGCr{RbG{FM2R<3EBQ`twufKZrjSKlJCP z%)bx+9{kXspECb0{5$YNe}2mR+wpJ15B>Qm^KZew5kK_jr_8?&|7!fupPw@Sa{Np1 zLw|nC{EP6!WDf2&#e-?h|&rg|u8vbPb(4U_&{{;L=_@O^PW&T9`Bk@Cje#-nq z@ejlg{rM^L_ru=@KlJCP%%6b2D}LzDPno|n{*L&eKR;#ucKBQ2hyMJO`CH(R!w>!W zDf2hRAB!LQ^Hb)pgTEGj=+94?zdHUH{Lr7DGJgg9(fFZ1KV|+>_@nSce}2mRMe!HL z5B>Qm^B2G$fgk$wQ|1rHABG?L^Hb*c@CWcie}2mRS9IMf`twt!FQI>SYzO`MDf3^% ze;z;d=cmkn2LEaN(4U_&e;WSd_@O^PW&R`h58{XZ{FM1q@$bVA{rM^L@4>$dKlJCP z%)bNwcKpzvpECb8{9Eute}2mR8}YBh5B>Qm^RLGL|Fm{?F_KhO9B&~Z5U`hzfFeeg zZ_s7a)ji$Q9TXXRdX{l_hjx2*S2vilru)uJ@6=Qc)zvezpvffqV30&s6D6`H8^8pk zi4tQ%Fi{?eh6jWP0{bLud~n4`2;pJ(0r3B?d#bwX*32w|mB5)_-*dmtJ@?$xU0vHx zNx8`A^C^~}l=2f&E;9Ojisg?<`HNVu`*ACe@-EQ*o}9~Gv=J-_0jFy#bzLYNZw z0*fVKO5E!!ULj1`0MjqnALSk}*MUrVFPQTtQ%-}A3sd4dn8giY%1Q9og(;`NC1J`I z_zGdlUEqQ+CGRWpbBd^cNZw!M=K@jxki4IGT$u6>@P;rY?>{=il(&Q1!jwC~w+mC^ zQPCp*ooBXBc^mlbg_pxflEiVM=_(viLSWpJ6%W*T63dQzE4)J}XT5Rq&ILKf_S@dC=XcM>&hv z;mZ+I9t7_cro0Dy$>sRpW$>|e7y{Sj!d2l<3*RlgQ@AaByYQTFNqAMbF8qDrd&syM z|H6Xq?|_uAJf!(Y!XF&d{J3yg%Ab<@r?}9#_=C|L|KrmBAB9f~|CtP%hSx{xg?|cP zwNvwD_>hs~8RHizaD9%9_RdNDTgj;Z1e}uB9^pH0*6fP@wKBdJgm((RL`M6&j_UT` zkoqU2{snY?w0|2m39mcI(C;m2eLnBT@l1$4CPn`zqOXK2*p$2;mii}LUH^pC|BKZB zh3G#a`g|Ub{a=b8!0SI!|J7w({{yN2uGGJnn-}9d}0M68(P*pA~*zcrwuQyW(oye@E=`8R2>1o5=X@>ECI6KA%di^T%It!L)@P z{GVJM*mlRI8--W+58mUlFVXy-@FN#%{`{IQfAS*Dg;4Vi2)?X;(Li%wxGnsg@R^}5 zKPmh-Vg9}g>-U85-JWQC8ypNSJ}<)YG7sQ&Ak~EyiCSf6kT5st_!nm&gYb@ z*FR)_e-*w9zQgis#J>1WQDMg?HwqiFeta&H{M&eaG4Jc4|GdW#wb-|O)| z%=R&!2W7wT_b`CT^(e~IybE?qvpgq|=*#nV2|t6s()w@W{7&=huvePpIh&;ZrH1}V zqyI9dk*j#Teh)P)_UL2>(g*PmT6|Y^>KwBoAqQc^))bpJxsGb`3sbw139v z-#6OlwomuR-;YZ3Z;bkX!v0E^zizbW8RdtJ@`FbCS!4aLG}h-`qrN;>nb?D$ho{GL z+!(Js@0#epZS?mQ!$0_WUAjGat|qCE<}>A|41ajf=>L1hdMp|Hd(tT1VU*u#@P31L z8S}rz7~h=H{ud2?$!HI`b!L7ziZcAN(cg`RJqxydq|)oF_TDc3v{exJLBU=L`d&B> zDXiA}AvI^}dsQ%}0)Nmfw^sSe?4jf(L&4GtqbgQu+UtjX$L&9;S~KO$z%r zrc<(O_stzu-LTbaMa`gee0t!!PN=NX9u+o+L7==)nnbB(>B^n1zoME}t3A`P;~Kh& zWL%XQwbnYYmpztCQ$w#C_Ii4dzcHw;y>N$T;i#?k19GJ9s@Oy)Of)`p!>t^BVxOg5g?$gIafZ!K^>Mr+xT z9sXEt)iWb&y2|lB@-)k(u8*A=47;Hp*r5cAWQod$>Q-g4KUnbxYLDyBIc}@XAW}z& zjrM08`r@t63U#fCNO?fbD}=tTineD`DT#G#%Sys$+=jGSpYnsQ%KKXql{yuBYY(%# zuH!A(U4%+ZD_HI$Oeyq$h3tDh`+yn@m&r%GwPmAYtG-F}i4Ke?@at$*VZfMh5&l%K z?MLRA_A>Rb%XOtO&+p+R(Dk_VR{5}Umf|QbYiHHcFLDPVz>bWAa5g$#VCDLLXGyWf z77Nl|jpO^K4ac#4RR=X2fe)M14ni+7#$KE^+Rj)j%&HpY_sN$s#7EU5rV0Gb%C+C4Sz4BgOneSakyYZ8zcp1W!=Xtf*ATSGN_ zkkzP8%)`^O)45UEF*L~GD>R-8FkohK2gVL~`Vr=xXm2mNK_K&y(8y%aCq zY?KZl36g{eyE5gdrOkS(MK2;KY#U0l!CoA&=gOuUtweo#Ao>;=2ihMy=7x_=TiVSjBTYeB4ht#_W}J`0#3c-`fE7Mvq6Um zkP&v!uiagD>^Zg2_u%(ocacNsgpDK+!cxn!9~`6|NI3e?Q})7OfWXNF#O@;lDcJLY zilXF9&UR7aLyOy(Mt8~XE-u*%Lnr9P(;nxr7F3YWkVcuDOl|uhA2(Q^4URQA8@*ew zkzt)AxQvf7?WSJcQTj42uhirW6GzGH*DB+&jde{m8u@wb*x5|K58tgY+rdW2WZ!hm zWTXwObJH0vEXLWtJ`2XC5Z>KUAk22ktQ?^to^5g%C$C86lQR6g({~H@R!ccRBD8hs zFiLHTTnF9IN=QmBBsUorw>}3f%EW zp)lH9nQde*tgrJ8{J_V1z+M`WYp&gL>=}2I?&a776?X7xFt6a*zl<%ip;q2hMak#dT%0{2CMF;G- zMDu)8HH>}RjV3W#wiBnbt$GrQr9$ldnCy9Ke)P9u(pBP0$&xqn^W|D?JAvr@(k*Uc j`bysPl}fIc3Mb1rh-HyK#tN-_k;354JQNkBiKtkx zA)<)ghh2OscEFC<8~S`ImSLeb5jO%b+L9jDXfxK7W2=)v|bfS+`1VL;0fnU3O^>x2&(Rylz2NQ=EOFJEiC^F}>8q`&t0JDG=}T1k)%teBK4n;o z_SM!`aFT9)_4hMbbnwaFGxo^e{m^%z47RARskxC+x4w;!N}oeUJcYlv*A)TNK=b47i5ZCM>v>#{OueLk>N%1@&Pg@5nwFi?es z7<|YO{qdU;SDzPDRFqXMuc&HhE^98I@7C9KyVMs}R`kCyS`MT>?q6A1Mg8K%^>rG6 z|3=LirDL&nnj9nPddC!*S_~w8bxpAb?AA9``Kyl-nRm0y?;G#Q-&P2Bd;orgMd`hVjXDl?T zWO~ttUq2zBXv2H6N6nQ`@rJ#KGI`>LANiN$rWc+4-z>?z>Gb!DHtglFBy3D2C6Pai z);!(Zx@cphXv01U#Qi=|wC3&RLal$zqpK>4HhPOT7X8`gzT%X#etrmQmRdy{ORXX# zqIA4bboP^3v*$b!Iilr?Hazk9A^3n&E!xD17j5cDv42rPA^D;WFBENflNEfvxn<72 zah#tv{Q2jf&|S2t5E;~2kgm{i_V%a~N0p44K^_SgZ}>x+x#{%%+9{8Op;{ULMA5!6 zvgF1jg9>w1$$2MjT$NmW_P*qa8~$WoIAc}h2x3JW-eLmZiZ?u2v~gux(V9P-Q<1qCDYkY zhG&mDdDPrdWpj}4mOMI1tBrc})0t5}AT6bHnEKhviMmBL6r>gFz zLO7}AYOLuO?$m=_G7l1_7(s=Oe<$IR;|2nrBe;#-CPX+j!%JaL7h#yGTZQYe9dPgt`)~Z5XsxpCF!#^-Ah7&7{>ZQoPqFN^isP`qwNZ$?>4wfh#qSXb&7K zgg5}G6 zBpGiGl1;h|IYp*M5+PS*iX5W=-$Ve52t004CpJ_AOEfUj0r>YI@4~kg=p!Uncr_&u zO(^9V5dS1#f?;^1F6ojK^GYGQ;_}XjBBD)i5Q>O62ex?t*lcSv5kL)rwE(?NFr^;A z!vvm6zPl4v2w&QMA?D!n_EBC>qw>2l6@KMn5h5@NPHJ0%n-3mKCl6*MAe3OH9)llq zSn%u1g-AA+c)T4j4Iy7=Zodq`G8kthozLEslnY}N|HYKNbt@Qe%K-Cb9_~XW7lFy2TygEd%VK|O_Zzig$FK|MW0pzO&^v}+{l5D0ixj{W2kk;(L-M3;{6Z=ga8g>|7F=Z35a zfT$6h1-cNp_Dg-yf(SkIk`O%(g6&80a@rASedj8)Fm|8+L8RjU3S}ii6T$QlG5*Gk zRFX4qLP;J~!ukN*SuaDv@O&sMNc)&-5&GzLA^N`o_!);nl`^$d{~ze>P({wofsf4L z$=-3PvQ}HCtrFt9Hjo{etV^nhY5{j@vS+hy);yzKJO@cN_kPwZ;OTe<^h|W|5G<8F zmj@H9Trf=~#;M7743;GpOHf!dG(61(Q(D4W2zVz+&q^kB$ZwKe`awXy5O`WQ+ zGR_oYI4*Nu3q}fSG@yEd=eGzi19UUN)h)vJ0%GM0U9hzLX~3*}QH${Vfc+;xd94e+ zyc>Y~CgJwwWbMgIC@S5#?JOadVcBCgyX1Hnd2Om<^pl7P^<0hhQ5f7Sl4Gu8&R>rM z=h+1gcI$4iAI4>_aVej5GPGHVXA3a_m$|kDSk;RX;G2kNT?;(Ix(d*X1h01$m`vd< zK)(@uVR9LgjM^-$m(~h#1ebZ48}Y9bqB|~gn^UE*27p>a$WE6nvI;K)w3pypll539 z>(-Wh%I$vuC9em3S2B6bW=jW9M-p)KwUw|7g9C3q*Mt7$-gLx>Y_nd1|5-Q9_@F@!ZA)D?tGawBJg zdKn?p+{iXi?<3?yH$qPlUMFOZ8+jkpp9!gOBOdf_*|^MwZlnjOqX=2-Mv6h5Pe`L1 zIR(@;gq-R|E&%l=LQZodcY^vnA!oUfH$eTGkhN~)Cr|@kARFCCJ5VEpTTW`=aU=UcJxs_>H*y5jAod*0Tii$&Pzwmz2Oo`3s-AE3o;|O`#jhqDPsf4`gM$QKHIzrxa zBX@xM0wEu{k+(tpg^4f~~M&^UMnvmb!$YxM)C&ZiRYID0m zJxEAG;zG1g>e5te+`2@FdvTeGiF-ynkUgNjPDoOso}MU~_dyknK$6`^8&JCw;!D({ zhLVYZI)M;>;2DdF{cVK0+-n;F?E&$d1oa&ipy;4mPtBIh;F#d z47U&Zf;xqeVB)9f8f`w94eAO)G7}9o`Y5Z{g1UncE0N|DHknaeHx{;qj zZHIN1+0Bjg1a%xCxo+eHQ0oaf#)XJrK6+cjyuh1D0dq5+tay{IAh)4&*nm2dY)&-1 zU#k%!b5|;uCc~vh(qpy6WWC&=Mz;n-)l#`GCJ|w!K?9F{OPuIU5EfRcM%O9SD`j^f zeUbJ6>N;}8~pIoj1P2M+QvXi)?y*H z5cgplcL9hG5%E(}N`U0{%>lpU)IjPSaJARpOx)sHs%@9!%3ya)n$} zj)@a4^Kmz_AJqR6@{}9-1JwTWfjpn4mlV=;iiyw|K$j9M0#UR5(=50#cRCf?1E=5# zS_Sa0(?ZMeyPv{IE?yD(H^}`e0kyS3S2)!a6aHOV=w$rZBQi) zk%bxxRS7W^m)SFhi%>BrR}ghTjOq_y{wz9uPGs}AwD3a+i15p}8zN+&P`QtMNY+b#rD8PFBSOFe)HbqBSckQ$p%C`84W3Xb~;IzFw_PWm+q)55&H z5Z;6+grC9B5kl&1!k2KyJ7GvH!DXImgSIoY0pv#rT5f}GBgpy*48B%qhivhHV6KV)73Ua#y_grr;b~@+i9v#lf7Bfbo^z+)4W*=bo>>>v%FcS>iDaOhrOAk*nGMTbpyXaEk=vW zKzWR)&$OY0Y{*NXCi;Oq>qc@wokGZSZlnU#^9Xs~ja&ulQ-r+WLPXBW6r`K8o9@9g z(3SD5qq>9Ibg|7k?m=ty$Zs@nyk@vhD6nX+mRff zc1lM*>$n$b=vfD0@w1Ne*cjj8lijn9%?zZpo@1YNDDJ)>%2@{~C1*=+-*fGAM!Hu7Vg}y39J;y@9ydoy8 zpdlbv5VSQ032P-N+lYEi25E>T8QKLZ&o*wf@rU+;%Cn8zZB*+WP@jOfc}Iqt=4iuz z2Gaf{AopkJk(9Hfo{k<1sFL74F?9^7r9v~Xn+V^Vp(iAE@n-=2LGbf#ah}hFvS*`R z;WFQ`;c`T%19=BQA7tneL6yK>P}`%R%uj7X@>$||kQWmqf-*N=nNRhM=qx}F5Nrfh zr)Y;oa1lz8+hW^rd|Nz@%ip>e(^D?#21C^hSv^TaSl?)Li4&F2xd-c7vQD9@8uBh( zbXP5t%rMuYsJ%?1jj|+8U2eaL4qK6mZmT34-&Q-bvA#l7Vdo0r7zR?B0K`@ZihC=F zvaPBIbV-uiw-119t4_fB1^_!FY*7BAZB;rWM?0g76J=*O+A13$b7$3PsS!#l&Pmi( zeM?`$t{5)!J5@bmzGAEO_Ftbi=;q8B8Ch8f9FN?ab2E5k>5BLiikBgt?9C)bvxKWu z6+1~%PK;4x#U~kIjR$uQ#iyb|Ip}D`@??+?v51Uv8(%KDGk$ z0%y6cmVN9+0Al5)xc7i4%Z-$hDU#cF7=SD{Ct#()5LIr}IYrBjBAEGWw2R?DKdu4l zC^t61Ps)XLrIs3@q*S>vn)YI6c^W|kf5hI9VZM^;J-@43**!2tS@U}8oCz^&M8^*_ z@TLZ=KS8QG2CjQ2Rd>wiE`p2*b(@M__5>imrjiSo>gR2UqwOU6*F%{IWkTq85)8JE z3BE(xKB3$9bV~&8&!U^`$9>aCrB>~iJ?0WPmN(u`Zmp-8$~AWa`8O_ezD)eS9|hhjJs zm$|{s?kaJXp@Xtg(0XRF+CaXfl^$E9)tpvr134y=N!d2HA|0>HpupMv>{x4Fg-pb^ z=JA;K8p8K_2X||p$Uw^P0Aj6KafdtV)=WytqmtV<5`b*YPQaQ6K(%J7?+}qgk{lB+ z)MyvOfj$H6&eqHZ_({32-q2Dbl$2`CjHX?ktEP>?1IU75j<7wa`4QEjO&Z*Be4?&~ zXH!Oml?iG;LZ-Tr;h@eUIOpQxRI+t-A%|jPHp~8NKJOtl)f7JUjygQ z#J$1A9o_tki3qDh09yjM%=2B`4@PxAszbsW2hN4Wy+uE4X8#LoQc&%oT;(=?5s>q6 zncLmSR#4v}6ar-GvyCNfqz9#MVE7FM2MnO9*81`b2fojTnF}APbe#$cKYrRp{5byOiQ~T;{9eiL|ANvEodY3Wa^B;HM5kXU33F6p z_&x-T@IKr{_)Q{)KcTy@yp|C8xXeEjf3s&y=IL1=$>t-8Ua|w@v(crPc=zh;{F}04 zETrsoD+h7`q0c5Jg5u#5at3pxNsdc^K1m!05^0SG4ik>Fab!|@=F997sa04XfRvsE zazau&QlmXD4ZI&nviWbDfqjYh6K&w?9x$-0OnwRwHt@4V>fMxq%+W(~tOf@g_+Pt$ zHjYe6&-{`Nlv?rd86@68O-fQdfZ7`U5y0RO_**AY4;JkJxNAMWr)~tD{y{vZFDX10 z0TG^tyAiI&-GhgE_<0VOnc>vY4+i^VI;^+B)2SW!+B^BEBir-Jv)%1lStF*V}NmD0CgjdkNY=kSrAuJPys1mlKp{ zs?+ujg{P-90_-kfhXY)dF!H zl2piTKwO6;l|BCkVml@`@g^=+hd&n`KdyOS(w)7X@3dos2R7RGn;C+@O8k9!a41q$3V(R0I`XJ;w}eK zPWwqIbyt$xcLo4CQE&p*)d1Mwut5{9Xg|TTFY8&2c5$MMpxrr9U<3T5Tv$DkIo3Hs zNhv2Vnns5$=*X_f34qV&bRO=e`CC$$ChsC#PsH$Y+&$s52ok{uid3Va`KG(kWbstr z`e?jLv%#Q=VKg7|&{{8OV2hSG(LZVVVy)8XI)y5Gn<+PGSM`zhW|A4^T4?q%jo09u zx}OidD_7vlvImO62Z<$+b~bFt>v1-D!nsO9Yqse z=lD-A*5i@YcLZKyz-6vWrL&ln+jrPEp=wZ{BjkKu%rVs;)geM}0}~^GUu461MPvCv z9z@WkdeNwrP9KF19G7{yO-R<6O&~u=&^EWw^Pr}V2C~y8#JzK<9mvH5-ED(tz!IU8 zK|YtD2V#&2Z3SgNQ6I5Utv5iSmn+PtQuSyj^UKS|O!Be09|B&L50SkBHQ>wwkU#SU z=ixWYywR8YO;|nOxSJ1~<^HbYyAk(@Tz`(jAE3CAo2BFbqPQn_ppHLCac^#sjz2_k zGk3an(@D-fp=GWQ~$=E=Giamuf` z5Ah6-br0gaZn!yma_tJL>B2e;B-k08w?vPfF`}mSS70&n94_-#pRPqp@an-h?}E#` zO`k{-589gSaWKIH=j}7c{njx%>K;+|9-yYamh}0f>Jn zwB6}@6KyJnWKN*+dz4(4bPLsaxzj=plnW8AM`?6sod=QBv)}}CRnEEiF>-kSI(Ws6 z2%B#Pb3eaE745r0q#$y|b`?KF@m9H=b^LvbXXOso@egEtf{y=(;>o$?I{u-=m+JUO z6i>_DsN)~Y_%djJ?mcEY;^)<&=A}{G6zJL(f^-8evn`S2N;mW%2tN=pJw~(= zug6hETxKX!b!`64&?T&CAf7`&b|&=*q(%apK)j29&Y71`+Xp}l!g>(I{}7NHRkg5| zfGQ|rxd%3x421nzUdj_``g6PuU=%%I#4Tjowl8>x-$g|R+LCxSC=b z?^mf{*AJ7gTqQ{@^xBI^q(_(%rYCwl$(1lqa76GlcAWEBwC%2C;K zD-hetk<(Bs$NvCwtsJG0W929%$R&=~>m>OxB8Nh7o^9o5gRC*S^a?z(uC!QsIFg8I z3O_-h;&L~o?L1Ys4xos+b~PAk`XieXm$20u8dOtqpj#j;tP?f5PRS}eo}~(}Vy^8n>vSW7hWn-gI{zkCVfX7Id?%lth$4SkQK zd6&t?7W6qQ^{10bmwU5bfqrt9 zd8-$N@6GxT;%i1CejDOAnY0Ov9KRiLoJ`t@I2}hd|A{zGChgVuF2r#%i4>bx;smmh zw7e!-ex$+AHvU*0%(s%f{YJ|kz{bRFt!upvgby?y zO48?VPhwYD-vQxD`(BdDy{fcifcbBJ{9MVbq4uC~rTxJEh%hl1!5D{Gtk7Q97y^_mXI=qk}walDZQjAUxUJ?ylgjR zH>f;>jT;j`gdHREn*bg*p}}yNKqA5#rO_o$v^9jWZ=un33RPuC)`~PLC^>|EiwB;% z0uvTrf&ZlZ3EyD&!}$=_WGhqV0*F;$#eEitvH~mjBuQ@HwE$!Vb^_L8064Q@gYt(u zFa0eu`;A7sI8n~5V+dmd{G3gT9^kUh5lSk~2{aoN!5i2KYCgwaQ1iJV*fz551Z2r_ zsRGqCpXH&2zdPnF% zsJGRFkVZOf zMdIp#vS&6BTRq@3R6V#9kgFa@AxAxs65R3I>wzR6&-LJWD6-W98)W?qNYw+`amV?e z+hNWrm~tAy{+Pign=5@;Av__ZRlKRebK6P2mWO;o<21C^260y% zs@2ds8^i-q=pqfRw?RA#g?0n_0GD}g3=*NwKxv0Z^5#Z6^%ziQ5%oM9)mjJ&Km9yE z`t*}67NIRb-X#7jz>n9!I3M)rKv*AvoQ3?GSNh~L1qF+C-HCb?3E&MtmLS)N=%dik zi8tZR2wdjbWCfo^;gzdoK7p7+iI3rF4KBq)FA>>z`dmajd-mbJKgy%ONum<%wE(E- z&;ip)J#6fPHSxp7^JJs&y^8gE!xJ(Alu9)KJ+oPf0m z09UQBae6U}$YFyb!n#_cU7Y9x(C(b~umOHjF04XYg5M!7v+I zN6&m&n^8z?O=Ig9!4@6FXg5W!L7t!#GD*^0!N<$?gJ56`x(_7o1IcoCA9xQlS?_4| z4TeL#%xrsT;KY|WQO>M&wno<}wB=0YRDsV34#DJ(t)Y{SZfpK6ttlF*(rYm6=M(u{ zx3D&8bcqw?(~_2eeztX;LX|bmRK56AB=^WU??Q_aTri%jQT=i=YO?N^myLDw%f3bA zOY3$}UHx)vMnZ>y*!pG3AL?A_=$93>5>#8itaXFx>X)T%>q{W6epw;C$Hn!_%ART< zwtkt@Q2p{PfL#5u6ms;-Qi5FKc-|t(>BzJQ{TGUC{jv?RI>WDA3I!fgLCZVZsFAy! zyunNTa_HN=LQLETugi}L(Pl9B8d4QYJajRV5}jJ3?wV%5%YQx;LonN{sE%9YWl`NB17ZZF_X@Q{1*k_iu{Z_UJyK zxS5-Nym}zym~oLdx>pq1aQ~?9rfJLQGwgb5`Kj z2;M$fHBmaQ>u#cJNQtmsn-p!LbZ9f$AMpuaD;pYAhv7h1LKqKSG`fyIrW&mr^9fDc zG*z!4b|Vcv6c83a6x6aYzE%_6L%|XTQicPF4F!sOF^F;nK}u;Tklem20LY=h30O}7 z;OvAA%AYHQnZ$3d=K){=J3-{kL{di1xnw!FlHfG3+}JAn0^kt}-_a_2C&KjWoL zkAiX=QJ!j*b1qZf2IW(tywED=X{LMw$`8{)d978p=M8&H(b$>a>(RJ^H3@U8ce@quG}gei?VK=rp~8 zuzT8sKSErDe`1aRh@S8;f<*RI3YZL)tv_$n&c zEp4*1Yw-#SW(VeyHraUyFQIT#o9sylzf0leZ8}^5{$%s~gnIlg1l`<@&db|_$mWG; zv_{ezPz^s}!gn3W4-#~-+AB>um(fcY-3#PBLN99x{R{}bE^A)Z0xE(_8f;aQUc=W_ z^QXm*s(BYBD6DREaaHqvMnW@z*s7-F53L2&Ry7rM52&`PsdWDis;g>B-B$nlxT>j; z8X&H!sqDENh^=aJ8mej@1mvokQpiy?r38POz+N>a`62Rr$Pee)s-_LH1_Dx5lT<{j zChOx5I>X)PpjB)8{W!x*81ii4i$NArWD1)94Z>N?%F9T1unq z6sr2}y@aMsK2Z-~Q^2POFv8*ou(v?PTISM5_W<@D11S#zhz($h`w)n703)STuO+wd z4*+ria{^X&lgez^p!`J#FqzrO8tvjlIkS!dj1BN}Hmz*!gb_+A&Iz(G&WBNk`F)a? z9_vzJSf_%*&tZ=wsjns^JS{|;xAhzl*9=`DVrg7kQugElv9%>m zL$##^fLv`!3OU-6l;Fa!wmSy_%!e9x{_ZRyfk@oj00 zY)kFI!@3#_^-&(#mPkZcB^q7gM0-LQkL)$NPNB+7aF08h-rT)xsZ2;BPmWD7Ax*v$GElK{+$DrEAB}MJ9!qJwL z?pdI^+LF|5oe#v-mK5?B5ZAb*?D-Oitu1jHsx9Rr&#ty4g&b{3N^oJ=+ma*?N2YPY z6pCzZ$p%?#b@3H=WMyf&_;S8ojS>nzx>mI)da>UjM4grX@D8((H zR<>X&ZhN(mKvd?;+$}0 zD%=sg5LqzHir5(gD-{$z7F*@hqti6buGJOD7+mHl(dGBags2l@(*SWcmiQc{A`iPY z0_A=>PLFH`x9Lp|555r5@C4jF z;WFI4;U?V8@Os=6!dr1q4Bv@+Qg|Qk$>Dc#_l1AL-3X^Zi6@+kyEi zJu$o*_oVO^+>^t%;_ef{y_ZAGEcW!g8-W{@Y}-D$JwO-?>nE3NG_{ z{cgWTnnB$|$WDV)#bh#{CF;!}c$1zYL^c~rpTCYBvpD)C?Cjm!P^w15B)imOt%QL3B)fb_ zW+W-(9U$CPp3;xck`8g&{OGJNY)soVPlyEwh~NO+TPz%UoW_OIVa8Ljras^zs0_Qjpxf0{~=GcLLUT08~>yhzvkP77#`7 z+3v>`+Qo37W1-#oP@N6%lX78&kvY~mLP@En&S)C#M93QIVJE1WB!PNWwgk!AM!(6F z7h!D&)iwG}XC!nGh;8(f{Go&=9HXD2jsVp*lT^CT1l2YAN!`{1KwP7rLcRv#8vT?# zIZrx9KTbo9esci1Mn5U!82zLK`^!H1NpdMUIdmBm*+xGbWIY9l{a@fA7133h+yCAJ zR0**vqq236d#_RtgM%S2DqRi6i4}46W35J)I8m-2)&Y&KQ)pa0pm8sg%rMtd55aYV zpEq;rvN~bK@v0DEbEen(W2Lk+>&PqWsct==EXpJf^F%&L)OS0qKI;Vu_Vp=l$hs5|e`TuHt3Ifrz9n@Z0RGC< zVv@0aWy;#{I=+66%PjLMmqy!!GKR?LN2b3_J$Ts5Jve=Vz#N0@;^0*Q0Dh=F7IF08 z<8{0c@icEH37VZb-yvi`yQ7TAU1MZn)q-*jQG0l4P}HqoSi3;vG2mFQ9s{yTlaRXm zK#3=bb&JqJ@Y0_^G5f}-vH&cBavF!r?62JIkzZ1{WFhirP1ooUT^RoENW{;mOlUY% zdSycX-oQlYCJ1p^jBrENlYqD^M!L%49ROSwqe#Y97UJ0UuL&^#m-%`~^>EpgJXJ#T zjZm-S-eQP+(EA1oza1L06K0424YUDzxi4dmfm&$@0rmNKS{}w+zJofMx`L0ozV|J z3CV$j?V?fEoxADuGx;3vrwpcDQ1_u!ThfU`Sg zB;qI82v7?A&9}e<$HK4|5zQOb3pBn_G{T|O?x4{v@-4A&lwLXx&@1cmma-54r5*@U zh=EQNTHOOQzEL#5WiXfkvPqiHD4qNa(C&C1hp6xZbZ#h6MKlUU>M6804>TI91FI12 zEB{_kWoDOaU_(tcV0`#mkk3x}j3QZUb8s8`y;Sil1lM-}nCUP9{O&+?Csm^ag=t3mgDm#A_f~ycriDWFr4|?3)usv`A z$axfsP$)nrlmk16Mxn^<6dE-HG`>+Z!Xf%na)2H~2M!PmhxkU%djlU5jY5$xDYS|B z_(stPhvT=u0S`UQ7Dp6p*M+-ZxoGih#mvVF^irz1WqJA4)KlF z@qtr_Mxn@33T>gCHCi_Zcp#x6CBh;4Q)7|KiG@RS3viU`S>On{^gcodl&NTdq5+Q5 zUt){ALMVsm7NBV06WsE@!>u1?5^Z`7=-wtb;c2X+#?&Et3{6fGzD9HwMZ06tV7cD-mo3&em0d z8lwJ2)W9)RP3ShL05_jk{|)O$u7TauMgm*FoW~;oRi42+Zd8X3)(4XZ->oB?g2s@? z5y3I8q42(V17ZEIlL{CmA3&9HT=rW+$Uj>)vtY&b7z7lKdc*&Wgo5*J$g@;{?w8kilXCxS3p!RX^9 zTe6)6X_CGI=+k;uYsQl6AU-Nue%BIx^e)^q$0kFv8YN>YQOZUuUd3#lH+B)lT2rah zU#BQMhNApQw}P`S6M_{%@?j|rXxPmyklT5TVf#V9MX_mib7SVX7eJqm)W^MrKq>;` zKStm)aE|{Lfj-i(g1whuE~mtQ(5bZ^J013T2T(srA6P2*5nP8{T;2hkasDLYGH5GW z2^n)r7Wb>glp%9^Rv7c;_W&M$BE?T+Fl$)trT8G5QumSiHA}L_tpfcaaF0J1fo@26 z*fTA0_R1XhCg@jybHYam;NP&p`29wy`a%7grCH;~gHC@}Ie5>`Qz5R)DRWIRcEEV%qStdA5rR_EF( zxCdmRqJz}0cgnC1=nFMDQ<2TDGKXiO7u0m0rhk+P{ll+9m#HXPzjtcE^p?matVeT? z)OvEPVU=LlajnJdY)xJUI{t{L{AWy9ji?Dr#E7lPp=LZ$DKbK1nvwY%DD#IwlWy>1 zMTF9aq_|Hpc4r;nDw%Q_m41h|VO{dsy5zSJ(3vKih1)533{6)HW?hUAT(CkkQuS-} z9(HaEl8bhgOk2r|uMdOuAO0;W+ zu2~8Xz5~dhzeXdt$I$4CD3`6rSOp^Y7;_b>x$Hg0ZP0bp9)tc+O?;10uGCejU-TGL zxtr;kNw3d;3ysBdk!`bAW_xryv%$vwN1R-*%&FAB;eBqBdyy>R?x}`fl}8@AH(9EZ z(bl6kv5O4`Y!{=x<%BdeuoLDXH0^XatPcXl=vS8EROLNLFYqEwQJ#d{q;=%Z!<@hg z2Q>SI#6IGCuuI&J!ktc|M%s18pA~3!o2Sm0jUIWwGVD3^o3_K~ajF{DijZ*wjK%!C zVje$Q=?y)@Zr&a*i02tIcY!|PLEMsr82%8{guqSzI;mfCzD3cJG_2gBhs{rP!Ii^fYj_OvCWqqAA-HCAP4@r!6&jjRyHUa6AP1ObpAcYr6)| zUI9<~0!WnU*J(O`Ma@^L={q$2z0Jh`l&0UH>HQY!#Zoj|V)oW&Wk&TrLq7FcI-}P- zN8l`PcUV9f^?5*GBTgOy5$tVV!m6N6V_7eB)%$@Qu z2yYXS&SY!i=OASK6T}yyME}EZt?=c8T13bj(kWWRHyy+!1ia$_*qhR&z7>EkCzcPT zUkuhMZ|wAx>wrE+9EW4+O5{0EKPTi{7vehtY8yB<_=6*1;cExtAOik$0Ma7PjhOub zT%HxYIN@&m5-E5oRg8p(b#x0a2A@XsEGml2XfcRSAVO;?Y3^oBJk4Ih`I+F_LdYuX z8vNWr!5%KA&~8xo6Ve-b@g{NI5!L}vJ|b#=gDiwS5CO7)&CPLmj6}&12|MPUfbQAd<;NewZ37#3+q&Zi| zIH{=FUJ<%k!@T=r%Y<~(KEUsgqH_)EPAQ*kq|D-BAiolN3F($)6vH`$k?byfLIzjx zvKW)-*c}vZs#hAat$H(u6VnY~GE`}|V+yr;O_FUya^7tt-?bUJmgIlA$T52q!xKkk zuxo$O#uY78JHu;k25y4VhIegPv`m%o1j^-qV+{C|3@Egn68zq{ANc^JJjuDTsx|zZ z3zj9+sNp1!Q=03MbsAv$M0_yaBU_<%u63?PvOQF3C|T8YUjc+Z9v{qg%k0!h#4U3d zkjHQZhkAydY0HGj|8^60V($jB+Bz0L%rwSRrkG@s`9Fc_Vq!YWx&=S?Q*fe7ll72B zX1c_!XMnsxGIKoSZ(Cm81(m*W8?106UjVt12E~OgB=jecHunILCmiIk6)i`6s~s5Q zXVZZXRao32tZsk?k?2OZ(vhG}C1kr>C{zk^H9c%I7SicEUQL|;u(p8nI^zDIC7sqz4gb)R zBI^#o50kX%byh-Ih4*VX)dkBc{ECJ%U9haehX8*~$~(JYsr*L`M_Pbwt=~$ySLqq* zVvM$LVRh6zqg&v?-nE8LaKX0PF&sQoaRsZe)2VBR%*jb0*Amq15|=q?((u_W!1kQ1 z(~K9p7;QPZLi1eH0*|n6(eN%8Y|F{N!1EQZ;B&T|@E{apvW{q`&s$O?Gv>QbDKboF z^Vc9$P+UXvS%#qod>jR}RY7dhlF^E4b)r z%J34b=J`hpdW7|&hR<&SmV>)x-j5L;SMcVeCF7TV&C!gH{3WB^xr4RH>qix_d3ciM z{_HQgg;lN@jf56TnB8pib+hJ9cX4y&;+xFiF3s5OsEjsiKhxYp|B_o+U3V)7PdO^1 z&DuGdyXmOhu?dxRrRF~UsN8Ha-GueJ=3akP?x;_MmGOYG`=Xh?L{ypFhUKPtD))pvpO0CB&OAlD6QUP%3%oak8Z0{)U%K1m>FM#p41$Bb49 z5&8~Ho_~SyTUuqR;go6-{_Z-+nFRfoK#50n;EyAKdVvKbk-u(lLwW)kO){y8Pp-Gi zo1yTkc%g(OjuWFo+1|ydyH%l z)=l7f5La-fi^rDMW16SZ#S=|S8UBi9Tyiu~ZnfjA{VSMqI(?Ts$_TF4sJ7yLjA2-K`lvIU1v|p4U9T zx_E3xeFUC_hhUU1$yujtMp?j_C(Fg-HfoS&%sm<-ULw&vgIqi|qnf~T5w74^7mv-T z9hzr`i^px$;8kr6f9rx{NlV7HnlUBWnFS}K%y1g{ zXDcMq{y;bN6`ts&QGYcIPgO*RvA7!AfJgPb_XG&l6t*av}6>LP#q=6J~**2 zvDHSYf)gQ?`E(G29tmcY=8u5}S}$bG$sdj&EeJAB7CHN|nlo~a!&=Cg{VvQgtWQ#Q zz&@J5THipY{~>VuAHz-Llks~2TA%q2;OA=!{-BmE%p&=G-vLP91Mue-z)S#Cys$Ud<#!tA|j8fUFuL2 zZ`*4-WKfMtACNc}(e$xMKdC1S=n3PKWLE7a=wO zbh0g_AK(gNnHROsPt43Ce06|mou6JwGQ`4`ij*B7zD&R(mmD<+k@7B}WOymP&I!v# zlmlmeL-phh04Aa)7` z=-GUrk)l^qh;NJjp(@X-NHnusIhEu5%fKTl60p@}CPauMa1%*!h;9*55+V5r)xyYL zLMarWP=IM~5sm6!;6sG+>4fI>kD}w5SaQa4?Bkq;deiO^DwiqL=-NF(%~F)~F9wVL zm{Dv?N$)}Nca8E6&VyEB3UG*skz(BPUM~lYZxoGCsAM#5tmtIkuqyc#!nSzn-ILKM zz%4hhhBH&;S4DV-<|)M}cfokO?JC~|*q9NF?>IVMdIps8hAO9|lz!6*Le}nP$Ft&KW$cn025$&g$!=$3BB4GPT(a)%6M)Wf*>F{e=TZTAPiaaY|3t=EtZ9iJ+VHuOe=|JY9T=Uw@_O2w(7kdt3NGsa znDy7^;|h*mRgioW{x{!AtHARxuJ{8IG?Lm5Nbn+|q$aF`ujauln^aPPo#}=t+c@5ngcqOL07+IqUKroZY}Ve8{$VM)OdnSongH`bPco`L$PF zMDLP<)li_xAL^854tuf%vf0)e_ZjF#NO;^41WqAa1s{RaqB=Qm2_K&1yq`~oQrXu1KoU~BYht%wb0#d>X{sy`)+? zPf0~3(FVI{J;RvpX&TQsMQLV^5Ce-1`p)FlXDMjB>XO!DcuLsE3pZLZ1UNl88e>T2?5)pV95`Fzt^F=8g`g@->(3^ua ziXBze?>1F`NL8h8Bde*`==^h5Md<{}zl&IM0U90~CtLagIu|@wbtgBfU!$ZHVzK^b zDoobRAT*KdQfyp${MO0V0s%+^I_~t9H z8|~jg!;g7Z%qI+}m~%vWT}gP^(edgaO>gD=XMQG6aCn|x!KX@P z-K&&!ujKlHdP$VdoMO>AQ2Yq4cE8DagYH5sAlbcr`2u2+1KKazbTgY z)Ni}rr}BafUz10xrayB$?79}%%(a>0ZUTKg7{=X$z#;_3KZ?L63Ot9v9SGoG^-8!= z;nq1ON zpe3EC4x$aXIy~81aKSiN%GCRbl4i7mmKMpe&R8vyM~*0^JrKR-9j}UvBJfqW73OhxkAemBXr*`(4Rrt0wL5Ht!lf5v<*Tyv@I}4_TZeSGSClW~(U{7w zLI>#Kn0!l|>TQ5uf92Qm`0d=yq<~+ur8hw3<1}8r7y+YO>+}R~>$Jr7t^a*Ss{lOZ z@faP`y{%JHhNc{sf;nFYQJg;5-xonMRd`z$rxSfdtAbWUN{EppPhy_oZA}~ntwu0M zQUc`rx59%^jZ93Lovza*U2P^hk#07mINgcm#&Rkv2BmyV95E3~YBv#ENV;A~myic~ zy16>E5#m^f0aUrda7?cRHu)DDK`8ROHz6)@TwBmI@>WEu*E z`1`l=_|gA%G$QGQmZr=CHp~`9X$4X$xCVr+-u4g8agDB6_V~J5dX4rg^K=@2jjRBYPjxm5# z%8sU#D6$A<#nl-hPKwcBuk55|r|Y(ZvN@T$5}f&utAtqO&5bgmn97Ez8h}lhTvVWP zgDcbg9Ijs#)O)0)42Q-_ReX3_9ZNhxSK(?xslqIvfUZFp?o-e`w?!qbiMfj!!lIZC zl>uG!80okclCoMAmX27={YQW9k?V#E>Y%gWH8Bwvh9&$<=GXG{OVV<_$N=B;`)PWv zGR+&q>>(;nk08`Aenm%28xp{A8F_j6wKela{>-MT#-{w~g^L$gHRk8l)mK*aUa+De zzfWGIZ(g7LrpAi@#Zp<-(3HPyaDGi)MeWkcDv`gmsZmGr%bHg-R5gkGQ4I~XH5KK} zHT88(`K1*|C9k}pA%9GLU2|1kb5s7I zskySUsv2QxB0vWAX9P8a86yKVBS!~EV=*Pf%H;?pXmq5cp}A3OiL-Vg87o~00aRVh z0U8LDlkz$Qd>kmNt2$LiDqty9N%StDm6g}l)}zMMHv&ZivPUr{%`b1NsVHk|Zmg+W z00vONx)`KW>l-U20ksH5HkQNTlHibOhEpLWHB_IfWMElY&EkgIs>P_5TwTi|eUaf> zXn?(3KnS9f#Z*bQRD?23)9<~ep{j-yp+EUgdeAVi||@+@@nrTJzq;m^ZJwXkiZ8slS{qdcE8Yj3-m20 zNEqNf|BT}k+7y`vz}+XT_LM65<8lN*GNo4uaC29zYX_5M2jHfXw_*SF06 z$TUwkBl&huB-8&o_}2GJZi|G!pZFmn*Y;U$GaLNg1JjS62;jVauX!(9nS5cwfZ0g# zW3$vu^S(JHxd71PJt(rLJR7c*Yyxd*1^g!@K?T z)t+SZYNi*Zp*urwH^YA+L~i%K=KT?w-Ds4;vR9^&np?ch)q^qZsv#NRZwrA zaeRI9?f8GbH{~@_e5>bMkY7K&8LYQ@R&$sVdEIjxY}*gps=Y5l{O2CWd*7UK+jcOl zJ!3x@UiBo0m8DlsU!6R``;Tuu-P1k2(>;AM&34{jaFD^j8GKhC+dSKBhdT8B4CD$< zy?NDb{^PwTg}u3@{trL%q`^DdF>k7Mq#+mQPSL9DtLd4M6Z?8KmDS23l_$G1Ry@2$18=Cql)8djehT5zewLg-TQyA=-2T7 zLd##U=x+wpM9qz>HCp=gC`(-R)X>JGv#eE6tPJA(qNUG|YKf~wy4dbII?GoI`X6K>dn6vq%@1(hHQc56t&A2 zV~MLGe}hGDn#Q!mRgrU5LVD}7h1T^qSoDVJR=sB_rp1r1dJ|P|kG7C)4aJ-n*94zY z4|v~EzbzQ7S@eEL3oPy}lNM}wNhJ`|66d_X!J?l-{}DBJrVb{l(FAF?QNidl?)X+o z3)8Cb#EB)7!ppD_#`-jjg=DxpuPJ*E?9(T&Pu_rmJ;L4Rmp4^ah5<8gzq|oW%j$a2 zQV~m*e7(Z4uh^U`>(~O97jF%X^|X3x%3oYxx1hehsj7EVRaK>P*{PuxsFm|uB=)YT zZ>(}6+OqulOKWN?dF3d|mSOqUbqcQ^PsH+3U_mF!%9b_HuPx(+9oFokv8uYMOe`#~ ztE{am6UzpRW#zSHVr+SHxhOkn@`S$21`jAHuU%Rdi4-@@tiuYkrmm{8aG9{h#C)vS zo!kS9ndtmi1a}sOY17=K?SSP5hoi=8P(WWzJggea~gqry%e zXqmipF&+i578!JMkhz7+o2we@%4ME(#K{J8i|LU7>*0_SM?y1E2NZ)0Iyq2oD0=C7 z3OLcofM{-P*;aXKDff~7I%_t5nZcv6%ks3b+X*gnpj{TOot;a&MeY4y4A%O~stOw$ z>y@)(ai?y$YFgET!sQL@OBr->pk${u;!%XEs4DE_i6BX?HlvqTSF7^1#a+z0wn^ra znyOPdahm|qTta<|n`WRLS27p#$D;A9ROW+Ytg)zz6`5mfOl|pMhw?b8OAx&TDxNKg zXw1b3&ycRjK&Le-?qWtJp~ub}i@I2q-hO?ZdR5%TEcM!Xp|@pL)U|Q7_2n96PumGD z&6<5+|Ck-jt_Uu6v~TKiqh+omPPQR4>SLWrG%Thz)-0}}dabz!DK6P_!&L6U2}O6V z!G4obzot%}UWRH{UrUXCz5q#cDI#+%a}gtb##c3uS=!i$hiA|pi@5mu4w_!oJZgS@ zWAl`{nRONAOBXC`E?izw)xh2E)N%8d6^g&$5alFVR$o_!o|=Wrso@k(sqQS?QIw2;lH zB1h(rrlG&nClGcLjwUz2 zwYa`T0Svz#e%Na<{edB7M<2&u2)-@j7ZK$)ZcGTI>NJ^Zg&E2#_9tUdoC z_4tl|df&4D7yq;g$a1Cj!$Jv+mVt`>}l)PO_Y=lUE*V@lfiRo7xGFhR8Yc$LR8ZozwCpO#5Vi9|kL*OaO= zVGsk6l=e?&MX7G^JVVHcyXkY)8k2d!0_`fZSt@RJxA`k>ppg>qjKb16$u5+$-iShz z3^|>+nt7cTIi)A5_Wk%|V=FwdpP7m|T}DffY0R|NV7;Xi)k6=neI|vdiN(ZGU1O#@ zh4<=9s(jjl76m1O%xb+s^YDe~z(jEtI>D-BqpFZDt|0eVs9?J4heA>#D$@~J2t!MO ziEUR`O>?|knhCF2LHTKA?W4 zdooQ)8D_{VrzlY#@4)6F>fHAu?*FbX!EX!e+!^+bV#>%owy5^S!yODx0Q^rPf zXU&{7`}kRj_^is=RW-9_L>i8totSoFL)6OCehXFAp_b?1(*&`cfU zbu*i!T1BM^&-LHyUEcAdMCXgjU|L;?IzMHZwR{a!b6q_Xy(!A z3s4Ew+d~#_m|Aj%$qZ^d=@2z48y2P22+cD*shioIQzadFLs^C)8#bu9$D>H9cwCxl zZRM3$$!s#tyTYd0E~pMRKdrvC2HeNc}Y80ka^9nLuE!>MIpwD0nVA~_O}5?PXuw&96K z%U~2jlP;@tu7nF2Aj*8&3=e}b4F<-ap4$DabVm|1s>WuS_eQEP366K*n`rV-m25-r zfcF)?xjM_fclz&ZxY0k^D?E5)oK2fzJB?1lc)p^kDcRMP&KQrR=?Ez(cK2kG2z)BiT9H}M#bu7x>U3LkG9z=g#pt*7>mG7* zl5o;MydNtFj>FDZi>}Zm=PncX7E{|+V zdUul@crqplk#(B{)JEk^r))52Yh2(Xb*BbT_cB^+e_H#h2Tn7ZpsMr~yLRzDWpcH63E23ox z%QPvSCQo%FJVpW4DvhD-pT-D|tHK8fwwppm3AS*bhY60$;MhRG#I-xbP@pw==Z;It|oIlCJS|CSbAx)4YT~Hh3 zh!@xhIS%^P3OVk!tr>FM_o*FnIV-#&avT-X5;@X+Zi-w^`_dLU&hj@#j%=_nXKRgE zS4?wMSk3TNWLpQ8M2g+pMs+=mmhz>@T<$UTzCu`NzmlP~89JHh*h3s|^$xZa3VQWAo4J|1-ARu6h zdjZSidifvj^h4n;W%mwVap+ZfwGtz{cRVJAE7PxR)LD|kVyljsn8PV*IfhK(eyU{` z*DDUB0ag)Q26Ei72a5+fBcoB5mHV}e+K@W0ASts5ms^(^Tj!Qqn9oPG&ZQ4p%8D0H zT1r=tEhcF2liluvoNhLschM3^t1X^5XTJ_}Kdbk}T(LFvR_cR!MHdM(%;kt-bza&9 zTV+?Pg~#A)#5k5@>+qJ6s+>m1QMyg@wA{{fwT2-rzx`6uH2sAJ)7MzK^w^IQao?cS z9rnO1&(-U=<#KeqZm}#quUjO%>vc;6b2)T)n%haPEYLM7OH6~l`#V@WZB2Fsi(ORK zmQ8WjHOO$L0tQ~Et9C=`iyjSU;&pv{4PoMg#KM^cRC$-Kte(nF0Q~|SuP*H8tm4r! z^X|gl1R&>%^vexnMAuFsj+XcjSp*Z=RguHjk_u6hE7L>joi|h_H~SWDUlj~j87v@} z618BTR&c`{Qd3!E&jLBdfdhBgdT0_H1uS5e-M#c}YG=2a@wn1m9?b?LU4Uf&w@77I zRt{y=sb=iHw?lvPY^V0VEPkbKEy)_V%}q0C|ML=taZ z%Hk}YYM#PUn9iWMxm_USvValH-C&d8Dlt-6LaKY*@x^S94I9`5J zQrzdD`P%%fakg7)wc))giF@quy2yxUYpYGu87uRxp{fIy9BV%dm#m z?~&_%1izINhA9yj`b!S zcyS`+%VD3bFOPk;-aPbK`t!(VU3f0Y>lMkV3j1lMv`?S&!Squ(s(`XXbUlJiMMo%gxKG>8WH}bERCogQN`_W=mT48!?v( zwZI*s#k*#kMXBAH+HcpeqNJ|`bfqyK!w1;Dm$D{LMBdkv<{485q;n0Z1H#!x(*eO| zIjW$uCudmgWU*5td>kF{Am~t4-N34x`(;2ML*gGBd-K_hxy?0F(K56vri3=6Ta*5) zqMQ|BzaSIJXo?lj?Mm{6saIidB#VttgE|i2cZ!zTW8`yV-|eV#%><@|w>o-FgOhX2 zCXEwytRRlNcAIe?QdT$cY6zaYO?-YwrDt^8$5Y-);YmBUpifb8F+8ehQ`bh;rBm`A zTW(fxyU>BjE#ucJ4T9H2O@~*fzP2)#j9+I_1+ENSREe(-%}930_yL!TNm%t8lrFpl z$t~d5hs#j2DpQ(xqjWwYpWYI+D?{$`JqE{p8y6&}r!!eqxVsC1-)Z�z}0;yCEr`xM9Bw!KAh-1q6-iOX5x zZ%iCVg}f(mr2G7K#O1Uv??fDD`QL;%vcUqZy5x`*F;-2}C%ZcOyxLqZJA7K4b){TN zTpg8rtWlWb{Pn9aJ-!t!UqsBX|g|!7(>cBb}VMIQ_X-%BLh2t!QqZQHiC1w)BFYq?wJ$Ot%hK%t+GD zs8ll-JYv{UX(Xn%H7@AVw+Dr4h_q^V^-Z`+p<@Bg`D$LKU-gTU$x5?(91$TL316-qg;z5rnWpdf&mqj<*1PxxzUEuwR;ZL#>y`Lc{ zSa7Og_k`?!2x{b0z$ub$UW9b*{do2ALe6fs{%}JhtTQu|z z$V?BqWfs4>UUfZ{-&#*JMbH!qzs3@EO{JPiDt)+VUVy`ID&1x_rPSV_xMPmh>II6;l3uYA)M2rciY1rZC`NXLibh;-pUqmGS`Rq# zrEUxxh@`mZ@*szVPg}HjPEW@%DV!+jZtQB6ZR8%_FI^VzK+g0eZ5O@~v}@0N9GC8U zW%DbOf{H?lOAc)hvZZm6OmTW}0k$Xjdb!7MEFQ}U*z_y0=6Xk)-py?BhT_&~? zUqO~#YQ~ZIpiSNMx)g5o(;MAni3w9p+F_=k_}X;3wWl+S(wM9lRAvyHWHm1MPA|wb zwi^YAdtEP-r&8@&f4Er0=RBKF>bj=pX4{*3d~c*J>GBMvMAu5xq%2ZW$$VB>yu%(( zeC7zZWu)fwE5(?t`Hcc)pfAy-_>3QyX!hygs3pucvdp!z<|@)M zOr41#hR>&tMe%m~Mx)UkfiHP9V+Vb&OQKm{#^ozclJmOjpOH!TbmD4KVRQKU}WIB>QnSFyYZQVYZ$-abBm3&ST*LfsyjfqUbRn(=qvjdYQ6(r(8mp=XK z#Dy)DMH5!AJ<9w#P>fX1iqRhXH@UMDwb^GH;R_U#obKs{{ca^NnGKc7wGv>f%C-_< z3uIXdufr21lZDn#LKO`(3JpNe;-!@Y@<*OPg-af5V zxedJH@KX0)N=`p|CGg=bnE}Z}K|;l6uMD)zMX#nlu4f*NM47hX(gI$UC_&qnZ!yu~ zP%!smtu2(Jg|=m~G|;wvc>8Qy2TONo^PEFIf9VNpKy8JEG|skgL2a`wU0~B}%lEBi zww-NT!)!b6Q@iZAD!f^?-4xO)+roWrlpU9SX_IYN`I}^0G+1V{waB_2hBV0ebh+AN zuMVdr%%MUmI_rG+x@-=&`KwbwLGZQ3u1Gjd@kG_qu|Y$dR~$1fR;l9b=FDSfVuna+ zvD}TBk;&1P8IdeanXwLU$&78VP=q#Q*~RlGd{{eX^cB*K8QFqbF(X`HBWA?=)`l5Z z+t!2`*L`ZiY)6GRV8%%y?U#}5bMs|8>`Uuq9OZAkjAXEwW^21tr3-1g@@R6kTpkTh ztC3wn-gYay)BLrkkO25vEhhp_qZN%cq}5hPwJ}Q#*BsVvztk?XXpBQpz2~gg%$*hM z6OHOYsgZPXKEW6QB?Cnx>1KVRQQhhqNf+l6EK(6Qat`AaD~q4egYRa$muay|gvCg0 z?iI$O1U{73)Sb8V(+^mRVdc&2okWbsOAH_RC z+-4gTmi@HuPF1Hp^3@|+uHMRFJ<6T`(gz!Hb?Pc~!+69v^=g#;O4*djo7oU)b6*ML zs;;3mo2Bh9^La|BJA|S%DDCwoCim#hUL;4d)u}Y+%zy;dX+vE5d$Kw3DlW!Z=&Z4Y zomU#?C**BURtMVJ>n0ji>72)M2+aQN9_&IHlkvLHU1~oA7 zd^|#yp_FM9FT(L5lXzRQ9WRM1y5kG+BHV32f3JUR-#TFxAW z2uu^)orKaK&vpH@QIl;}MGaYIRkRI8JbYG_RXo?YFk~~8(qornXWh(1CKw(yWONOB zJsO<;BD(@t%?O{YXLp(_a=Mu*BmllauO|ZRXrpphysKAqm3+UcufD`|ebJY$V6^OJ z{i3Sk^L`dz8{}&pDCAWTE1#a~Xf}6})Ht`QRJLHpkxyaxQG;9xyq-lT=|&C}zdLPK zi4ngLQ=h|fBmv&acBwDXq%)F~I$eB*erGb!mwU=wr!wqg25fM{4u51RBWgJ9?TVyn z^LV1Si+hZGfs(hm9{Ze|*FBP6O~o?o3hq_*xX8A9-6OOOYICHJX=TmWTJHbxhO(x^ z<2`OnQ&-mI6!L~KT7pj1Rf~KD)iu!c%6YZKr2od%KW(0qfjM;rq8jaqaanCWD87kJ;lAChgN$id0fr zrZ>!}!X(>9aZVc7X=bzYDVYdCW=0k@*=)Uvq7xhNt*+S}u0w7JMZnDGNNzo>k#9)j z*ct*NpFj7R_#Bj=7U_$x0@Hly3^~b_W8%Iudonb1IrOWAuP)o1+2WG(X_=@8k1m1i ziUOiuT^K-BrQ~K4xztoWdF`U@(llWAO{cAaKR=zxky zt1&{&FISo!qq(V|8N{MxA#wpj2o}de1OtZC+tQ6eQDs_I5~83S7vQyb;w}h@trJ-J z7_QIATreMERo{}%bY~F{vqNmMNC$0H(0$TX>T^6kLshV}naKskx%Ts#j(<{kP4GBV zMIu{`2uS+MoO~84Q04-T*tGhKb3o3kyhLu)%&%OP-0=Dm@F18(C9<5C-;J1fAkBA)3()o^AE&apv{vDf$F@~p=JJ+2&O-hr-c zZuAIJeb}2zRxPX{;Ld%l1lt#P=M)YsO5~I-@a3f)l)k;aw4H6+>r2~tpWa_Ot_pvF zX}c-p4W=#J=U14H%f7tBv|Z(YiD`=lYf-khn0jVBCE~30m?Bx^7|ES5MmHW~6Y-7V z%5>)vX<{6yhD>9syQ@Ym(!?dOGi6ilGDqNlqd6K=Ct@l(nroAdt!i|L12SaA3t3u> z{&%5Qi*Bu|-qm#A6$jTMB01u%?w>KKd5kMPT^8d;_u`_M0+o!O!o`x~GmV{*Wm>g* zMjT5za5y|#8sTF zAS`Q0K`C<^$`A#G-3hvWf$J8*hmuvYB_f@TIF^BzP#N{oP?fqcWp*+I^CKP)UY4+J zdSuZ|PZrexMLkL)Y@4>IT9q`>L#ji2ona&H)Q|*=)CG(@WnPNv;fFg#bxNekS>8)@ zCvo5eFI6P8Ar&`d9kQ=2(EnO-paC-J>}zwjJ?N_WnI6sC+?ZoJ=CZaak?Api%j1_R ztPS$Jnu68{cUdEwkay~)g9Z33Qd9S0`4*CH9wRQ3?nqZM(~FwXff}MLC(df-AyXOdl=C?DEcQ(FoR5FCovGn1KlNqminGycdjzX38LTIw^5dN1Ne5p!PC z6uHKwp>DD9Bh{U1Y)hSqmwrB{rb9&Q=155?4g^8<#%lN$ZlznItlyEz8_E)NR4U0( zP0<{wklHUcid+juvXWbr$a=r3+as^a&}hYq!s>B6(psHt?9|o$7(A%&z~ZoIW2brb zAd@5X*V9tnYOUT#=yff4obJK-W@9?Lxp^L%?3t;KW@Cg`^hsRff>UQGD_zF)=z8rZ ze8=4~^~f?DT*XR^o`}0mS$;x{+!wc~xtc!vYC_ft|4WO+r&GX(#<$& ztIfgy>8r7wU71Kp_Y zC0yQW!BcIU5Nr&o=Wf>IWtFj(N zbxrYElVGk}=!w&DrA#`rqy{?6GwLH~iSBpH{rvaqYsh0X6ZUY*V7ui zk}k<95u-^GD#SBS#GGMjL6UL@LBVS4W_A}YjD@2v%r=@M9i6!RCXras(IaIqf;06A zbhR?x!Lso(FN+AyoMg*Ji#@hAP4S71dbk*$(-h%jq*Gr5h*aX?bBRxZT5$MV4Sy3x ziRL`2a)qayF-gYT>t^;w3>WFbz%|h=_nk_X<%m$Us2O_<^yn{M*VG%pRA@@XaWv)@kZ`!<8Au~|Oah-M#>GIb>gGm- z$!5a@^|y?5%(%Qw^LHmSev;7 zm6y#a%&EK7{T8B90!yQSBulrg5|XBrOHtE##%MHQ+1!qXFfMK7@S{m>d7vtlM9M^! zE)hjRodmJeyyODx*;9pDKck(*ZA|TrZHW{LoV1XtmW)1R+-NkVhaZlTiIR%Shxv!D zKUmT+qSP$ui1n6c>cx`|otR5u)8_I-2P(uZN!+%CMhq1R;TMj!=tyb6iiC7`i_z4j zt4-#6kP=Pm*=UNw0Li~lZqdO=S9xW4k~+f7$tw|%i=5B`8B1ZcOG!_B zj1DUb(u^wAn$_0PVksj~g}60laEEr2yIGzXNcNigL_P19^Eli_Z3wSYC&P?j4$F*^ z!+~7+totT+Zr67O}2?p+pQb~>aAt{1e@Nn0XWR}f23EJKxb8*-#+~VF zp~*aI$%(T5hIM6Jw8STEUfP5LBpU)1QcbDqYhkF6hN;DHs{&)5kkqk8v^kMRHI6Zy zlIg6K9;M5^)#*@myHR}?%eJ-o0QKyXTU>P}Anz)R7%C;$FrY%4RiLMlJ;-W}K1-7_E@LNcyoLeyCVgzNf+B`sI=R$mry+qW)K@t5MWIla+Z<8! zXLgsiEm2i7e>LBf2cunsZoLc`Zzl55_GBzMxwC?tz5gLi^oi- zuNssY$*#uvQV?~%Il^L0X_=Ea6Tfy${L~0r_xU`eA)=_-B^-XC)Vc0z%fqJ99yMt}G$I*=Agrhi0ukB9BJ1GL~|! znp%&bM?^QpurJNHoTz6La&4i#(9x!>PD2%Tn%LT+#iA`SU)}*E((_dZp#x}}QN3T% z?N69p7H5vnG37J9we0tpMn-{G&f{&+D%_Fd=|op_JJNoibuwskqbbCNCk$Eab2xWG zQ|2T=Ffb|^ykQB-dx8>fZ9)>XwF6St)iV#JU3wk;L^l)7NLn?#Wc+sQEOd#pU1(F? zOQ6)+<_K_5K{i9w2^;{+G>D7(?r2nIIf-t)m#Zmmk011skFw+9R8Tmk?u=}bwk>%^ zxW1UW4pND<=>b>3OLsJ&N)L|$Qe_-%GFrjFIE}#^)655yl(;8__KYwn=9yULN+vyl z43mh)y3=X~sTwS_0jY@FKrZC8o3dbJqEQGN5jbuV$A%A2>1Z^0hAkrg>1?r$!d(?7 z(LiC$oL1Ycf&rN*l|^JE0(_3Rii}yB)0+W36E|AvB?$4ouw~|12zM-IUQyMn1&le| zB!Fd^KB;kzBFLL}zb-7N8*gTJB<0<`SE6vwX5uIbm*hRm@d&N#af;%ScN`>AFDd2q zgxMW!URO-Q0chmF|G>=e&@SspCf**0H$YjE}ooJFJS zRDD2G);6Xxs$O9SZ!)3g8j?9-l+rb;~aS-f+%e{%c7;T80u*Cia?r6sSJ!n=! z{8lY|V8f(I&X5KuES$O_(kam^hiB|}`>K&Mfl#lk(fcL4bNXt;p(pfX!6*c3mCjq_ z!bSONzL0*)&aLdP+4UYh)nf&>r_b$JguU)HfnAdL(kwE~6WCIxl*Ms}xwxC`+xcm( zsR-E=F$ss1o7LvS8hivH-jMKaHcDZeIqfI+;#2AJu3h&hxpj5tR@KuXFBy`}qr2pE zUtuay6r3$IT0IJ)CxAFofRUg&$z--!I|25Td?^mWZ?wZSPi2q}HEyYO~z?Kf)x#hQgkWAoyB`*}Q978gr0=-=B4D-t{(H z_`b7hwy^&sOPk@}JYsxswv`9RW%l>w<7nmWlyS8?liU(ayDS6#uoTfcY0R+H2Iu$G~o`5N(;X>&tTnHx}%?EPmpfSbU#tRo*-A_=V{FB zNT9<+ZS>w>h1EXQ>Id?`%o-|Vxg6y!dT3u{qY$ly-tFT_rRyVOe*)99*Yr+n>#d~G=CSwo((J=`Fz9t?oH_f{Gl#NJD?g*S3Gcq|w z*1_<=gKR-k9|;TzQ$w~O$>B|%CgVm2gO`25!48$P7*K;zClZBUcT*9Tfu@wCiD&_2 ztADTB`H6=J&X4paI+BaKapq7S)y|j%FBq)H+GH}aOixlY!;s+MlNAJa=VY&acqx;yb{jw0-pzAVT!2>TawxfC2tR}?T{gu z&S^~ZQ7aWDQw%%-$e}V?t3^HPsqpMPZg@$`D(bBnRyTGi6NsqTb#i|H3u+A`~v#f4%hI%L|yUgFO?|$+5=Y`=kD{+MsiueJ3aKQe>!Ui?q0yH#@7*tPW#RHIna4I zjk8;2u0f7RE-<*srqAw4vIvBB2wtyj72(;zq9wygw>!BSgnr6M6k}_avhdMK&W>W+ z);U}~QDD`;l%b%791%e230gQ47SBKz(KOWvkN@SIxUZU+dx5~Z=bgT3cOSiQjVJ!g zXuHD{vc6@)g-;-oZW29;M8$9{^KU?Zgi};r!pc9wLIdw18nt%U6FIjAA8aC%>j|d$h=5PB;DPD zUFNdzggyHUI@FgZBY$1LT||C+UaN6mVhvGQy8f-UG;=%gGvYTym#BK|tGr+D9y@A{ z`w+W{ONoB}{#*BF`Qp=8|GnXvTfOQp^>x*&zOG)a!dt!Kkzv)VcBo$cf5WQJ-`ai1 zg);_@8EXA!=sl0D_;UNM{oWJT#&WRco~RtAOjm5~fAXo1Rj<){)(lpLYeos&e=z=4 zuX>_-)w9*BUQy15?z3EM#DB%Bf3DDI|A#8$t(E<&b7?;5btNMINVm1Tdf>2}9=F5Q-^#+H+#z;*hTEl; zZ|>xf@KzjOaa?`%iVsI3J8D-KSFbs1OYN%9Rgh|t9~CRk?jIR?{uOXrvwDVvaOioP zz+6~8aQRz9mp_V3dTPbLw;#G@Z87_mqF~lZPpw4~01aG(jHZcLAsoq-;LM!ywQO zXbiXe8V@RefDzp~x^?d_#`2Q~(b8XJZUx0a>h~J{j|C~4fv^_c`-tw{@h_meW`_!K z=25&S1nWVOBk^w!v6kO)U_{qK;CA!yFQDtJ9ePCYK=~&>c@UE^5ROO@9t}EJmR zgOtr?JnRipzdz&uksxI=4zl89EpWSXG7Z91;onH*0RQlepF5q7S0?x;50dn8k+~f- z0;GPA;lGqnWm64n@#qxbcH%)GZn^VcY23ztz85mGX z0+Ld=J4l)c=}z|rp|#s8)$jn2)SN>><3VCBzr*lc1QLHsL1myxpu<7Z%p3(0xk_Lh zG#zv_NE)R&(6OL7pnA}8AX7C?#j|v`r-Pb6qGJJ3p1*wH)2$8HP5s`u$KyYUAM`-~ zZ!i1$uuE<}vj5vXbxYR&Y{w%n9enHJ^AG*JW{*3|N`Ex=U;p==4@Q-KymH;+=Uw=l zy<1||kh*tHc;T}ff8Nx5{rn4V{>$A(zpQS&xbbJ3k9dCgohR;jT*+7Woc;Fr)2qSfd@$6m4{q)hPcl7+A?X?{j95v*c!2?gea@x={D)(P-!OY>S?l||G zwLSGW-`oFzYf96LZv6g)T~8W4x#gE<7act4%=>?{`>J&(z4GV_hs?j>-0vm2{(R9b zZFQfV|HD6w=@|3*rln{0|LNe*UY?h_<%vHP-8B5N-FA5Gg7fcQ_~C$;zKEQE$Ap?g zo@$tNN#_2GPv}XWd;Lu(#iq{~^xCSwzp&F$XYR9Z%Wrr6{wuqD)$-0`>(=-C^}>I= zbz{mh!#ks2T($J6&duxQKXb~U%DZ3NFmcPAg^wM0=4+2V z_=oEB=Rf>-W!vU;2i(5kmG^u1J$AyUKm7RfX-6bZJEr;lr=R}!xieZeuS?u>@zU#e zzW0{1cHRAzS608jwj7167Ss&t2Hgz03-l!DWzc&d87+@QfgB4e2b}_H11$%w2W~R2E7OR1~dqTz64YSIsw!IS_)bV z+5p-FdIYou^d{&NkW`XkpwXZbP&McTPzz`=Xf0?1=swUE(3_x<=tRbWCWGogr-M2{ z%Ry^FH-qj1Z3ev#`VbUBH$DtB7Bm^u0BQy;1ziMM584EJ1hfV8Cg>B8RNxVyF`yDq zE$9?b8)zx$a?s77`#?{EUIx7f`V!P1jYMo!B(go!oOebfa*ygLk){}_?Etf3H$@^} zfDX7B41Vujr`wY|IyGN)h3+rcbVVXBf4$I?gH8jjU>N^I zeXmJRkKaSow;lCu_yOF(e8+SovKQ!n(DR@dGsqW^{Az!v!*B)t8}=g|hQA{W-_mT< za2*DmXO3*{#)usH?`6DC|FL#IeUa98E@UN6YZ=FvVZQ_TUv(hQ;P;Q|?}(?gKmS4A z9N9~^S8BH-=}?M=RvdHWIkx(R+gM86LHot9fhz5hU% zB%SLZvz9VrVCPT!D)@&gslqO@5`K|4ap*!BamRJWbDAG@103P^;PYO8cR-qm{IT@& z;g>Z3?go)YHMvEHLGoJiS$>~Bu4Ohdjt8RN;x8iQbSI?UJ|NL2mG zR}nu6w<%v|Kdt#sm`1;3ync-E$nSTr=(1aae19Kg(f>dHPP@CCW&Be3C1w0bxSx-- zyN+o$66Hh8rQW#f%(ci135Vo`{94ggp~;GvwnobPzd-rgoLQ(ZQfA%xHG^er7}Mdg z;acV)`1L5lC%@uK?Z5aTzuG4>Z^~FN>z&kf`HlR&H@+XC%@luskM!P=W#T+vSx)=X za=_s_Eu^mA12=!6yJ}xqxjm%3jhw9gH|61^Ea_br(xx21JoL8-4>O&XpskQ!W<+>i zS2G@_&Hl?DbXZJT9Q(syTGY~wsUM|Go53v4(^;OS50c+tlo=@xCM;`?*1V~wH=!I! zdb{&*3)>n~-ydX|H0}6G##`EbY4c5cznFfTes9rlwO^(VT#B|)!eZLleV_=wv_{a^VaeuvEt|M-*0@$MfLS3op#&w zbxZGDa$+QL`jS_dLuM@q)gp2iXfx;q&^w^dK+&J*c&=Fj2EXsTs^jtCC6UN}muj=Q zw`!U4#hO27U(NR`(fk0ok?_4Ip5XT}NO(c{9Rx=Bd6Gc*9Zo-=f*c5#H-bip zA%4<6$sB42^mLYLg>?KyjRlf)kUp>HCA50K2a z_5+OpiOg8w!JtDx6F@~EF_);8g33XMgHY|&9BUd7O_rKp%>bfUMP`D;jr?lyd<>`# zGzT;nbUY{l(h^&@HuAX%I3JWE-v&&BqzjPdSmb+wk_~5)Uj|$bIv=zWbRlRB=wgs$ z-&G(K<;XQ4={nFoMQ#L1R-rmYZUcQg_w56}I_ImUum5KD6BjOsCnq(3b5W|J;@ghu zH?O>V!qE?0`a=SHJhr8_!qXdH2BwEgXBxQ9GWu^x6H37JN14M(dg9kKg0- zUk_OS^re?A{q7Sxw*2Sp8Nd4er(3>z{`*H)ZTRui|K9tP`jd`&;+&nIn}6RYPrVwQ z@YarJ%>QBZvR6Mjc=%!ato-e|fzh{izxMOv_P+jrueW?VZs2{(etAIA^@qN6@*RgB z^y9lPjP6{Kc42{rO>= zf4|el`U_s!bIKksPMbftV^G86*WdWuD}S0fYqiW(N3={V`Fh%zCkDRp_J<>fyn5iP zFC>b-TJi3o{~TF<*zzVhab>4PheJMOvV-+i~N=(u5ndhfb<-KLTwu3fum&2=-cmpSkUgEzi0 z=-78}zwgGee|%|3@y@T`_w2J}ze)~TkSzV@mG#fP@Y&tlN8bCS=K4d|zd!Ts`+xb` z$=f~Kb6CR_AN;iGfbU;<_Zb7fgnjai&)$Cfwz9*YOYJk~(zl;nefJ%Qu4o#4#nJ;0 ze*S^$h7Fkb;X_{>`oVsQr4LSfvH$Y}j=KMQd(Yi?>dyC`QncpoD_*bt?XY`~e)-x< zdzKXMbM;HN%^CUls!Q*@eCf42pr`pc6o? zpk<&-K{tc$1-%UV8|YimE@;4HPB{^DH0V@NCujxeO3T<_v>3D+bRFmp&}PsdKp%kq0~&?~ zb$?J9s0MTjC=EInbOq=Z&;y`nL2rRR1MM^vYg?f4psApG(0tHx(Dy+<0{sH?4CoEe zr=T5&VQdFF6f^~NET|c@2y`LnTF@rYW1yEn?}NSp4MhXLAE*>m4LTXr0XheCIq1ir z`$4}2y$Sj!s2|3mdw|A)jsndAB|(cpt3lU+?f`8D{Q>j==s%!gyCN+>WuO|+DWEjy zT+mIRdq7WtUPoD#{%`7T(ziF%Mi=g@jgCT>MyaI-Xruo_k3*xit=g!i zP4{8Ybv2FdtGA`14O(j2v9{EG6SUDo=&`8lPxG|VfpBQ)a1D4w8(oIsfOL`gJ&&$W zLci=N+u{50T#WvOo|L*uAuUFO$J$2M{zP}-FP@`xy}L%iq_wu@o#8;-9D^i5mdo$` zIofEX6Yv+HMx^FB4);TkD@N;zY|mz+o{G^Q(Sb@|j$ae{Q!$#eyY1tuGqh0)a)kju z6Qcl;I{FYh5&nhr5Tiq!K-Ar@jW(~ebsYu~k*alctwg04qj&bS)fXXRVl-u6+i2&M zHo6?%FpWPQuZ^Z7Vhq>R+qKccGb52*b>@_CuJOtYTWaV3(^6NQXd4~IKzx9dp!z>= z)KcF-n!5V!qK)oaV5e6VrIsP17>G#~TI$r9w$ZLET4he+tUORlZNlJ)4mZu#Mi(P5 zXtcu?ZFD@cg+?P7h+7c|26d;TmTGnqCvmGbItt?+hJF?UG0O?WI_QvuUg8uu{fN%NE=;qlI`$)wv)w9J9#h5(HO_X?8Yhm6ZWUY18c^in<0M_e zU=VryDy?#O!ghc2BiiVlOYPuA*^Iu2lw^oYSsT%S4NdT1COIt|fAO7(LR{jSSJ>_^k7?oAD6Uj_SeZ6j zd8F-r;Sg=K5JjI+T~eZr&Yx-Y0jB!<&<2acm9uT5Q^AYTb;u4j^_Q}CEp=+wZ&`USLlQF6rZL*Tf=;U6k-APs z@uRNgjN@>`kq(ngiI<(?zkaX|#PHF!uC?cBqYqEDjlS)tjiy7IK3;jdHmY4}tN(-z zX9|I!)QKp`630i!+eR;(ppAaBuWd9814EH|AH4uWzw_SO=qglo>Ux-k{F7a6qX#Bx zsTGJTrT)kcVWX3TJG`i+wmQS2%HL_Dk5S~9IP;jQ_aIeiwCoNo^|P~Vqf`28qu)7o zs2*x1^wZ!Y%j(4$Z8Qs&km33>%00#!k=xEux?WqOpxvnje@kjNyNtBe%Yy1n*cR7q(D2KwPe@1TF3P}hRz6XI*^XQW}$Zxwd>uOaDcUotG z9cJP=4vfU%W$KxLXZiJif(FLl$`#hd@LA*=K)29Z_H4*skD(L+s??CPF4MNa%*4?o}hRtriR$*=!&G%$K= zR;bvD{~Muq6RpuC=%0~u`TqjsR#GloIaBe6-076F^L@6@f9Cu09o2gC_{GFdU=fx~ zT7bns*`I+t9A62n1r`BOM@AhCMASy@2eg30fK{;n4;XPLdp*S6>p-+a+E7h|~DJfD+CTK=JQOlpDd1fpOp) zK(vG7UjT~UUjvb5qaFf^|GxmDH68VHAUdY;*J*yu4}ep^uc5t^c9CBOECsd#N8zsl zD0<_-f#9bAMXn5ZIB){69JoJFkljgevQ1E1pEYe1n?~&+N4ph0!8jc zpv3TtVz6whNq@f;M~?U4RUh({Br5r-285FhK&@(&QNC0;>X zL`)M$5qBeQPyDJ|>v^B}7V&xFQ^a2o?;zetyoPuRv4MCfaev}hUD}^diGL=(N_?95 z81XLRM&dQZ%ZTR^&m^`In}`j>TH*xafy7;iI}`t%(c$|C@z2CpiBA(BBi=>aNW7MK z1@ScEal~Tcp~L~i?TK%mq5XfEcqx%9%>7!)Hxb7X#}G#l2ND0%srCJf_z>|P;^oAP zh^@pXVij>Rad+ZS;^%3t|0Cj`h%XVJAU;goM7)K#ig*sOk$57pf;fqIFmYevaN+>s z*Bv@M|0MpN_%v}ja1iQO5!!oc=SBmiz6}G4`QI&Vp4dT~Z@07N|BX&om)CPm+s#Q!69 z5oMpO*w+zDiQ|dGi35lqqf;08zY?DzZYKVMcn9%H;>E-+Vk=Sh_KLo0;&|c#!~w+Z ziGRhQLFC^c%D!RYpCR5syp?z{@d9Eiv59yBv5r^@l>8r098MfS{21jy?Egx9hA87) zF~5~4<6Ge`ATA>|5l<#gCCXlEksn3ejrbMI-KWGq5T7I7Mchcdl(>r6L7Y!KnOIM( zCQc=m62}vV69*7K#<)?%pZE-MGf~E=VlU%V!7GUu6FE-p*Gj&QSWO&HJb)nE`wcI05)3P~5)^ECxzBmHCIvtG`fyi4mpOSFh1W#hX^MK<28NlIi zug4Zhp9CBVK1TCHX)gIZ75e%E55)ZL_eeL<{|Hdze*uKm zsGkFe0B-YfjrULLY`0hqSZ#8Xtj_hTFvB%*6HMl)+ywP)(PZ^Rs(sW zRY#s^)siP#)#Qm*6?vjHl|0d!OrB_!lP6jwCiPkXkL~9UvqSc=~(Xz-Btq6Id^$i+RRsS_wUy>(UpOGh8vMwm{MC(KH zL`(WLu_s#ZkSAKw--$iZdYwGcl73L^iI%J}3s1DRkSAI)z7u<*^(1+sCH<+`6Rk(c z6Riiy6RrEm6Ro?*6Rl0;iPlE)MC%svMC)eqL~8?iqP3np(YlH}(Yl;G(OQar3;l8f z(US3v@I(vC7K$fYo#csD8+oGDLY`w3d@6T1&|jt;OVtRyTQ~)k&UcwUH-U zE#!$-GkKzQI(edX3VEV+0(qjGvLY`=S zgL%G`ccLZdk%cE(pOGh8pO7b7ACf0pa;90_6Rmg16RkJN6Rp?D6RnrY6D?Wq5Pd{z z3wfd?>mXuJw4NkSv^J9`T91$?S`U&ZTKADBT6d8rTARodt&QY~)-B|T*3IOJ)&}xK zYdv|QbrpG{bvb#WwU#{5x`;f{T1lR0okyN%EhkU3mXar0i^&tMZt_H{lRVLCBTuwi z$P=w*@u6Rm3UM5~HC(V9x0XiX+hw93g7trGG? ztB5?&8b_XJjU`XC#*imkqsbGky~q=-k>rWi2=YX07$MC(oRMC*0(MC)bpMC%3eL~9FqqV)`U zqV*(sqP3Yk(RzeD(Rz?P(YlX3(YlK~(b`0wXl*1pb#AYdLwMwUj*3T1=j3b(1Gro#csD8+oGDLY``9IQrh42I6_Xcf$1?{h< z{NKsHME+mo-y{DYy04=9p#!x4&rttt;h}#6?Hg&oobFr5uO;6}`EMwHF8ON782qlF z{FBuG0QsThA0xjrc{%qc>2VPGf0Ca<{%i8pj=z!&s2d~%sg{V(M@puo)t^AI|I92$uFqhx$ zcpi!Zy!c5iKN^Kg>@U`Aq)zNX=W20Tdsh5t@**bo=C?QHx!xPG$RACCTA;{JCI1)k z58*xGI<4e(hW|9)ruj7aTgdN#@*(n{F@EpU{sZ#!ML+Df$YwhH; zv;UFL|C@dBX@h5O|7v~ihx+tO`{8{@8imyE9SFZ5bnrEi>p$&kgqE_ zqb)tJu`RoU1U@2;8*vkv?vC&n>5INYW27!&PMp--R)@=&6S(+KK81@fSoO5ylJYPY z>N6H1tD z$*`S-9*xl)*U8)7c(0N-0SkO)DH=rt%%^1-1G!?~{@6=2iYowX@JZ#y4tyQljv_Bp zj+O^6H*|zNp|&#v+UdHuyuK~H2mz>QQ(vH}ORFzNP0ys;J!<1Aq->(8t+8W4q6ya> zBYiUMDco%=d6j5d+?be`T#)L3U3XK9WI}!SBwIuWIgsEgKk=0bbsfD)fJ)w_9Q=5Z zXzf^pkG|?0HW7&70~6lB*L3)Tt_ql`2hnm}s8eSq=OpJRQEZT?o*VO>3=HOA;1=#^ z%zXzWz6T)D3Hf$}`?CW0xJ%qFSE!oh$27JkMNO89R@cj~JcWHIL#|*~mq^C(<%ldr zJ6h!W{DSvBeD^oROwtCwoD=+lj0sWJ4=|ZfsgLD3Uz;gG)MwRK$mf^5Utf{}rayuj ztRZEl^qVg)xe9oRz5?FZ#G)to0Q8e^er^ zzw_FF4;wogg2@w=LRg7UMt99>Y){Iq_^z)Kn2*XhSstQbVx3$w-VJ|DL>R?Dt%;VP zjZ~MVqSm5{#U(%Oi~o_GI>< zf)bS^Q}L?k#;1Sh^`Na*Zj_w~wCh`Ac8z1pQ9eDLX-Xo3zKEIc48_&wtwQ}VMK%0m z31QvMHh*7&l_K1yJYW1U70Ue~lD!`$W;n# literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o new file mode 100644 index 0000000000000000000000000000000000000000..30086cdad0e31651b476929a02169960b46a7b4f GIT binary patch literal 17540 zcmb7M34B!5)qihh5+2z@M5BU6HiME46=Ts#l<1^}MF_h%P9_71ge16E}yB@ic4L7g-`k5Q|sQ(h425r_uQGuBy@T5=6}z*=bn4+ zx#!(`-@Pxs@PGgN%@E77-4=du6R%3cPZ4fhC*uCXqmqOEY@eXn8(0RHp`p{_ol7Pz zpDz+z713!;*HzE2OVB3uM21coeU%d}YYAB%YlF_wzdm0>us*uf*VMA4l^maM>b$C1 zm&8Sko^sK5VV=%vJjb#sbq#1ueh1eV^0zDv zh6mW!b-XTFE()?o=tS|kx*tFds&BbJpqiZ8-rb^4)L9pZK0_Z%UvpDSkTS>8_ZzXo z=qvvh_BFQ#RF$dv8W~8q#yT3`J4It9^lj0}LE9USgj8;-zOK`Bp-Uw;vrpG_((j=9 zq&o(*_ocDAWV!Tj-I<#HVzOmPSEuL;z_g~8rBb2K*FT;;Vvne?Hpz2h?CYltOrOu+ z*47;KwfL7KS_bwdn^W`!8+}Vc@Sd(MwLjiF zL-YH@e~ozXIM#jd+uDDbmenYBDxmU0+{G7K7K`q!vaDTTLe83rn-_;X-a~Qc;2!wM zf%z}4Io{a8*)zSdFW;kJd!-dE@OGh%mQ~T?jlHS3haGS1EtPtL)~giDRn494Z9h_k z!nyN$a>rNqd3!H%Sk&9AeB+IU^1v$6tc%zjtF|lTC>t3qu3ij1@E$`Vu#TEN%V@ErqyQan7o)$Z#TX^)S zWvyK7?Tqf-K?7=IpDR8DYh&-L7k^e?d$ri=%y!J7@?9|);q1^ zXr$WPl?}yK#b-O1U(thd(_$ai#9r0@l>Rmbc{{7O)y7siaBlIUsw=7%S6x}<8`Q-r zmb~qgtw;{~^OK4fO%Qq8*Em)r+uId(n4zobTvOKWy3=Q7c$2GBUbf_|1x7BoBmsC+r?Mab9RZ8}j!hj?gajUzsbdiBQ^%CkS|*B3LbnPWhn!xI8b7Kl z4!{p@RD4!V=YOO;5PPcqOIL3DGmz?dy(;(iUUV-a>a)m6-p+N~l}JtO5>&VD4cN9# zF{*PPd$+pcC_=L1mni4$t=edS8Y^~Ub%Bw5(DMk8m8`2ql zBi4I(2K3NpcrK$`MSQae#-7^vB_GY)@5U(5zHW=^S7p;?rAiFkst797qeo4wx2kuD zdWPHAZBG=^4M7w4vfI;CDFo?&ryS)OyUVI$r`N{5@NRsX7BU=lFm^89?Cn}(tKx7I zBC98IA?)AcjrDqCuW8FVt2d+j3io(y%iFb>ZrmL2;x05*Ooc}e&EsG*_#naoq%t|4 z`Vdcui+>qUyG#X$qy2~{(A9nDE7S+4AtL7VdAp{ePvYHzMqmg$Afp&YpI$dTc(?>D z>#0&tMaAokkr8yDX*^>D+M+#*0fF{)d$q$8T*&WFI2>U=z~OqVi{wv@P4>q2EN&J?b`hkaK~48EvSusqeG%g z<#}VOJjOxIZSV1bMN9c8btz-LG0zy)Q@fu7zqU(dSG>r_NIyg9tisMmnK_`p&hvIY z$_6KQ*;tr*A9$)p{bVc6Xf#C?n|-H*tO#c20onhg+s2~Xl;0;;@5ii;4&3-O`zHRx zNb?7uCeK(Ta8^SwFeDFFFhXz@{b5;Hr3h4ft=*+wE)e)MygsqD|)V z_BDl?hj}x>E7ClUNAWqoxZmtvOn+j|FYm|I0oJ*uvL9E4-*&F1(0`otC*bv(9d20; zxmK2i^|HG7Zm(FRT!%=VV%u?!(nRK5Hy3&KDUA*Vae3aykA1CuBH6Z)qXJ%#KNA(& z*HV5G81Aza83Nf%@)AX^26+p}wB01vrVWJ+-OXtSNUa;EsF~^Ku zxrb0}$j>Nv9Zh%zr1N9^@M0b>=N^r5M*n({IrJ2i%@~iLV%)AVnR%|$vNDlmb*@pa z(UzUXhR-HB+BF*P%RT|=G|$lafb7xuNw+=c1MIuR7qu{o*Qmcu5PxtJk&nc_x*{$ojA}z+u z$F*0dq}@U42~zIvZR@oWJv747PTs|0xe(G$ev&p_3DOycA6{n*Iz=grw0pp?pQSE$ z_xBz%n&&^ZaJkn-&+zXrYRCkQD*&iQ* z&R0=>s;xVuAzyV!ku7nauX^M(A*T#eVL#fY8^^)8VJh@bQH4XKRj7nawghPu0-^JzCNRDMCI`m~=G3BA>q|1is6X)jZu+~?Dd zyFxYd4(QX4o3He}Ls~g*v2t8G`mW&jx;&rff_+T;>;QB*-wcwuC#1E1ex;;`z`BBS&`I`odp@+~e25Bjdhp}CDINN$pmQ*V zky0zlpefwPvG<#%crXp|GP}MeIQA>kKS1SL$!lVI}IsY~JMw`clwZ`*&5otGh0L0khkMoSE+@xydCXWJ>O^R_1oNI1_Bd zJ!~cE8x;L>((3utx_e2h`7);RZ4AZ*D(r4_aU8XVe}P}y=dx8p*$(3x(+HokstPXA zjnMR(xQnh*`FK87YCHWx?_H^zQLmce?%uvKUl|^7je_&t-F<8FmEjGB9#CF4MC*SP z^;yTKb80!)o{J8*PvAi5u4LNE@Z+}#nVypD0>BW@(B~i;6tc zHM+>QG7dm;33zGCh8{xl#5$zyjQ>OO7IK3_kCMAyaq|!suaSFQ#>q&&z~nWm5qpqK zKQ*HQ+zIH`w3|;F4#-RE%=!R1d=k=bQnqqJyqaW}S_@>TfdafCXJmf{$sx|kBiQ

%y#wnfdlGdkRA;&C=|e0vARTPeQ7u zAXzT$?1UVOr6CjxOrU1S>9-yni-fn@NnMp(7gKQ|RDIigq zF%gXHF<^WQzbnm|@k>2JeNi%c^F-+F#~m<5w;4Ntc$EH8<5;Wzle`tf?i?9Bl}a zu`C#BDQh~ba#H`Cft;n`u)nRTzm!iO7L--tq@*d}k2JNmgv;g!S{s6;I6Nu4xV0q` zY>9-+rUq98n_Jt0p|ZNx*5*K?zsbl=4KDFVnNyHnQglrM1JbqZHH15_k!#9@4Vif<62~Yzp>l7tZr?4yKCZc(QDhC+MNgY zx$EcebC*O8F6dr(uzkT4_tj3RQ?THmbHUE{-G!)qkYsOC>qOi`p?2kT zcZRFlcCU!Iv%j+wZFaXs+=btPz7_v)-)Mi7;VM4PHLj5Djk3Kfoak?zo$lAJbCzV> zzO(({0{!2u3pS~L&$@;nFipr}s8pA2%`r)HQe|7Sjg&$2_IZggP|76liL;Jb>bAJZ zfP-$MxHB$txuoJ?-Z}3Vj@z1f8v>~RWio#+Y}=aotR(-GVD&F!S%(Zm+~T(8K(!F> z#F;C0tv7-OP06o?;kN2-^B5wjVagmvtk@z+5*MEw4^zFDvok^Pa*g@P(K%>TK9o`+Y}zBN zX9d9;t7ZpmB?%5%U+t^vKhL8OgYbfZZd6X|Y~HgBwhx!b%D`=q)--CZx4rV_MdwXm*>n>qUpNxqd} zX?G=ljV0!D7EBB#`2gMvc-ht!I+6G_rAEa?>P+&%IBUQFGeNSrYUf3dn6!Cm25-Gd zoA-Ij=@N*D8 zf;%w0lwrRV;(=tQ&QJWBx87{5xOt&}O!DD4Yk;S@unZQ}*3O+)v?3S^V|`hKgm7sglr{yR_Qt66)oc}SwSYR4g*%%oG?_C&8}X)91GIK z(zFH3R$p7F_3B^%OV;JBElXQl!@-hpFxXJ0@|L$YM4N+&tUuq*@I`o+vq#phyg8>Ol=ce z5e$V|LsmE#Q4Y`)7W1=L`rB%_PPd{h;ijc6=xjQ{7hk=jNN7b zyr~5R{g9P645d#K){JRlx}_DiE(^9;&B2zXkw$HJzjlV3t_}Jk)(U@fR9jUaU9tpL zHUz_gWaE<93>a&<|7vXl9O(mLDQs%7mWP-60+CgC-SJ1FVXEMlb11H)6haEI)l8ch zac$9vFQTk$jYbj#ve_)UL-~X{j1S@QB|hC3)W}9y64J_brt?F=hOq7yq*D7uSP@e) zprj-I(9&Q;X`$amllD6aM1qf|`5OEYzhxFzTVz#aw*JjhNDoPgU$ewAa%R z^$UK{5`R;3u)!J|o&W*MJG;uuNsVJTZ)|a>i#!`I(L7xygEUu}Ttkt^i;E3f$a!Pq zSvha+N&oe;-Ushk+jn5e-HS#SFUxqa<+0umhrjv5bN7#XZ`n0=&EA4Hw?Otj+}m;Q z#l0W*d$_;A%@fZ;+&th@XO`fZDdh|B@Xy*TONc{AlRh0cFLka5^pS~6Z9oI}$cjjv z2!XDa5K?C$pcl!~`C-xjfGiT#b~y4^NqKd=2im+E8NW$&gZk}1k)aQV;g(NNxyzya z?}o=c>LW?c*18Yq0^@h~8F!)ba2F4K{N{b($el$eAGxLFq;<2(H+(O1vbV8g_u6y5 zy!*_*EDB!p$={y8?fi#+@y;LaD%tv%n!N8mJmI#F`c6J&?WZpvU-;T5i{G1_A1JzG z?Hkbb0d5x>Hyk(nV>0gPxc#^zxNpGyBis+*?!oPSTNO60XEFQ9nRFM?q4!1~gXO~jk>=h|)Ig`b0 zY?0!AGg(~o35%QJWO1Kd3UdFMEUvahid)TOare1^n^JnSoGk91i90$JxD2@ zVGE0U+GKI7TUgxNCW~9%!s4klS@ZEDc7ft$0>!>|mSwNXv-7fsIGaU^-_5?QpV6b0 zN*X^^IeFK+F3wKBs2%ocZBv2UMeac|c^SD&+dVf!l3SR~xHpSjfadTra?{#}+?3vx zcC$y1(zNnU+*gTw7iD=Fd8wazpT=D&a%N*7E;qeB{ie89ZSN%> z?+E0*{f!oUHdQV~FXb6j+eH3Ttup!Nb;`|{wN^J9Y!Fd+e=;p7P1@=@lpc(1dQSwhzBC}qeU1T~_3{9j*au|2zX7t|yMUvC5g_%?1+v^3KHozCQ!Ug1!&PdT$4^{PjS}H3C`Bl|YuiT=-=`{M|!IIuL)VQL-COru_Xt+Q&}} zMgqqGX;(UsdSAw%K)ap?(ym8z`t%5fSZWLTCI9>1(LF~q>^5+Qh%Ma?iTChs+Ji&57e!oV! zuhHMcPX&(%9uT}juukv{!BK)9!LQJn)bp|6VZk2@-X_R6q1<9YbsP(td$#2N7k-F) z1fzn>1(}I|>0G!GxnLl^E7&CH7d%g}LXZm<%Fn_NF+-0d=`O*~rC<520rOuJd`57$ zAP>HozeSJ>MAGeoJcuWKrQlq_8bKc1Gk=WW2*F%IerUn`!xATd6MRMR1;M8T`Jo2o zw+e0%>=Nt{yjrkcaGoGP6JhzY1t$oeCdl!Q`8k68FoyIYi93#ar2ijdis7Ybe|c&^|CL4F2Fy*x@K+JXl_kbXn(1wnpMLq69$M1FBYj0tWOY!JLc zaE2hi{=vWWGXzHo@mkZVi;?LNW z{3Jolfr`f5tPsPLLV!ZPxKe+fpd&~o`DUE_P~`Uu_6hD4>=C?AaI4@J!OeoJ1lt4~ z1+NnH3QiHM6f74k6wDKJ1Odw4+kyCmp-#}ldPxgePmj=oo?Su< zdbSHK=y^nFLC-d!1wHo*E$F#VXhF}GP%g-`i0jx z+@vcNg*7(Pq|Nc}9YUKu!6$__$8{VRDQ^xwa)dTVPRLUEqTUJ#eMlHGewu9cxBDz( zuE&r_roRG_Ouv;vPfVfbrO@kA^cAJhe@vnIevn+BjH8g!*P0al9bhNR`%~zu6!|47 zbZv_KJt;KbUy}86^C_8rG==^sh3-nB3sdyxrO;DT=pUxg*m~xfj?X7Y8aP_QF~Abb zhtHsR#Ni9B!l{mLz==rmnGg5n)h;&oxN#6ltcTHe+gis;jdcQANtBlWS3 zt^|5;Y84I!a73jKS`^>t*CrpUwd&N#$3whHXX8*q9dfDSJo@UdRD^;p$wJpen?k|< z6`NM;ikFK&j%9$HY^gd;`dG5+n2U~z_yf!6Cg0MiKh&W8IWUv^<%76Tjx5yKp6}Ax zvwau)rq}trGiKLaR5iPLs&97nthqH8S8J{QfV2>YAIH{})E&m{JT0+meWmDgfeOKi R2!wv8Y}H=<=lbQA_5a$8^RNH_ literal 0 HcmV?d00001 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o new file mode 100644 index 0000000000000000000000000000000000000000..ad9243fdaa262646d181a924c50eb7386463fcfa GIT binary patch literal 80248 zcmdSC37AyH6*gQwYXieH4JZuC(mlW+>-204$~FuQ4C}}Y;NH&CK*MbGEPxu+n24IV z??J^FjayX1M9jj6i(np#{%=EEMB1fF2dFXE})*5f_-4aW5Z0?llrJHKj zFSA&*o;wnf^iyTuH0Udkq%4aW5v{MOxj7l{qqJM!J4#OrRS^Dd;ap{0T~q5zHg#-? zcYE}$Y?o4{O8D1F8958~$r=?Y^|d#(aFI>>PEz`mI`O&Er_=bGQeRu5BThW&^lew= z)%q^z$G*1C7S7Vt_jVVPtqaw$@h_!)-954(>GT!ums$p@Pc?_9yq^SAtt+Ft4|1nL zHtcKZ?C7>TH0-NstZ|fRgp{A8NT)#`4Wlbie=bD|kHwn0y4vEgj;40>7H@k@Qu;nq z{MRb`Zi2o-Npq>y`Z}Apaf6ukH#R8ko2>L*ad3a-b=cR{)MDzJuk^jE^gW>Tjh&U* zzMkD(Da$)~q_pRoqol&?$H??q(6>=Wjq=8~#x^HWdy+pEbNiRur%0g#%D&PW(yvrk z`@~Sth6%A%LHvi5k3~2OxF3K0^L&E3F!)400{tV66!H+r*U20Z8N|O0E6#p<#ksj7 zAhP1@{No=^m6lX>eUFs?5Z*`@-_M!mh(#(-vdyw1s|2aDt`Xvi!h-C#5g!I9t62Da zIeCatl@yN5D)#$w4#56jqHKkuvy0CHTm_-~2tGKw_yVMBbb4%d@fAp~MS5iu@NwD2 z*CO4B^pVX-ADUf!6VlB{PaydT*~Pab-LBJwF;IOX|9m0@d|4x4ypM{d0O6;BF{B8WPeC0@nGX9HvD}=3Qp8_E z!Lr^M{uKV4mUT%sbjpHdU7Af5Q8)_e`w=+p_Z41;_;6G$r$_h-e}wcTou1??ya(x- zl)en|i+zQApm-80F6(lnSNIAqM0x?GuRyxqS9m+p$58r8q>u86K*3|sa2Z0@LnCss z?hlSdR0KH8*$+u6e-|am^2I#nm6&iR+NynYa!WBdMWA z6~QQ<7)?db$+bz@!XE)rFdvs5*pl_wLEG@BG$*So*RG6YE?36Spy&~JsjMEPQ5mlw z&6UxMG%DlII^BmfD&u3#zYFP7U*VTXKS}btk*@X?jz*@`Ae=^JO+=dY5su25zn$L3q(gxCw-}orHTp_{2$g0tA69Egdg| zPzXXyXZtP)OF(!Y#&Ndy4lp>xL@meBG*^=O()?w z5Y7SNY0dF62v>mc8Vux|4uEhA2(M_4Yx8`CweVl6l`t6deT8d4m<6ZEBEJCPB@mQd z*~L$Q@RpPC90(tPVAcG~Ap8@AKWZIUpfANx$yS|Qi^2?h3MI|Y8J2}c%lG?#2OIrl zXu&(UoCIR_`Y}83XK{98&Qko{3cIs6P`%{new4kDo!2a&q&j<3R`FP0&XI^xtz{pT zRXoj?bF@w#omD*3mvbVLRNCxgsLSTG=;X0k#TCAsZH^>7e?d1gT@G6II{z+2#}=K9 zYteahp)7=-#+9EeF1QB7FNyWcf}0Wj0MXnD1wTRb1w?apjJY3w7U!(ZxdwlK4|2{r zF3b;+e3O#(R2VVrdZcsxBR>R*2lZSr?57~*`3h*FS%a*yelvUt{+yQeWR^XIpUUDc zWBDgaquR;8-3PfWN@EDWjZQb8`a7k^I)*rac5pcR*V0v{j#1=vr_x(K6} z>JTC8VxPN?DebIdN;~VA(#|@jw6l&W?W|);JL{OzNBP9K&tcRwGOF0;|1aWWi}Eml zg`Zqo!NG{$3^03dK?u<+5Y3xVFcZ-|i01T+iQ~@`Img@m?gT1D4)wbRaOK3f-`O4R z=VDAX6xU}r^SHYdJlQQQau~=oM6+8-B&PyN9!hcY=Az(Qa2^U;_6hzQ5LJWar--V- zLN2i2FHLWcoHIo zZ-6+Bgor47g@19TVe~(oX&C)qq**EPkA<%vg5vW?dnS8s={kMZtRjHlm+rpH=V=L{}nOaC*Ui5nYJrut>pBtf&q{ zbZE5TAVdQcU0Oi3^(FEcQZ{ZTsAqzjHQncrAU?LJ8du?`CGWU8ME4Uo!{=XXfwJ1h zJPcsk@CiBh;_rTd!zXf49z^nXN>1XUkej8cV0eg%lA{+Q!^7Nm{_9!mt+)z5t^WLX zSp?NOkAX1$!m9v{c_g>+J!oGz92Ge<54mMe_&R_|Tag}?=i{vzF_C!3JeEsK;weCU zViHrHB8nmvO$Q(*UQL`YI5K=0;$yx5^wgq8t02={JdK6L98p=KZ_&j#|3-1dbInWD+lRo^Y@ zY9X_3(u^X{%}D)Q@%$bb{dRmrxYoTf%m{1NIouweWGs*k{qtjT{zom2Bp z{OflB^kq@aWO40E$^|y1D4*-0n4M_UmeRfU3BNIxAm9=u^$J#NgQj za}`hM>q2Zp2&^`EEImbcS5tL#gXwBwtoOgYKvsvHp$L6f!|M&0@)DuD0Dnx~vN9z%{wTyy{kGZvAE z2=DwRt|j2!?YFCrIX_+u&Xa0f>>+Wc5ETf4ZyL&5PN3>+0CWYxXQqHvzxW>TSBYnD z3LX)97to=50iR_wn9QLBP#wV+_!G#|vRQ;CoFhanLf~=}*#v4YA=kK7iqO|V{V5?g z7`9NQVgdm)>RW(s^n>A@HiHoR>GDlYrep_#cc4q)sYAzX0?fg8!Hj9(kS+ha&`DH()tH zjs$cW!3PXjD!&tuI3Mtzje3#r6hO@c|1~AN6VP=8f8~3;+Gh6@_OoT>X zgn1AlFvH9(4(cU@%p5}emb3`{7}R$NnPt>Yc-X~49FGvFa^yzcs_6SCT3JrGRESLo zfq7<@r-J%ZLJl9|>enLl8mMC~19HR=(&R9v2Gl)-%r}e)-2&=kgw&e(JP&HY|J+youZl z>O+LIn8=f$zC*}X6Zsg_p}1uYw42CCP-hU5G?5BW*AlYRM2-S=2O+1J$Vs4HM#$+V z@?B8xCFD#K`6Z~Y67nq*c?;Cf3Aw;Td_yruBLprrkup%%6Y?DsX#(|hLiU@;1)$ze z$PFg)b5LnpGjNNEd;n_hFd#oNkwQ?X5ptJ_l!1CAA@`d|4Aid^@=FuB1k@iB^0B{FiQ12&X zSl*MHTu9GJLVOz`P>?s~SQm2Gsn~x;2#hpk8bM7GGTN+zQ$f9okc0A0ZE}n|dsbWMEnxz+&1%c*ntgHi(;v_#P=GKysJd0)Tfj z-gg6`CjoF_C;6y+5OEgvON|!0Q7-HxHg*9-aG%fS7I85{uXZb)iB_Yf2x5xxq4 z@1%IrW)tCiL3x&_Cp)RX1?8_qJ>5zDCnzHVpzgJ)MKrACUTY`>>~O-*9idl*(iq|q zhb;k=Ao$`D$`^$9Ao)`wUE$DpHgShe4GM8LLg1zm*MMM`j8Y=>37~_h%iT8Ob|)-C zWuP_?a@UBv+(-wgXA^SI2;C*wJ`uVY)Vm3}e}rC=E9Bi)tUlvF9x{;$pe`ZgQ4?td z^&CQ;9-(h3WIa$ygs%kjKEWbrm+BiKRAcD|;Nuo=#tH@@@X?6yQ}{ap!zPe#@QUzU zkk2M)qyu`=t!6*rpNt6q7=LrNB3@+hitu=lR}(bZ0d>F-*{I=8U>6WR-Nr?DKPZ1A zYNbsrstv>Z=`{)D6*yuLncLLiNjQX7;pRY$I}04c+W@T`G5rg$=A(S zAyF?05}VZ}#YFN$fh)nAEuD&@e8;8~y@EoDi92tnrmEz)DN3qv~nBGQwxCz9g8uL4x(S3<2%gla(9PSjrq zNYH_t4C?KKJZU0Ng8FYlo-&c)@RC*JM4vX1D5#x;JYyhY#uPY0-;8Fuj(-vEk5?U6 zO!clhj-Zwmp^4y8s}AKnTWx|hu*nlD~X6O}kK-RfPNqH(kt~x5A-51z0I`k{F%^Ngb^^Vqe34b8_ zMR@8#*dam)oIILJBdMYFpl}A~k9M`en-D6xYX&a77Z#2lhvfo7;7VIsLFa>fFF{w? zkO(~w%0Gy@e>7>Zvkd1RuT~p3I{3qfg37CnA3CU^GEiF)iOsLz7EI^guvaS z^-Rh|QoEz41Gsau6#1N(~b$42V~iBo*i2{?m-5O~@YCvFk$0d@o7uQ_lz zBRm4~zX^JCw4M=E3mh7Q$q0e>971w0@oJDCCP*A4OOq|jsrHC|M-ZAg;5$e;MJFuA zk47uGpQ)iY%GBoPtXr_mig7y1l@Md(e9?p3JjhO{3h z>_=8pmw`{;0TAXLi$7;$O8$l}$`1>zJAg+Rm^K~@eS0h_?qwj#u}Dg(D@pE>9RTE5 zbOWJ%0MuBd@>ye17WPSv7W-T%7uGcv*#P;ZFEmP5!XhQ*sRTI|UqoY!2sDl^dAYE5b`QkgHS?*_G`4*=R$YFw+mN;umMG+T!cQ-Qj3(7Y7j=J+&5DQ*&u89 zrs=oCC-0uEZpi`-%9`H||LI!W8gW>)242xXXah*O5DdIFTzk|Ymgw-PCj;TffL{!! zDqw06KR-zK2(aj)BVl;Btr7Pj8=&$aK5r}q|GXZ~_G7wyMVAp!UKFN_bilEVLPW5K z6PV?YsUUnYT~^cOD7v)LMasMl{)VFHnpgW zv|g`O7fDz5IJo$U*>Qyve6k;?s>w%{&qW9{J9H3_m`JS=h=ZIhYYgiEP`GbwE|jg2 zUG!hnuzZv!#^)hdU*N<7YXdyI6rG))gSQk=#RsSl%8LKNT*&dm*6>2i!ORqQFwrDZ zL`%0K;>1k>nD`m%76%hQV|}F>Onf1A>XGbs*It_ zXja_608x%+Qc5){xl0ZJkfYfRgaiyxqnY}4JabzBD70O zEmBfyG&4HotWve!8{Y+^e1S!d4VJ6W9ezUoZ)KkDhDBW5(EXskOh~_)k5>SsPdFVXAwLb0qhT4mzRAtBGwxnvmPX=>+{qr62zFdhct+ZBoMd}C&{uDW%fTo z;eDeY5kC&aWO?}Sq?2cozvv9gJABx9b+7mn6B5(+1Ir222XM>l8S$Z>N_r2GOeaFs}{IO71)okY&fzujx#rio51KZ1C;C(XtzX4$b|B^@EO&Q1>KbIU~Xk!CEa2n{~m`M2rK4b%>R-FF< zi64FD=PM7Oo@rhV;AP@3%vTREeZf2svqWeb z{YCvQ!GB7jHOfh3P>~rbdH7cWI#Pb zgpLIAZ9-&e54^P;VEGumLUW-x?vIC2x%;tT-u~6*8{tNsD z`|d8EtLbDlt<&fZH_E;{bUXC3>|TYY@zIyE9qQ;H^&EY4@G_`(939*yO?m=U*%1O?gG_ubWrJj8dT%xpwt}-jzgm&IF1e~}a!=#~FnX8$f9Luwc>t5Hd!g_t1Je!wuonu7+XuCBp+HJ$qLADr69LGD zf*S}e0H78MwBUk>G?-Ukq3s$i_PJ2ef_iW*``LgZQZ7Qj)>4a3R!zSgxUe9Mx*i>g}q6m#Xc9xg>^L=8&Jf>3P}9scoRS=x54oACQU zj$DdbJ&$kJm|A4%5aAPneUtEu95~;xgw6-~0fH{oH-&jh>B~`^X;}v33Wt#F6C*)h zOwcu^(0WiWBIE{#5PRS7evqFb=uQVj6OstOL1a`;;9eUN;SeZmi28E}HFP{E`-uAJ za6OyJ^73urM5^P!6A;K&Bu*@oq==7sV`?Ct?Ax$k5cns+gS%o!7Q+WfABRx7R)QB|S7u;+eDVqaz zJ`vgr{;koy3RP}^57e=3?7OFK2A}qYgavBMqXZRfOvx`$2=@dw zkAZ1#1F(Ie;?6%z`$AGmbtkz?rUH<@&<%v50F*DJ@YVw#%PEHC9pU83~WZ7N}ztCHcd(pgLZ_ zP}JR^I#y9i_fJ7JR#8%S=zSo@DoP;}u(fBbqLe+WfH+oBoQGOPodL*LMM)voDoRRF zmAGEOkmOA$G)^x-kz*C*fI@Ep;x?V1C0jd9{U3(m$%Emf8t-7Jq9GIDT zrYm8Ql1g0(57i4r2TY9@&>C zndCjzy&(UVp#Kh0UL#Lg@EWKBw{C&_p$0Mn)N(?Go5&JSw-GXmzeGWqDQ$Z|y@`;q zCh{Ptzb9n;P`yAjKGYX;_^-LhrPi15px@C|J#QS}Y&jw9&t`W4xQJ>^(fMGrYdk7(s;bSS>r!K8jsgWao{_&i<4JKV??$eX(-|g z$#P7D_JH+zV!t6I5p|jV4kK>Q+K-%BDOVGT#98 z210H&WW>}WsM8+cq?8`uzubjO4q(0Ro(^-Q2gt{5hCLlB?inCT4?s%E6vNwopdh} zcr}0W^ySh6gnm+~ta&Y89ekD6yv=&&gMT|h;16z;kDP^02EwQE{+O>1k$ps!fD>Op zxYNF#uS%~vEg2AagSTQnXV&ojpm3*s)42D|@`4>nzWeQ~x_zj!#5Gx8_01BJ(g42|vK;hQ`CK+I@WVa_bZ?p>p7`A6u_>sv7S>%Ef8Zpr|j7Q#Ic^^Jk)yb z7C^>&P71l!b5eq9)43}q$@iepxc`MB$9m2Ig$i{2&(D&rou>Xn7_B@Q$T^ueH;>Co ze@S=fE}zS#NC!8nO7)%{Zj>Ed=p*b5slgy+J&ueA!}#BV&w8<%T#ViwJr?R6{oo~O z(pjJy{owbEgzo|3=m(NN{2r)|exRr!Y`;1Bfzo{Zi*cR$-CAl3xl_6rQ>E82oxl@l$uU@tyB$-DoLSERU^^zoeKUyC zF_BX8_maEhDFD(jxq;B%04T>q`&pJ_qJ#*AVJ4%+J{P(Y+TAlN8&E{bMW|g%EmBgd zLKvO$`!&itkFQ7GzCc%@^@KfiFqZe6U$Su8T8A~XwMnVHu#SS;hXH!Do)aYJ?Dr<%|qk8xZirkED2A^;I2dl^$ zH3RS-ubKhAz+B`Q`QMR-mDPDh{(eTnZ9p6&U-E}<1l2L}74s6nk(>!LMqBjD3A~X{aTh!&FGac4&<^w>X9*ypBqgfCZ zp~p44SD~s;y+_qB<#OaM7gdGe)4q!^ukZQ{!7Dei|sl)j6U zlJAn-C4U1TeU}>u9a66fJIP1oGYY#&qs4BN3+q}`u>nO~%+T{%YLSxiRDxVo)x#)X z;B<%Y@`1ute@3CJ>Um#&BJl^#VvqG9SAv*vE3)#wa`0E?D3zSuxKzXTP+}VgH zDE@lExc!LlrTBXV<8DX%dWwHiFpe}lOz|%Z#{ClUE00Ee#PI3o;creLdw8$`5fMBA zS6?uJYgVua*X-ceaYgSv0GS^l8W=ZxJgx36U&9BZm9JUa4h~aCLJ%0k?@HL!=@--8v z%x+&Jg~LZDij(|=Ap>pYaCGM>wuK6kq5w4$7FqcE?xSX3Mk46+!hG> zs2YPoT(g3Q;hHU`-^|!g0zo<_FM?}v^#!-!niag5ATe$u{v5v*E%{(z90BJg5RV1M z?LwSB3>~;QFz(TzcyD1F;+F-+T?u-u4e=d;aislmigyRbJ%M<6JL0tBa zNAdS9&;!@Pd1aRoIdB06tuOE2p!$jk6D5Bm?oL1#>n)Y7uL6}n~;RHJLoU?hAU5J%UP{NWcsb#zTd9hP); zO{IG!s7BY6x4VK*CZ9zG|2k+MNR25n@^(p#|xu$IMkfL`edd5Xt&bUXMiXtFj7kWT5^}H0w59!yTYH#*(7m0II{yE8TB_YK$eRJ5;pG zGnN#x28c11lszW{af~I-Lye`M05Zms6mpFvDZ!25bn}wD1BDjh_o2u!mK;#%VBLK4 zvt(yU(|lu3Rbz?Hu$yD)ZdvJD_gG^|y=*VL7m0|__cXf0=R&U`6GQK5bgx2{9VZhy z<@)3FSlS3aJ(dXbj-~V2n3CHuINdk0moPBxMF93qqCV~GtY;$nuT>PlFoq&$@%$I>mZ))#osF_ta?g~!tS z`Lruc1vrh1JCS$;f90`s4pYSV0IP(tB`M?@ zOHzUx!#S2DnO-3l;hUkzF_s)q=mkJ(UXq<9b@R>l#sP zKoJ)+bcn8mMM}z3335dJVJ|WawAhbbL&t!^r)uIu^z8H)7dNy6$OQ<2?bh?t=Lq2s z0pKMcKwOL+LtL#Q4_W;jC_n1x9-@k`9(9lffnGdB&CX+OBK#I8{HUXksOnMS3?EA5 zn_h4!-zoWn-@F*f;1#%L1%H5RcJLRt<^*5FH8=Pku6e<)aLo^nz69+YoQ~^|U=&wh z@F-lfg59`g2lwKd6Z{^oxxu?|%?mz@Yku%8T>Zh%a2+DXkGcwCfx4`6fyg0SVeo34 zaQDeq2%_-seY*U`8Q&2ub|^Ne)@!lKTb)GeUp-W*$o;$q2&+Fj)jI1 z6a5EI!FLDfoA<9E9h@%HH-q#2AiC~^VSm7%T)#hODzwm{M?an0^3#iM{$EiZ6svrJ zV)QLi{(PQfIcx@K)Ea&|#_j)MJeggctxb3Ro7`<8Lr+2CR^j3y{0s$POPi7XB znfJ9 zm1hwPC+U2&pU&UQ%XbN&-2Jywi~+iVtf2Gle!fuB&$ayw0c4XjpHX@+?|+8?j!`rD z=}4;o3!+i1G8fZF#U0h4(UDF6Xe7rL9fGT5@`avK`S%lzVwE>j zY)Ktxe4%6|$LPVHl%OXQmCqC3N^F|>`9jG`iWN|ERLp}ro8bQ^@le)&zR&{@{}Ak$ zRB((Q^!vwBl4B>;AX!35id9A^_G|3_`afQb3s((oH~VR~w{jh!wp@)V*iT&J18MM)B?yp&=~3E&GQD>+7|ME!RnIkt#8R?*K96_t+=`^VVn z@jqijd@SU3#{Wck&XK@rgH2v&Gt2)U0w`9QkKL7uR|%zkB|i^?LqJpcurkifAF-(m z5Je-9=+Fj8t+t_~7&@MyLkZf#5dSz*Wj9f06ZLCMC08p;;y=$OII_InrgE14yKDky z6~7!sQo?^5rAe85(T}vqM;7#Aj_^Ot@{Dr^m880oR2O`R*dIECICw$<{aV74 zhz^PP=}Qs*>@CQjVwDv0)6ot87@|?EGDNXe8$sg>B`Y~b-&*q14X=MGv2ctpberiv zif9z8Y^K=d#K#v(R&tE)z5TSx_kWXEIK~%RJ^QaD8pSHVN3pkvk1v$0B4{*2`+0t#nWB=EApG=J>;i}6P+_z={E9}^T2 z#h>GE(RXFCN-WGlwTxRn-#26*N%)4&May6rx1s)v>ht0=(qB9nv>i4Md0vI{9WzhF@T5%O|H-6&$s*U0K& zYlcdc-rV;GfMd|mpX@@cT@K>(u*t}0;jm%QP;f9qGXLSDpr4JwXe+dG&y~3cu)Gm? zjZRw|oCYoQ-M*1NALTMC1XXjOb2OpvuyTTJ<)VW5sFXwVuvMpOBUjhcBsZZ2H5Quf+q<}st24K5 zlx7S&sG3$hPt`iUI&&zDl(jKs4p$tyn`I7+EV1Q>*;=PLs9Nh`vqg&hr{_4zHX{r5 zI3KpobaWF`z${%FcVo}CbIElha~w$BC^uH>sX(-7#3Tw)rhAwy099eR$#p1tNX1lc z$I21>r|KZ?8gmaq*QuWETRsY94*Ev=77uM5MZcLfFBe6mE}S(KqupS@YwzQIkx|5d z)Ucz6wW52>KU`2(9gFA!Y8H&adC(xcFOTLdMc#YK;9oz{Q1WMc@51-SZr zU!cF^76CmGTin7od-j~RM6;N)p*x=Jp3@L*Z;vPE%`2+{(mAd1 zuI@R#eRC2WEp5H6aWSX2JE;?Mx_5WaiFNgCO~#vA-AGLS5E6=cpDGY&L%0Z%%DzM^C(?r+d!QcwfA&vkRqe z?Cfl7+1ixQd`sh-n|j-NX76h0(Fm8MIngmkR@NX3UsVF}rMb1eJ?oD*`R8?>?$04hwxPhSoqt(g-jwwb> z73=Cu_ON6=&d?G;bNks$*<-p;x6)WuoUK%vzG~2hKoR9%UZ(T!?rCj}Zw7=>gx^Ee zmO(!=MyfO;C#$WLt%O*S>gq{q%g{nlh%w6Tfhb0N3o@c%0T)572_i-y<`+5W5F0&o z<^EX+r9)TEqW>$iPnwjKi-ASmEk0@W>WynA^a|xXloNb_sEnD8)F;Ru3Ecp)7sej=#c_R^`~~-+O^TzMxtz5U)LC=NW+Q^ zjZ48w@eNDsV-3-@ODVprf!WrrUqyeHM;mLFE?r-@cG)_WTwAjys*_M3YdpF>8e3Cy z6b3~MCP~|xT6z+F@fZy3B}3u&`r@skt+TUBC}?X_M=Qpz==xZUon5ibZB1JQUAm#EW6LC$XmeA`_IO8YY;&vV!rw&47NurqQ%}p*c+#Ef7A?(W za4gXoL#zw_34ThbKhTkE>Fk9;JLMn632UWDkLXZpyG6(5)^4$L2mZ%+u%n$&B59#) zw$835RD^)rONy9GnEnAmtxd_Di4G5-e7@8j>mdu2PoW%}x_5W9P{ZhUUs1Dm>1uA@ znuep-))G{^B3jFBxvU`;-56cV-2n0Wb*onsZj00@QEK9)vHH4tR;2mr*GKDX)=Sd* zb+yq3?kEk7>!USmNKa#JJ^!g&6J5`d#-r&E`WF3Zs9V0ahVxriCk>SOy84f5f9}jJ zZ5V6RI34(*=NP5Xrc`{z#Eqc^h;9jRrH~|uR$O*P)irE{wMeEO0S)n8@s=1lXHQFM zpY3fb3(;+55nzB7S0zy9cMJHHmUwr!BOUK*O2(};IxVIMS-@_Qz+kZw(q0Y8ls4xr(_3jol{rq(oO7 z`c=x2Ys*%+GRp>q%a*Yd6zgplJ;``HhGCf8E#L@aZSl=L97!g&Y?U#p9}G%DTRPi1 zlcJ@m7Z{Btcsxv#hW^MyJFov z@Fr;JWM^*={h&3fG`R&=>Wbd>mkp7G_iOR=niT9kLiZCM%`$V0>=-PuTqWW#q6c1M zvvMm$iMQLicQp0%CQoq~{?zySO>i;C7x)F^dDB2$E6&VgevpsB5m{JEMBuuu_w zD5+RVGhOVMwX4edsw+1(we`j$k-F{;9ayfQm0F{H!jTfqSoFBLtLnPf_O`V#A4NQ9 zW3o5SC`H`p+`8^%=wlM*m>aLI>u%^t!bP#XjCwhCw>Njn{2Msx=7^Lclim)@ot+)5 zMkm~CFr_A$Y}(B%9CPC^WnD9^S(rga-5m4kx|g7K(Ak+q#oav6vbMJ!D-vdrQ8x#f z8{LJL$KYcoop7_k+&WrcG7HDtI5OIRiBd7hsG9@rhNhQQPZ2j7skBPtD7Gq7s?tX) zbkQ9AvViH>WqUfrMJAytyiTDW~tZ73%#jX(btx>bv9{~YuZULG;8*%3fm55R|JC{Q`UB`wFxrB)BYKeET+pS;L+!qxYI7AbP z#yUG<@YHhs5!cc*<;vnHLo1`$0ii+7e+{rAx+_7J(jNnwyA(?qtbc*3n8^SOsX3zC z>ifuAii=)!UAm7qc~KRTmnwxh-By-S%_#@Cnec|T&Yo^rhaR$_JTe!uE3lAkz;Y$g z-IHkP=JtzJ7(~k3O%gqwJ($*M6^aGNN%0sKkhu1E=(H&B?P+Spf=yvvTX%P3!>LWl z_2M?)smE5?Mx8JwjErURO%o%PhC!$SgQ5y=N|sd_d@33mnAdIAi-4Lo+(uylx2}n|cP4j7 zcZmVE$8PK3muE^&0(6p3dsaoFF+008R84)XZkA%2r#aktlb#RVVYH1NgBShP~ zdgM}&V@hW#=E_>E_^7J*Zzi=}R5;qNZR+Vv&RUp>wUvC7W}TiPcdut}D2ok>fBh;H zJyKCmTYlZNvAhJ^dvy(wSTs5)J@pU~jjDF%_f;Q$xU9~FVl{d!-xbge1}9v#?JWYe zg=!Y39Rrf>zc>R@!=+g!O?MSW^;^}sB4tbCxU1c2^)Y8sRo`62>n$hE$Yo_Tw6R^+ zNxgn^Vhe6RdCGKD0ymJX&Bl0p7f;~P=-P(L7*(X2`O#c_f66-zF^+e~Fbk$qPL@&U zPnUURb9_sJ?qc|Ff86ER83Zq`s>IdW%5u!1u+wTyimLlLvOmK1SMV%K=~!egoCgL- z&+eKY-1aqNo1a$=+5#n9wL0FhrDrShlo11tly2zRTy62#34;#{-*p}FCA-xZxi}`P9yom>- zBQ+p-Y(l7dm63teMucuPHYM>aG@iswYj<~DYqW=!>u%bB@{d%wh0wrmf^bia1F^5E zA-bMsVLg8@7>JN}MDY~l&Yfo>IgWVw;GR&^4=`56Gq0(Emq1d`*mzP?gmMzJ9b~OR zyIT?oRFpx{^{phz=3!-~MPv>bpPjwQmN>02=ys+wRvqoYb8Xt+qm^cQZuQ(Q1H+yS zSO&=D3CpU|b2{!F2P{J!VHGWl^mC->+S+wX>((w8jhoiRmK@y}jaihMhT6J1JGpLc z)L_sxWmYpS+Ebg2CQ6HmH1%a_=hX>qMY>zCqLuEFd9T3HgXD6;%U#u`=W7|^Rf(6) z$h(~GpLNMzD=g4P&%^RSS)%2ssj2QM5T2P0&VyAz~Y$TOUnR>M;Us>DK;WQOP(x8y>4i8aYwlSVeY{tHY?0C`+ z@4S%76QdPf6Gwj<4HL?$GYRz9FqvfC4K=Tp9yNQ%w5AF*xO4?M_8}w^b?!r`5t4$* z+JDHPh<6?`;Jn?CJ`3;KB=shPw%g0!{|aB<@H-dwUOl{!k(H2gC1cl*x~udo^d0#q zmJAiBIMP&~LQ_|s0=-2@S#@c-GgVxQwISU~>y@Fmq+Vmp`jql(JMk=eJ5>juKF0X}k@y10F*dx9O_yyYKuB$Bp^Pxf7tutbK|l8kvWsd`$}-v!cS7bh&;bD)K#0TmgxFq_+|sRfIJU3oY-^1t>2_@w z=56^DN2S)sA=1Imebm8Ej(br>p+;6wvN0al3DiV3ghW zkGI^s?F01ASSBZ+c`|qb&636qXgIYW(5Sb^q;v%7*)w?p>AF+xL}-219*L^nOuU}z z%Eav28|mMUR2w4wOJ&&q7(jWv`y2xiGB!2_AY$)j^k1UXdl&=AB*lhB|GDWMiT*jg z-89`c1pAm2bB*qCX*4+|Za(`c^(>O28V5JisB$&XM3c}?vRbR>JDoZ>?WT?vdgg?i z3!UnRH$k(zV~wHf-kQ&K7Pzm)>991+iTZ|e+=GEb&9#wY!7~k|u0o z@YqR@30ac&KT@*rqfSiBahz*twRxQskJ<=5-=uQ`ZB4sv5eLC5L0e!AEy+Yz4>h!W z=r6Y|OsYq=EMm#lcDD7lcX*|pbdNk8M#G7B9JEA+R@}o@Ee*jADh@obrFGl|sY6>$ z5vhVLOQ?71HkE~Nkvyuoj-}3ZIBm*?SY?tFI>gR9g0T)XWXw*sp}Jz7JTR<9M3t-o z)zA8H;;|Q76qGIPp-9j>TCCDIx~gLC=LSnvcr?Sxz*3ZEX<*^0*9I2sH9O_vAOnB@ z{w>ucZYdnd^1xyq(E7mQ9^eAO;vd`!!4mu5mI#*kpw2jJmI^Z5^3IO)XUv(jb#$gMBQ*Wle*U!BGsD5zPH3`-Aha@URJ6(<=ut6Idv#-lGCV|t5x8Y4X%P( zssZaBAOo6Op}t31YTu(QB~Irpig#@2TNRUYz@x*u{mDE$9BdiJhl4B40C8}n9w82f z0S=Lj5}C$GiYE)YI;~jdA zu8FAkSrN9Xu*+4cPi5OZ%~tw9Eygp8XX^4PhPUj;Az3^yi z2V0YrwB3m#73TSQZzVeha_S9(fhft;=qbjX+bZ3fgR|Qhf~i${8yo9he8B_n$~ntT zr=n1s45V)YI;M|zsc^nbS2#MDhn8NxjJg?}+~sAhBY%qOQzX2>Z*iqpRt;q<60JC0 zZCQZV8@v|=`B>E*F?(cak?cT2k{>187;ns5kPJ%4f6g#ARt!DG!} zy5>o>abM?c>oRQwsdZ7TLOUN;qMYVVth(>p{{df|bIW*V5%8>iZzN~L=sJ5{OV zJQLkOGaTUVRjND(w~v)d!~eFUl}gi~_O?>N3c7pw=ZCsWdJ;1u$GhAnWZSS%=;=?d z*p2%}Zy(RZs6VD+-Z+}4uJroTed`t>2k)#|$5ia{>*!Xhz4^v_P(GfHNW-r;%vC_gavM9eP!pbA@#!cw_t)@rDZ z(e{R#6Hx_FYd;E#dNKVu9`sYSEh2>~!i*V8SBswH zXiJl)LhHGdOZv#(cyhPqO*0|lI}NH}3*BbPlm7k9rx54j8^ZLyfc(ydm3`_yURH@B z^7-?WjlOL#&AZL+B0LVL4bW1oL%trF7 z2I_7@12o&nfCt_Rdf%_c`cj@_ssBS)cM?NMjDt>u8tdk`af}dw5A#Vk!pI) zy@tO%s9!8)oW-P5wY=GsDqB%gOCNNl&;9CXgB@K_)1awKqpPF%ez0O+6+IdVzW_rP z$YI%lk2PVl&K}OHtv&SA<1A85E`r{|U|xHMjocO{5CFM)%OhPJBw*Ie5@e_7D;r4>6mf@XRifA!B`LPPUphrb2yU&P_F*bs8YQrjHMQw&E== zx?RV}LFQ2h#mGBCGouraCftLB3tDnfo^!(%nYVJe3>z=GS;L% zZ`&V}p|^s+YeXLwU4xeto3_N4btcoQFnYYba;4dkzfL*;C58dG_d-1x{fB(9mug6s z&s99`W=YW@2E<2i&(k}Dl#B5YLJyYAzSri;;B#%JG``kmNbO^7-0LD!`qoSW{rgmp z!^Ob0H4fzQfz3UjhXywL03Q|D0)u-%V9Wh)j|FV`K|Ks`hziXAaEH1(Y9nCSb}=GeVAwAlMfnUpvtD(6~bV8Z>6uYu_? zcC?Iw=#?gaX_anL@DU=#f>jz^tDC0Xs9JNf6n}j-jnNm3XmF&dVJM?F9 zX$53`5Ye8`-CTx}vPey9>+)J`1+;Z;>5c2VF}l;O$A>Yf>X+B@oeQFP2dh?dETiA} zkl#E>sX=U)at$qb0lWjhtfQfq zJb*fzhErTk^u2kxqNJP4Zj%?&Yzs8FHFqOzR)$$+74iYSmvO+ghT{PAK;Nsu%u2RS zv@7v{**c~Ml+r^|OH9=#%dAqGjDs(wslg~^q-wqVnH;|JOZH+~R^6|@k3Xto!tzFw z7%U)gl=D|_-zdHS?&j@Z8Ff^2Qhb%o${<}G zm!hp|dhxMdm-%wL$0Sq6v;x-iN?Bx60y|$O8w#J2ZrIJwc5z?J`!x1LO+Cu^3s`e) zd>OvJ*h^mxp?eCOY?W&}Xf@sK__&v)Qi*T|bO)_+Qe+3kQet#uI(DUn^sj5wFRM@B zJ7n_Y7Hu)blX}+>cM6B#GPA`P3>9%%3j|G<%vYQ z)SsG77~<)2;*ZRfzJ_kpu{DhFvov7vI)W00R57dPh((CC11J=%<-mxXxhK>YAJy@u_ zyM*{>+hCyn-7oBR@Gra3w`*iX%Tgg|yjsfQJ5=fPCuJ7!cRO7?9dUyvxYB6CGe4IyQwMqvPpDYrscDTq zFo;2HP=$JKqN~$+mtj3p@!Z3v8Aas$AU`yV#|EcwB00N7%K*Z{DE2DAZSaSwh2z!n|U27o0t zfDHhP*V}>9Z2%~dR2u;OX>)7<7+UQ6RsG{K|I^DWnS}cvUjsA3*Z^=AguJ@E->z=# zl<(VPWu~LrnOPj_NIG%IsGB2F(b!2J{!gf{;|={&L=hbbI#f4Ut0*sa6%gc(%OKv!cv^>%Cq+5U&qfJ`ua zv7->SE1t`qPB}FAyz(;bu_`%bxic50ONK&9w#?2<^JMU4nk9`Z({O4}rcrOFNa@JZ zv-e-|sr;DMHxM_bc?aahH1hzRm}VcG57Scrn+wy@gYsaO(7+v-78!{D(!7IqUzXrt zyq6a0-+5_HZ#PZnyLiy0a9#aqa(FJ62HR_-SJ1EDN-x^~=oyFshS#zSU^}fySz{-k zfaLR7yj-)BmjB|zWsx$q1eHh4`t-dsCk@t!T$E}~N6KI)12US>K*>zq_&-J@MytkwK54m(ZG_NO^m zvqL$Osm_TDE$Y@t$CT13qX)7nxVO1!{LM^#M%wxXF;@?DT1ZO0+=fc}=;ykf^lCA` zU1h&2K&IM0#Br=Aoq$_$Io|0_TUualZoD=@4|&oGNZ2hCiEuslBkACAi?e}71#2@5 z^8epnRB#vc|I-&)JnvGZutgsI9r(BJoe#v&DfQUpFaD+(fM#r`MIXeE4foNH z1v``?iZ?$b87{$Qa{ln6Vz3qqa*HEEkJGelT9x`uA4w23{DrzI0F9P)v>B`8R%bA=(yi$3x$mp6E6_ z|8^2ozLML!YO_A{$l5AAKRd!?myQ8{2TQ*J;kixF9Sv=%c{1Hqu?f*=y1Oa`r@5YMfSqL~UOC+~q6 zU@UrF1yGBM2z}VvF)KQHzDYI4OPL%m^5Y>`EjyDYD-V42oe{$a8QwuLxfPUEFH3Z^ z>The**jPj+R8iLiR0z8cE=AX^zOj1?K zdNGKm7%lWY?{m18XerKZ*F7FX# zmqfZl>n^7ML2ZT_(q2}tt?5at+se8QSN8bw7ypoaMkcq7_!ab~ZpSDxI;vx#>E?55 zDWmxtpRj3jy%3mDmxtTXSf(_ZFPUwlRR9SafFWM(G)Nzl(DUTL3^S$NIh0d}^%SC? zaqp3+?nXKC|-}oxBt>%hLX8pRE?2FO*+)A zC^EMZKPzx&`k7{fVhB`V6v+=bd2aJ*GE_IY^me%M zsva#39fGD>; z{Ynj7uw#H(D!Ge#6goKE3i&5uJ?u_()NwkDGFZ4zw z3PulcSzBk5mzAki6)6-{;}dP|UHAk9mDV91j@fEwuc(9^J|!cdwt++KuD zH@KJbZ-*E}?pTthTY*!KW4wCepO<M_}t1X z=*y7(E9ah@dc1ft@K#X;ZRho$NycI6$wqR!OG7_fO$!71y;}CHI$^Nkp4j;&y5YsG z8w&deiR`!54NY^UCdc|5%RI+z8={svK5kuOe{Z)l=~m{wfpp{EJ9*c%kp3p#-T^Kv zRj=}4XxMiQ_S=FkvOD+k>a=eGx}3L#q8OX$f$aN z4=*k4gL`^uiT!VnFD>ywJ-@W22L1rkk{QSoOpAHYk1%b?!92sXr22n|X|Z}oQM#v? z@_u}wu=jd&mn^kO^i>P38_}}4_(9a#&aU0$Vr;I)WK*K2yN)+$qGaqUI#j#IX83=j zIa0bT|995&rrUOWn4erW9&xC>2$7-O{Mi{@n`<2P z=>TR<>cjV82B>7xLV;gP)}QL8pE+II)S(Gtk267q#wV0)Sf1VHhgoi*gAZ&o;1b{` z7S>^Z-0_pUw6^!~^U@Y3->J|^u5UvV<~a?cbv(AYJ(Sx#o|B?x=DO?Acf-{^PpM-@ z@#G-2fY&I5JqdY4@Wb8sc~<-^2}EF^{^mxh_3(h+Fmc;aPG3lJ+QBMBR}T zw@C7L*kgV4v#aiH802UshpNx{HSnyQ&(3!DK>Q`x8u(q z^%u5R$!KkvtY4jsxROiV=u!hMCFanyt#La=PEWx9r*_I>@%3t@t$m zp#H6Bs9E8IM7|0IN}6askthC(e?+2m76PSn@HY?P{eSK&Z~tmvc|met`JyM^ef1A3 zKe>12=ljZ^Y~NSj1N<8Zmmu7P@C$^O5#B|3;ToxLK>`W?-2;|ReG`dTZ6w#5TXbx5LP0rMp%om4xt`lJwhYGMuejfjzu8d z$K&sb2u%ph2rURikK^wagl!0I2<-?v5NJs4L^uWEbOh?xXCmxHI0u1b&&A&h5H3Qv z4B>Kws}NAtjH5}!cUAm*_tC48&7?A)pe&K z{Hks1eSciF_FHorFa68A55E5VuU?JJzI*LuTaO$6+R+~!HgZlvT$%IQ>ZeCcUccvo zJ3f8l{Yl3z`1d~-m#+T7Hw@b&BOxo+AY zCLQv@`5zqh&N-jlFhP`#sJQal8=w65r;iT3>Z#{96|Eop*x9=(PCakpSx@g9_WD~N z9CpQn^KZ#2s~EEM+;eOG`qY@$e!cGTH*$AuK63Qq^Q#_;7yRs$$}i5nX4U?U&z^S3 z$(t*02`^t+nCPha>fMj(_Md|EvB#eBr_U!}mviyQ&mD5vT|0)I^l0?T9m6{#KWv$D z@%!W3zG^(7?_YPXeEDkfACqhUHSU84|25;sa~^r&wdse?JATOB$2C`ccTe)*qMmp}B#>r4Lmz>*jJ2Osy+ zqGyUrw>-P~o{#=E{hw1`T(WuiTlf9!_xV3)IPl#L7Vf~ zcfY)A_R9NT{cWuD+z(e4UsUzIuMH1BTl47N@X6;P-BHl^Sj(hKPuYLnv#;Ftucq^I zZu?!qXYY4j@xrE6ecx%ku)XxOvxa>&bJ#sS8;lyIwqJ zOEf;BpzkLKo;Y&N(z{-NIQaE z-4d_-Q$uE8}v!P>p#eE$+~Pq@V6NF?;w1RFdTz_5<)q`GK8ZM+7M1f zxCr3}gnJO4MEE1Z-w|^BLX1I}j<5is9-#%H58-Tts}O#K@DRd_2=5|%flxR^h!8>r z!g7RT5ZVz=L%0~>`v~_UJcaN&!p8`?LxmWNFau#B!jTBA2s;tZLAV;>c7%r!UP5>e z;Y)-7+*}x;5@7|xu?QUqrz2c~a3jKf2u~v%K==e94^FTMVJ5;Ng!KqVLbwLu z4unS#euwZEg#RFnfDbQ5s6wbiI1Zr`;p+&OBHV;dgu!jBOiMR*zEeT1(Nf^g825#}PSL^vLy3*iie%MflxcmUy9gf|iXiQpdr zAC52^p$4H5VGF`Z2eVF$uD5H3f!1>t81 z&mp{p@F~I&Odf|K%t2U!umNE!!pR8dA$%9%CkT%tyo&Hw1ThN#5vC%{Ls*RvLr5YV zz~tit%k`L4vUr9RAFPt3rRyxxSd@~u_B07`F#h7-RCG8ZtptfCEd0w}FG)j>v;=2h z2oTqwz&%Q;pQ}i(fTVO4Tq?P~eZYDsFsoTp43H%XEzD=e;Q zvn1(lOyY_wfH6fz3`HMQIlh!FN%z4RMY?y4BrU>Jr%3yhsSW7x%KEXVO0F@OB$fJQ zSO<{$$rz;8W$Ct#b;`Dm z6)3Eh4jZktBDMv)T1FvdmZUUIB@uxwgmuVVB^A&#kxq;?K~e)Qbz_rBlMzL-xnW4Q zv8jX%!bq19^?mPoI7i8{_$Az@&wJl%K-btn)7MU$KhJugI%YL@ zgwUR^#S1F1b>&$*)B5`4f)F}=f6V$;dkC#d4S)5G5E@E@^V_x%+B`Ehyr(6EesXIp zVwkL2>x+dsxglg_Q(w20gwT4sOPHZNd)7=QduslR41{UEKvN9@}Cf=biMDIs*;&deE~`)H z-Nq1l##Rsw7clmVX2q!fX-o>gNzI(02&pD0faSM`LfzVC$tUhM@ zhc=qt*HP=9TcL-nH!O>~%DG|6>>A1XWnO5wC{@3eB5G3+e^J!D%hp=r}YUxRaEXwA(bG;XVqtj=3PXj@qfEn&x8 z_@x+n>{B7DWL2DwpFb2rZTH2jb4=PE8(k*tr;9??DSLtCjL$6&p+hzzgdU<{dun+9 zLe7}7E<74SJJZ-NWRd&l;j23noBOjVYcB)+KpN;%U7@etc3)D&i`Kvwz`yLR2Gu`I z_wT2=er#*OvpUmsG~N?Jzp)XauN#@6!j&=f;U_{?s})13zq4)8`x>#nXqZo3vuvga z^|5@PwB<{~>!{1$@l)#K6meTB;t->H-l{LQ)7UYU!C7jvPQ&@!e6QIJ%^6Q`4Ru{^ zj-ek}onGo;d!XSr?MCrX&w`ls0&BH34bDZ&@T{Bdfg(O!6GC6NBDj(NOsT_Zpl{?F zE7CQ7Fgr9n@Wpt>347MN?@ROe0-@zL+l*Hs_x58C#)hYPl$OA=cRpOoW9EJ z9P~9nT{oqzW9j3ehzm`z`%^TWZ4DW(nfHdQ=WAkCeqRW^neN&-H2ileVm_fuDfDT3 zHSo*sT^##b!}2|wmhTSMYOhTP1Kn2;8opvLnbftOzBW|FzUsalvYxTNSQAfwHiSyQ z5JQ6-L+Gpa#SU5HR+QIu)CQ^8XvZTqr5<|8#*5G^6(RIJyT@sGd|e2gZ;N$ZVLGO# zyY|~`LwB!=eQo8kFQ&_GV7&g8#%qpEyccn?GM=%Qx(=s#v;;q<1!N}md?hofJ3A?x zf8CURYwgt++P^dYWs@DYSBGOkL3YdJMN_Tb+~Iju_HQ(#eQciHkC}e*uC~v7M1Q+1 zul@hXJ7Rg2KhuV%qZNs59<4~J$ zs9qeZ8;9z`p*nG>4jif-hib*4T5zZpI8-AJRgXi};ZU_WR5cD&g+o>1P!%}TJRGVV zhbqINN^z(X9I6Wb~)em_7>;82%vsP}NF zb2!wyIMiD>)EOM=4IJuK9O@(vbpnSP$DxklP)Bj7F&yd$4mFBH9mJtVaHs<~)P5Xl z2#4B-Lk;3k131(!9I79O+KxkQ!=X0gP@8b5UL2|$hw8$iI&r8D9I73MYQ>>iaHthH zR3i>mk3-erP_;NzH4asULsjBX6*$y99I70LD#M{lai|g;su+hV!l4Rrs2MoaG#o06 zL*?U8Q*bEZP#GNRioa>_`#(?OCCl91is^4)qoebq0s>?m7Y@~rLv6>Q zw&75lai~o=R4)$IjYDh+~aHv`wsv3u?!l5d0 zs0tiv9u8HGLzUrBr8rax4mD=)U+ribvj=~lKHz5V^i+TUY)6yRZ_VnQW}2M#KEI#{ zciQLsf;MA;eTzHdAByd;uQ)O{*q_;)g%4=%SC3`(hkGdj`@SLPpU3aOi*WlypSi(5 z^!V4{cG#!!+=srL_(SuxzXobvUf;m)f&S;o+^>I9a`${"): + lines[i] = None + lines[i - 1] = None + lines = '\n'.join(filter(lambda x: x is not None, lines)) + + # Write out the file with variables replaced. + fd = open(dest, 'w') + fd.write(lines) + fd.close() + + # Now write out PkgInfo file now that the Info.plist file has been + # "compiled". + self._WritePkgInfo(dest) + + def _WritePkgInfo(self, info_plist): + """This writes the PkgInfo file from the data stored in Info.plist.""" + plist = plistlib.readPlist(info_plist) + if not plist: + return + + # Only create PkgInfo for executable types. + package_type = plist['CFBundlePackageType'] + if package_type != 'APPL': + return + + # The format of PkgInfo is eight characters, representing the bundle type + # and bundle signature, each four characters. If that is missing, four + # '?' characters are used instead. + signature_code = plist.get('CFBundleSignature', '????') + if len(signature_code) != 4: # Wrong length resets everything, too. + signature_code = '?' * 4 + + dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') + fp = open(dest, 'w') + fp.write('%s%s' % (package_type, signature_code)) + fp.close() + + def ExecFlock(self, lockfile, *cmd_list): + """Emulates the most basic behavior of Linux's flock(1).""" + # Rely on exception handling to report errors. + fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) + fcntl.flock(fd, fcntl.LOCK_EX) + return subprocess.call(cmd_list) + + def ExecFilterLibtool(self, *cmd_list): + """Calls libtool and filters out '/path/to/libtool: file: foo.o has no + symbols'.""" + libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$') + libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) + _, err = libtoolout.communicate() + for line in err.splitlines(): + if not libtool_re.match(line): + print >>sys.stderr, line + return libtoolout.returncode + + def ExecPackageFramework(self, framework, version): + """Takes a path to Something.framework and the Current version of that and + sets up all the symlinks.""" + # Find the name of the binary based on the part before the ".framework". + binary = os.path.basename(framework).split('.')[0] + + CURRENT = 'Current' + RESOURCES = 'Resources' + VERSIONS = 'Versions' + + if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): + # Binary-less frameworks don't seem to contain symlinks (see e.g. + # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). + return + + # Move into the framework directory to set the symlinks correctly. + pwd = os.getcwd() + os.chdir(framework) + + # Set up the Current version. + self._Relink(version, os.path.join(VERSIONS, CURRENT)) + + # Set up the root symlinks. + self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) + self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) + + # Back to where we were before! + os.chdir(pwd) + + def _Relink(self, dest, link): + """Creates a symlink to |dest| named |link|. If |link| already exists, + it is overwritten.""" + if os.path.lexists(link): + os.remove(link) + os.symlink(dest, link) + + def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning): + """Code sign a bundle. + + This function tries to code sign an iOS bundle, following the same + algorithm as Xcode: + 1. copy ResourceRules.plist from the user or the SDK into the bundle, + 2. pick the provisioning profile that best match the bundle identifier, + and copy it into the bundle as embedded.mobileprovision, + 3. copy Entitlements.plist from user or SDK next to the bundle, + 4. code sign the bundle. + """ + resource_rules_path = self._InstallResourceRules(resource_rules) + substitutions, overrides = self._InstallProvisioningProfile( + provisioning, self._GetCFBundleIdentifier()) + entitlements_path = self._InstallEntitlements( + entitlements, substitutions, overrides) + subprocess.check_call([ + 'codesign', '--force', '--sign', key, '--resource-rules', + resource_rules_path, '--entitlements', entitlements_path, + os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['FULL_PRODUCT_NAME'])]) + + def _InstallResourceRules(self, resource_rules): + """Installs ResourceRules.plist from user or SDK into the bundle. + + Args: + resource_rules: string, optional, path to the ResourceRules.plist file + to use, default to "${SDKROOT}/ResourceRules.plist" + + Returns: + Path to the copy of ResourceRules.plist into the bundle. + """ + source_path = resource_rules + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'ResourceRules.plist') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], 'ResourceRules.plist') + shutil.copy2(source_path, target_path) + return target_path + + def _InstallProvisioningProfile(self, profile, bundle_identifier): + """Installs embedded.mobileprovision into the bundle. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple containing two dictionary: variables substitutions and values + to overrides when generating the entitlements file. + """ + source_path, provisioning_data, team_id = self._FindProvisioningProfile( + profile, bundle_identifier) + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'embedded.mobileprovision') + shutil.copy2(source_path, target_path) + substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.') + return substitutions, provisioning_data['Entitlements'] + + def _FindProvisioningProfile(self, profile, bundle_identifier): + """Finds the .mobileprovision file to use for signing the bundle. + + Checks all the installed provisioning profiles (or if the user specified + the PROVISIONING_PROFILE variable, only consult it) and select the most + specific that correspond to the bundle identifier. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple of the path to the selected provisioning profile, the data of + the embedded plist in the provisioning profile and the team identifier + to use for code signing. + + Raises: + SystemExit: if no .mobileprovision can be used to sign the bundle. + """ + profiles_dir = os.path.join( + os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles') + if not os.path.isdir(profiles_dir): + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + provisioning_profiles = None + if profile: + profile_path = os.path.join(profiles_dir, profile + '.mobileprovision') + if os.path.exists(profile_path): + provisioning_profiles = [profile_path] + if not provisioning_profiles: + provisioning_profiles = glob.glob( + os.path.join(profiles_dir, '*.mobileprovision')) + valid_provisioning_profiles = {} + for profile_path in provisioning_profiles: + profile_data = self._LoadProvisioningProfile(profile_path) + app_id_pattern = profile_data.get( + 'Entitlements', {}).get('application-identifier', '') + for team_identifier in profile_data.get('TeamIdentifier', []): + app_id = '%s.%s' % (team_identifier, bundle_identifier) + if fnmatch.fnmatch(app_id, app_id_pattern): + valid_provisioning_profiles[app_id_pattern] = ( + profile_path, profile_data, team_identifier) + if not valid_provisioning_profiles: + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + # If the user has multiple provisioning profiles installed that can be + # used for ${bundle_identifier}, pick the most specific one (ie. the + # provisioning profile whose pattern is the longest). + selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) + return valid_provisioning_profiles[selected_key] + + def _LoadProvisioningProfile(self, profile_path): + """Extracts the plist embedded in a provisioning profile. + + Args: + profile_path: string, path to the .mobileprovision file + + Returns: + Content of the plist embedded in the provisioning profile as a dictionary. + """ + with tempfile.NamedTemporaryFile() as temp: + subprocess.check_call([ + 'security', 'cms', '-D', '-i', profile_path, '-o', temp.name]) + return self._LoadPlistMaybeBinary(temp.name) + + def _LoadPlistMaybeBinary(self, plist_path): + """Loads into a memory a plist possibly encoded in binary format. + + This is a wrapper around plistlib.readPlist that tries to convert the + plist to the XML format if it can't be parsed (assuming that it is in + the binary format). + + Args: + plist_path: string, path to a plist file, in XML or binary format + + Returns: + Content of the plist as a dictionary. + """ + try: + # First, try to read the file using plistlib that only supports XML, + # and if an exception is raised, convert a temporary copy to XML and + # load that copy. + return plistlib.readPlist(plist_path) + except: + pass + with tempfile.NamedTemporaryFile() as temp: + shutil.copy2(plist_path, temp.name) + subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) + return plistlib.readPlist(temp.name) + + def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): + """Constructs a dictionary of variable substitutions for Entitlements.plist. + + Args: + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + app_identifier_prefix: string, value for AppIdentifierPrefix + + Returns: + Dictionary of substitutions to apply when generating Entitlements.plist. + """ + return { + 'CFBundleIdentifier': bundle_identifier, + 'AppIdentifierPrefix': app_identifier_prefix, + } + + def _GetCFBundleIdentifier(self): + """Extracts CFBundleIdentifier value from Info.plist in the bundle. + + Returns: + Value of CFBundleIdentifier in the Info.plist located in the bundle. + """ + info_plist_path = os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['INFOPLIST_PATH']) + info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) + return info_plist_data['CFBundleIdentifier'] + + def _InstallEntitlements(self, entitlements, substitutions, overrides): + """Generates and install the ${BundleName}.xcent entitlements file. + + Expands variables "$(variable)" pattern in the source entitlements file, + add extra entitlements defined in the .mobileprovision file and the copy + the generated plist to "${BundlePath}.xcent". + + Args: + entitlements: string, optional, path to the Entitlements.plist template + to use, defaults to "${SDKROOT}/Entitlements.plist" + substitutions: dictionary, variable substitutions + overrides: dictionary, values to add to the entitlements + + Returns: + Path to the generated entitlements file. + """ + source_path = entitlements + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['PRODUCT_NAME'] + '.xcent') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], + 'Entitlements.plist') + shutil.copy2(source_path, target_path) + data = self._LoadPlistMaybeBinary(target_path) + data = self._ExpandVariables(data, substitutions) + if overrides: + for key in overrides: + if key not in data: + data[key] = overrides[key] + plistlib.writePlist(data, target_path) + return target_path + + def _ExpandVariables(self, data, substitutions): + """Expands variables "$(variable)" in data. + + Args: + data: object, can be either string, list or dictionary + substitutions: dictionary, variable substitutions to perform + + Returns: + Copy of data where each references to "$(variable)" has been replaced + by the corresponding value found in substitutions, or left intact if + the key was not found. + """ + if isinstance(data, str): + for key, value in substitutions.iteritems(): + data = data.replace('$(%s)' % key, value) + return data + if isinstance(data, list): + return [self._ExpandVariables(v, substitutions) for v in data] + if isinstance(data, dict): + return dict((k, self._ExpandVariables(data[k], + substitutions)) for k in data) + return data + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk new file mode 100644 index 0000000..d7f1cf6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk @@ -0,0 +1,172 @@ +# This file is generated by gyp; do not edit. + +TOOLSET := target +TARGET := kerberos +DEFS_Debug := \ + '-D_DARWIN_USE_64_BIT_INODE=1' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-D__MACOSX_CORE__' \ + '-DBUILDING_NODE_EXTENSION' \ + '-DDEBUG' \ + '-D_DEBUG' + +# Flags passed to all source files. +CFLAGS_Debug := \ + -O0 \ + -gdwarf-2 \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -Wall \ + -Wendif-labels \ + -W \ + -Wno-unused-parameter + +# Flags passed to only C files. +CFLAGS_C_Debug := \ + -fno-strict-aliasing + +# Flags passed to only C++ files. +CFLAGS_CC_Debug := \ + -fno-rtti \ + -fno-threadsafe-statics \ + -fno-strict-aliasing + +# Flags passed to only ObjC files. +CFLAGS_OBJC_Debug := + +# Flags passed to only ObjC++ files. +CFLAGS_OBJCC_Debug := + +INCS_Debug := \ + -I/Users/SEmmer/.node-gyp/0.12.0/src \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include \ + -I$(srcdir)/node_modules/nan \ + -I/usr/include/mit-krb5 + +DEFS_Release := \ + '-D_DARWIN_USE_64_BIT_INODE=1' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-D__MACOSX_CORE__' \ + '-DBUILDING_NODE_EXTENSION' + +# Flags passed to all source files. +CFLAGS_Release := \ + -Os \ + -gdwarf-2 \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -Wall \ + -Wendif-labels \ + -W \ + -Wno-unused-parameter + +# Flags passed to only C files. +CFLAGS_C_Release := \ + -fno-strict-aliasing + +# Flags passed to only C++ files. +CFLAGS_CC_Release := \ + -fno-rtti \ + -fno-threadsafe-statics \ + -fno-strict-aliasing + +# Flags passed to only ObjC files. +CFLAGS_OBJC_Release := + +# Flags passed to only ObjC++ files. +CFLAGS_OBJCC_Release := + +INCS_Release := \ + -I/Users/SEmmer/.node-gyp/0.12.0/src \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/uv/include \ + -I/Users/SEmmer/.node-gyp/0.12.0/deps/v8/include \ + -I$(srcdir)/node_modules/nan \ + -I/usr/include/mit-krb5 + +OBJS := \ + $(obj).target/$(TARGET)/lib/kerberos.o \ + $(obj).target/$(TARGET)/lib/worker.o \ + $(obj).target/$(TARGET)/lib/kerberosgss.o \ + $(obj).target/$(TARGET)/lib/base64.o \ + $(obj).target/$(TARGET)/lib/kerberos_context.o + +# Add to the list of files we specially track dependencies for. +all_deps += $(OBJS) + +# CFLAGS et al overrides must be target-local. +# See "Target-specific Variable Values" in the GNU Make manual. +$(OBJS): TOOLSET := $(TOOLSET) +$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) +$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) +$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) +$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) + +# Suffix rules, putting all outputs into $(obj). + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# End of this set of suffix rules +### Rules for final target. +LDFLAGS_Debug := \ + -Wl,-search_paths_first \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -L$(builddir) + +LIBTOOLFLAGS_Debug := \ + -Wl,-search_paths_first + +LDFLAGS_Release := \ + -Wl,-search_paths_first \ + -mmacosx-version-min=10.5 \ + -arch x86_64 \ + -L$(builddir) + +LIBTOOLFLAGS_Release := \ + -Wl,-search_paths_first + +LIBS := \ + -undefined dynamic_lookup \ + -lkrb5 + +$(builddir)/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) +$(builddir)/kerberos.node: LIBS := $(LIBS) +$(builddir)/kerberos.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) +$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) +$(builddir)/kerberos.node: $(OBJS) FORCE_DO_CMD + $(call do_cmd,solink_module) + +all_deps += $(builddir)/kerberos.node +# Add target alias +.PHONY: kerberos +kerberos: $(builddir)/kerberos.node + +# Short alias for building this executable. +.PHONY: kerberos.node +kerberos.node: $(builddir)/kerberos.node + +# Add executable to "all" target. +.PHONY: all +all: $(builddir)/kerberos.node + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js new file mode 100644 index 0000000..b8c8532 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js @@ -0,0 +1,6 @@ +// Get the Kerberos library +module.exports = require('./lib/kerberos'); +// Set up the auth processes +module.exports['processes'] = { + MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js new file mode 100644 index 0000000..f1e9231 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js @@ -0,0 +1,281 @@ +var format = require('util').format; + +var MongoAuthProcess = function(host, port, service_name) { + // Check what system we are on + if(process.platform == 'win32') { + this._processor = new Win32MongoProcessor(host, port, service_name); + } else { + this._processor = new UnixMongoProcessor(host, port, service_name); + } +} + +MongoAuthProcess.prototype.init = function(username, password, callback) { + this._processor.init(username, password, callback); +} + +MongoAuthProcess.prototype.transition = function(payload, callback) { + this._processor.transition(payload, callback); +} + +/******************************************************************* + * + * Win32 SSIP Processor for MongoDB + * + *******************************************************************/ +var Win32MongoProcessor = function(host, port, service_name) { + this.host = host; + this.port = port + // SSIP classes + this.ssip = require("../kerberos").SSIP; + // Set up first transition + this._transition = Win32MongoProcessor.first_transition(this); + // Set up service name + service_name = service_name || "mongodb"; + // Set up target + this.target = format("%s/%s", service_name, host); + // Number of retries + this.retries = 10; +} + +Win32MongoProcessor.prototype.init = function(username, password, callback) { + var self = this; + // Save the values used later + this.username = username; + this.password = password; + // Aquire credentials + this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { + if(err) return callback(err); + // Save credentials + self.security_credentials = security_credentials; + // Callback with success + callback(null); + }); +} + +Win32MongoProcessor.prototype.transition = function(payload, callback) { + if(this._transition == null) return callback(new Error("Transition finished")); + this._transition(payload, callback); +} + +Win32MongoProcessor.first_transition = function(self) { + return function(payload, callback) { + self.ssip.SecurityContext.initialize( + self.security_credentials, + self.target, + payload, function(err, security_context) { + if(err) return callback(err); + + // If no context try again until we have no more retries + if(!security_context.hasContext) { + if(self.retries == 0) return callback(new Error("Failed to initialize security context")); + // Update the number of retries + self.retries = self.retries - 1; + // Set next transition + return self.transition(payload, callback); + } + + // Set next transition + self._transition = Win32MongoProcessor.second_transition(self); + self.security_context = security_context; + // Return the payload + callback(null, security_context.payload); + }); + } +} + +Win32MongoProcessor.second_transition = function(self) { + return function(payload, callback) { + // Perform a step + self.security_context.initialize(self.target, payload, function(err, security_context) { + if(err) return callback(err); + + // If no context try again until we have no more retries + if(!security_context.hasContext) { + if(self.retries == 0) return callback(new Error("Failed to initialize security context")); + // Update the number of retries + self.retries = self.retries - 1; + // Set next transition + self._transition = Win32MongoProcessor.first_transition(self); + // Retry + return self.transition(payload, callback); + } + + // Set next transition + self._transition = Win32MongoProcessor.third_transition(self); + // Return the payload + callback(null, security_context.payload); + }); + } +} + +Win32MongoProcessor.third_transition = function(self) { + return function(payload, callback) { + var messageLength = 0; + // Get the raw bytes + var encryptedBytes = new Buffer(payload, 'base64'); + var encryptedMessage = new Buffer(messageLength); + // Copy first byte + encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); + // Set up trailer + var securityTrailerLength = encryptedBytes.length - messageLength; + var securityTrailer = new Buffer(securityTrailerLength); + // Copy the bytes + encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); + + // Types used + var SecurityBuffer = self.ssip.SecurityBuffer; + var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; + + // Set up security buffers + var buffers = [ + new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) + , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) + ]; + + // Set up the descriptor + var descriptor = new SecurityBufferDescriptor(buffers); + + // Decrypt the data + self.security_context.decryptMessage(descriptor, function(err, security_context) { + if(err) return callback(err); + + var length = 4; + if(self.username != null) { + length += self.username.length; + } + + var bytesReceivedFromServer = new Buffer(length); + bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION + bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION + bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION + bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION + + if(self.username != null) { + var authorization_id_bytes = new Buffer(self.username, 'utf8'); + authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); + } + + self.security_context.queryContextAttributes(0x00, function(err, sizes) { + if(err) return callback(err); + + var buffers = [ + new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) + , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) + , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) + ] + + var descriptor = new SecurityBufferDescriptor(buffers); + + self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { + if(err) return callback(err); + callback(null, security_context.payload); + }); + }); + }); + } +} + +/******************************************************************* + * + * UNIX MIT Kerberos processor + * + *******************************************************************/ +var UnixMongoProcessor = function(host, port, service_name) { + this.host = host; + this.port = port + // SSIP classes + this.Kerberos = require("../kerberos").Kerberos; + this.kerberos = new this.Kerberos(); + service_name = service_name || "mongodb"; + // Set up first transition + this._transition = UnixMongoProcessor.first_transition(this); + // Set up target + this.target = format("%s@%s", service_name, host); + // Number of retries + this.retries = 10; +} + +UnixMongoProcessor.prototype.init = function(username, password, callback) { + var self = this; + this.username = username; + this.password = password; + // Call client initiate + this.kerberos.authGSSClientInit( + self.target + , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { + self.context = context; + // Return the context + callback(null, context); + }); +} + +UnixMongoProcessor.prototype.transition = function(payload, callback) { + if(this._transition == null) return callback(new Error("Transition finished")); + this._transition(payload, callback); +} + +UnixMongoProcessor.first_transition = function(self) { + return function(payload, callback) { + self.kerberos.authGSSClientStep(self.context, '', function(err, result) { + if(err) return callback(err); + // Set up the next step + self._transition = UnixMongoProcessor.second_transition(self); + // Return the payload + callback(null, self.context.response); + }) + } +} + +UnixMongoProcessor.second_transition = function(self) { + return function(payload, callback) { + self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { + if(err && self.retries == 0) return callback(err); + // Attempt to re-establish a context + if(err) { + // Adjust the number of retries + self.retries = self.retries - 1; + // Call same step again + return self.transition(payload, callback); + } + + // Set up the next step + self._transition = UnixMongoProcessor.third_transition(self); + // Return the payload + callback(null, self.context.response || ''); + }); + } +} + +UnixMongoProcessor.third_transition = function(self) { + return function(payload, callback) { + // GSS Client Unwrap + self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { + if(err) return callback(err, false); + + // Wrap the response + self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { + if(err) return callback(err, false); + // Set up the next step + self._transition = UnixMongoProcessor.fourth_transition(self); + // Return the payload + callback(null, self.context.response); + }); + }); + } +} + +UnixMongoProcessor.fourth_transition = function(self) { + return function(payload, callback) { + // Clean up context + self.kerberos.authGSSClientClean(self.context, function(err, result) { + if(err) return callback(err, false); + // Set the transition to null + self._transition = null; + // Callback with valid authentication + callback(null, true); + }); + } +} + +// Set the process +exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c new file mode 100644 index 0000000..aca0a61 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +#include "base64.h" + +#include +#include +#include +#include + +void die2(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +// base64 tables +static char basis_64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static signed char index_64[128] = +{ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +}; +#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) + +// base64_encode : base64 encode +// +// value : data to encode +// vlen : length of data +// (result) : new char[] - c-str of result +char *base64_encode(const unsigned char *value, int vlen) +{ + char *result = (char *)malloc((vlen * 4) / 3 + 5); + if(result == NULL) die2("Memory allocation failed"); + char *out = result; + while (vlen >= 3) + { + *out++ = basis_64[value[0] >> 2]; + *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; + *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; + *out++ = basis_64[value[2] & 0x3F]; + value += 3; + vlen -= 3; + } + if (vlen > 0) + { + *out++ = basis_64[value[0] >> 2]; + unsigned char oval = (value[0] << 4) & 0x30; + if (vlen > 1) oval |= value[1] >> 4; + *out++ = basis_64[oval]; + *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; + *out++ = '='; + } + *out = '\0'; + + return result; +} + +// base64_decode : base64 decode +// +// value : c-str to decode +// rlen : length of decoded result +// (result) : new unsigned char[] - decoded result +unsigned char *base64_decode(const char *value, int *rlen) +{ + *rlen = 0; + int c1, c2, c3, c4; + + int vlen = strlen(value); + unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); + if(result == NULL) die2("Memory allocation failed"); + unsigned char *out = result; + + while (1) + { + if (value[0]==0) + return result; + c1 = value[0]; + if (CHAR64(c1) == -1) + goto base64_decode_error;; + c2 = value[1]; + if (CHAR64(c2) == -1) + goto base64_decode_error;; + c3 = value[2]; + if ((c3 != '=') && (CHAR64(c3) == -1)) + goto base64_decode_error;; + c4 = value[3]; + if ((c4 != '=') && (CHAR64(c4) == -1)) + goto base64_decode_error;; + + value += 4; + *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); + *rlen += 1; + if (c3 != '=') + { + *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); + *rlen += 1; + if (c4 != '=') + { + *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); + *rlen += 1; + } + } + } + +base64_decode_error: + *result = 0; + *rlen = 0; + return result; +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h new file mode 100644 index 0000000..9152e6a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h @@ -0,0 +1,22 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +#ifndef BASE64_H +#define BASE64_H + +char *base64_encode(const unsigned char *value, int vlen); +unsigned char *base64_decode(const char *value, int *rlen); + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc new file mode 100644 index 0000000..7744a9d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc @@ -0,0 +1,592 @@ +#include "kerberos.h" +#include +#include +#include "worker.h" +#include "kerberos_context.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +void die(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +// Call structs +typedef struct AuthGSSClientCall { + uint32_t flags; + char *uri; +} AuthGSSClientCall; + +typedef struct AuthGSSClientStepCall { + KerberosContext *context; + char *challenge; +} AuthGSSClientStepCall; + +typedef struct AuthGSSClientUnwrapCall { + KerberosContext *context; + char *challenge; +} AuthGSSClientUnwrapCall; + +typedef struct AuthGSSClientWrapCall { + KerberosContext *context; + char *challenge; + char *user_name; +} AuthGSSClientWrapCall; + +typedef struct AuthGSSClientCleanCall { + KerberosContext *context; +} AuthGSSClientCleanCall; + +Kerberos::Kerberos() : ObjectWrap() { +} + +Persistent Kerberos::constructor_template; + +void Kerberos::Initialize(v8::Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("Kerberos")); + + // Set up method for the Kerberos instance + NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientInit", AuthGSSClientInit); + NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientStep", AuthGSSClientStep); + NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientUnwrap", AuthGSSClientUnwrap); + NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientWrap", AuthGSSClientWrap); + NODE_SET_PROTOTYPE_METHOD(t, "authGSSClientClean", AuthGSSClientClean); + + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("Kerberos"), t->GetFunction()); +} + +NAN_METHOD(Kerberos::New) { + NanScope(); + // Create a Kerberos instance + Kerberos *kerberos = new Kerberos(); + // Return the kerberos object + kerberos->Wrap(args.This()); + NanReturnValue(args.This()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientInit(Worker *worker) { + gss_client_state *state; + gss_client_response *response; + + // Allocate state + state = (gss_client_state *)malloc(sizeof(gss_client_state)); + if(state == NULL) die("Memory allocation failed"); + + // Unpack the parameter data struct + AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; + // Start the kerberos client + response = authenticate_gss_client_init(call->uri, call->flags, state); + + // Release the parameter struct memory + free(call->uri); + free(call); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + free(state); + } else { + worker->return_value = state; + } + + // Free structure + free(response); +} + +static Handle _map_authGSSClientInit(Worker *worker) { + KerberosContext *context = KerberosContext::New(); + context->state = (gss_client_state *)worker->return_value; + return NanObjectWrapHandle(context); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientInit) { + NanScope(); + + // Ensure valid call + if(args.Length() != 3) return NanThrowError("Requires a service string uri, integer flags and a callback function"); + if(args.Length() == 3 && !args[0]->IsString() && !args[1]->IsInt32() && !args[2]->IsFunction()) + return NanThrowError("Requires a service string uri, integer flags and a callback function"); + + Local service = args[0]->ToString(); + // Convert uri string to c-string + char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); + if(service_str == NULL) die("Memory allocation failed"); + + // Write v8 string to c-string + service->WriteUtf8(service_str); + + // Allocate a structure + AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); + if(call == NULL) die("Memory allocation failed"); + call->flags =args[1]->ToInt32()->Uint32Value(); + call->uri = service_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(args[2]); + NanCallback *callback = new NanCallback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientInit; + worker->mapper = _map_authGSSClientInit; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientStep +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientStep(Worker *worker) { + gss_client_state *state; + gss_client_response *response; + char *challenge; + + // Unpack the parameter data struct + AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; + // Get the state + state = call->context->state; + challenge = call->challenge; + + // Check what kind of challenge we have + if(call->challenge == NULL) { + challenge = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_step(state, challenge); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + free(call); + free(response); +} + +static Handle _map_authGSSClientStep(Worker *worker) { + NanScope(); + // Return the return code + return NanNew(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientStep) { + NanScope(); + + // Ensure valid call + if(args.Length() != 2 && args.Length() != 3) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); + if(args.Length() == 2 && !KerberosContext::HasInstance(args[0])) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); + if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString()) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); + + // Challenge string + char *challenge_str = NULL; + // Let's unpack the parameters + Local object = args[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + // If we have a challenge string + if(args.Length() == 3) { + // Unpack the challenge string + Local challenge = args[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + } + + // Allocate a structure + AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(args[2]); + NanCallback *callback = new NanCallback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientStep; + worker->mapper = _map_authGSSClientStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientUnwrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientUnwrap(Worker *worker) { + gss_client_response *response; + char *challenge; + + // Unpack the parameter data struct + AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; + challenge = call->challenge; + + // Check what kind of challenge we have + if(call->challenge == NULL) { + challenge = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_unwrap(call->context->state, challenge); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + free(call); + free(response); +} + +static Handle _map_authGSSClientUnwrap(Worker *worker) { + NanScope(); + // Return the return code + return NanNew(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientUnwrap) { + NanScope(); + + // Ensure valid call + if(args.Length() != 2 && args.Length() != 3) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); + if(args.Length() == 2 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); + if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return NanThrowError("Requires a GSS context, optional challenge string and callback function"); + + // Challenge string + char *challenge_str = NULL; + // Let's unpack the parameters + Local object = args[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + // If we have a challenge string + if(args.Length() == 3) { + // Unpack the challenge string + Local challenge = args[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + } + + // Allocate a structure + AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + + // Unpack the callback + Local callbackHandle = args.Length() == 3 ? Local::Cast(args[2]) : Local::Cast(args[1]); + NanCallback *callback = new NanCallback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientUnwrap; + worker->mapper = _map_authGSSClientUnwrap; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + // return scope.Close(NanUndefined()); + NanReturnValue(NanUndefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientWrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientWrap(Worker *worker) { + gss_client_response *response; + char *user_name = NULL; + + // Unpack the parameter data struct + AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; + user_name = call->user_name; + + // Check what kind of challenge we have + if(call->user_name == NULL) { + user_name = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + if(call->user_name != NULL) free(call->user_name); + free(call); + free(response); +} + +static Handle _map_authGSSClientWrap(Worker *worker) { + NanScope(); + // Return the return code + return NanNew(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientWrap) { + NanScope(); + + // Ensure valid call + if(args.Length() != 3 && args.Length() != 4) return NanThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return NanThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + if(args.Length() == 4 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsString() && !args[2]->IsFunction()) return NanThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + + // Challenge string + char *challenge_str = NULL; + char *user_name_str = NULL; + + // Let's unpack the kerberos context + Local object = args[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + // Unpack the challenge string + Local challenge = args[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + + // If we have a user string + if(args.Length() == 4) { + // Unpack user name + Local user_name = args[2]->ToString(); + // Convert uri string to c-string + user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); + if(user_name_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + user_name->WriteUtf8(user_name_str); + } + + // Allocate a structure + AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + call->user_name = user_name_str; + + // Unpack the callback + Local callbackHandle = args.Length() == 4 ? Local::Cast(args[3]) : Local::Cast(args[2]); + NanCallback *callback = new NanCallback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientWrap; + worker->mapper = _map_authGSSClientWrap; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientWrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientClean(Worker *worker) { + gss_client_response *response; + + // Unpack the parameter data struct + AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; + + // Perform authentication step + response = authenticate_gss_client_clean(call->context->state); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + free(call); + free(response); +} + +static Handle _map_authGSSClientClean(Worker *worker) { + NanScope(); + // Return the return code + return NanNew(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientClean) { + NanScope(); + + // // Ensure valid call + if(args.Length() != 2) return NanThrowError("Requires a GSS context and callback function"); + if(!KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return NanThrowError("Requires a GSS context and callback function"); + + // Let's unpack the kerberos context + Local object = args[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + // Allocate a structure + AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + + // Unpack the callback + Local callbackHandle = Local::Cast(args[1]); + NanCallback *callback = new NanCallback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientClean; + worker->mapper = _map_authGSSClientClean; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +void Kerberos::Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +void Kerberos::After(uv_work_t* work_req) { + // Grab the scope of the call from Node + NanScope(); + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(NanNew(worker->error_message)); + Local obj = err->ToObject(); + obj->Set(NanNew("code"), NanNew(worker->error_code)); + Local args[2] = { err, NanNull() }; + // Execute the error + v8::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(args), args); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + } else { + // // Map the data + Handle result = worker->mapper(worker); + // Set up the callback with a null first + Handle args[2] = { NanNull(), result}; + + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + v8::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(args), args); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + +// Exporting function +extern "C" void init(Handle target) { + NanScope(); + Kerberos::Initialize(target); + KerberosContext::Initialize(target); +} + +NODE_MODULE(kerberos, init); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h new file mode 100644 index 0000000..0f0e349 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h @@ -0,0 +1,47 @@ +#ifndef KERBEROS_H +#define KERBEROS_H + +#include +#include +#include +#include + +#include "nan.h" +#include +#include + +extern "C" { + #include "kerberosgss.h" +} + +using namespace v8; +using namespace node; + +class Kerberos : public ObjectWrap { + +public: + Kerberos(); + ~Kerberos() {}; + + // Constructor used for creating new Kerberos objects from C++ + static Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Handle target); + + // Method available + static NAN_METHOD(AuthGSSClientInit); + static NAN_METHOD(AuthGSSClientStep); + static NAN_METHOD(AuthGSSClientUnwrap); + static NAN_METHOD(AuthGSSClientWrap); + static NAN_METHOD(AuthGSSClientClean); + +private: + static NAN_METHOD(New); + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js new file mode 100644 index 0000000..b1a701b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js @@ -0,0 +1,91 @@ +var kerberos = require('../build/Release/kerberos') + , KerberosNative = kerberos.Kerberos; + +var Kerberos = function() { + this._native_kerberos = new KerberosNative(); +} + +Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { + return this._native_kerberos.authGSSClientInit(uri, flags, callback); +} + +Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { + if(typeof challenge == 'function') { + callback = challenge; + challenge = ''; + } + + return this._native_kerberos.authGSSClientStep(context, challenge, callback); +} + +Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { + if(typeof challenge == 'function') { + callback = challenge; + challenge = ''; + } + + return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); +} + +Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { + if(typeof user_name == 'function') { + callback = user_name; + user_name = ''; + } + + return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); +} + +Kerberos.prototype.authGSSClientClean = function(context, callback) { + return this._native_kerberos.authGSSClientClean(context, callback); +} + +Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { + return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); +} + +Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { + return this._native_kerberos.prepareOutboundPackage(principal, inputdata); +} + +Kerberos.prototype.decryptMessage = function(challenge) { + return this._native_kerberos.decryptMessage(challenge); +} + +Kerberos.prototype.encryptMessage = function(challenge) { + return this._native_kerberos.encryptMessage(challenge); +} + +Kerberos.prototype.queryContextAttribute = function(attribute) { + if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); + return this._native_kerberos.queryContextAttribute(attribute); +} + +// Some useful result codes +Kerberos.AUTH_GSS_CONTINUE = 0; +Kerberos.AUTH_GSS_COMPLETE = 1; + +// Some useful gss flags +Kerberos.GSS_C_DELEG_FLAG = 1; +Kerberos.GSS_C_MUTUAL_FLAG = 2; +Kerberos.GSS_C_REPLAY_FLAG = 4; +Kerberos.GSS_C_SEQUENCE_FLAG = 8; +Kerberos.GSS_C_CONF_FLAG = 16; +Kerberos.GSS_C_INTEG_FLAG = 32; +Kerberos.GSS_C_ANON_FLAG = 64; +Kerberos.GSS_C_PROT_READY_FLAG = 128; +Kerberos.GSS_C_TRANS_FLAG = 256; + +// Export Kerberos class +exports.Kerberos = Kerberos; + +// If we have SSPI (windows) +if(kerberos.SecurityCredentials) { + // Put all SSPI classes in it's own namespace + exports.SSIP = { + SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials + , SecurityContext: require('./win32/wrappers/security_context').SecurityContext + , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer + , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor + } +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc new file mode 100644 index 0000000..cc38e0d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc @@ -0,0 +1,77 @@ +#include "kerberos_context.h" + +Persistent KerberosContext::constructor_template; + +KerberosContext::KerberosContext() : ObjectWrap() { +} + +KerberosContext::~KerberosContext() { +} + +KerberosContext* KerberosContext::New() { + NanScope(); + Local obj = NanNew(constructor_template)->GetFunction()->NewInstance(); + KerberosContext *kerberos_context = ObjectWrap::Unwrap(obj); + return kerberos_context; +} + +NAN_METHOD(KerberosContext::New) { + NanScope(); + // Create code object + KerberosContext *kerberos_context = new KerberosContext(); + // Wrap it + kerberos_context->Wrap(args.This()); + // Return the object + NanReturnValue(args.This()); +} + +void KerberosContext::Initialize(v8::Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + // Local t = NanNew(New); + Local t = NanNew(static_cast(New)); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("KerberosContext")); + + // Get prototype + Local proto = t->PrototypeTemplate(); + + // Getter for the response + proto->SetAccessor(NanNew("response"), KerberosContext::ResponseGetter); + + // Set persistent + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("KerberosContext"), t->GetFunction()); +} + +// +// Response Setter / Getter +NAN_GETTER(KerberosContext::ResponseGetter) { + NanScope(); + gss_client_state *state; + + // Unpack the object + KerberosContext *context = ObjectWrap::Unwrap(args.This()); + // Let's grab the response + state = context->state; + // No state no response + if(state == NULL || state->response == NULL) { + NanReturnValue(NanNull()); + } else { + // Return the response + NanReturnValue(NanNew(state->response)); + } +} + + + + + + + + + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h new file mode 100644 index 0000000..dd00f1d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h @@ -0,0 +1,48 @@ +#ifndef KERBEROS_CONTEXT_H +#define KERBEROS_CONTEXT_H + +#include +#include +#include +#include + +#include "nan.h" +#include +#include + +extern "C" { + #include "kerberosgss.h" +} + +using namespace v8; +using namespace node; + +class KerberosContext : public ObjectWrap { + +public: + KerberosContext(); + ~KerberosContext(); + + static inline bool HasInstance(Handle val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return NanNew(constructor_template)->HasInstance(obj); + }; + + // Constructor used for creating new Kerberos objects from C++ + static Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Handle target); + + // Public constructor + static KerberosContext* New(); + + // Handle to the kerberos context + gss_client_state *state; + +private: + static NAN_METHOD(New); + static NAN_GETTER(ResponseGetter); +}; +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c new file mode 100644 index 0000000..8e55b62 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c @@ -0,0 +1,693 @@ +/** + * Copyright (c) 2006-2010 Apple Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +#include "kerberosgss.h" + +#include "base64.h" + +#include +#include +#include +#include +#include + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +void die1(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min); + +/*extern PyObject *GssException_class; +extern PyObject *KrbException_class; + +char* server_principal_details(const char* service, const char* hostname) +{ + char match[1024]; + int match_len = 0; + char* result = NULL; + + int code; + krb5_context kcontext; + krb5_keytab kt = NULL; + krb5_kt_cursor cursor = NULL; + krb5_keytab_entry entry; + char* pname = NULL; + + // Generate the principal prefix we want to match + snprintf(match, 1024, "%s/%s@", service, hostname); + match_len = strlen(match); + + code = krb5_init_context(&kcontext); + if (code) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot initialize Kerberos5 context", code)); + return NULL; + } + + if ((code = krb5_kt_default(kcontext, &kt))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot get default keytab", code)); + goto end; + } + + if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot get sequence cursor from keytab", code)); + goto end; + } + + while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) + { + if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot parse principal name from keytab", code)); + goto end; + } + + if (strncmp(pname, match, match_len) == 0) + { + result = malloc(strlen(pname) + 1); + strcpy(result, pname); + krb5_free_unparsed_name(kcontext, pname); + krb5_free_keytab_entry_contents(kcontext, &entry); + break; + } + + krb5_free_unparsed_name(kcontext, pname); + krb5_free_keytab_entry_contents(kcontext, &entry); + } + + if (result == NULL) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Principal not found in keytab", -1)); + } + +end: + if (cursor) + krb5_kt_end_seq_get(kcontext, kt, &cursor); + if (kt) + krb5_kt_close(kcontext, kt); + krb5_free_context(kcontext); + + return result; +} +*/ +gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; + gss_client_response *response = NULL; + int ret = AUTH_GSS_COMPLETE; + + state->server_name = GSS_C_NO_NAME; + state->context = GSS_C_NO_CONTEXT; + state->gss_flags = gss_flags; + state->username = NULL; + state->response = NULL; + + // Import server name first + name_token.length = strlen(service); + name_token.value = (char *)service; + + maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); + + if (GSS_ERROR(maj_stat)) { + response = gss_error(maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + +end: + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + return response; +} + +gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { + OM_uint32 min_stat; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + + if(state->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); + + if(state->server_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->server_name); + + if(state->username != NULL) { + free(state->username); + state->username = NULL; + } + + if (state->response != NULL) { + free(state->response); + state->response = NULL; + } + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + return response; +} + +gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + + // Always clear out the old response + if (state->response != NULL) { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if (challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + // Do GSSAPI step + maj_stat = gss_init_sec_context(&min_stat, + GSS_C_NO_CREDENTIAL, + &state->context, + state->server_name, + GSS_C_NO_OID, + (OM_uint32)state->gss_flags, + 0, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + NULL, + &output_token, + NULL, + NULL); + + if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { + response = gss_error(maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; + // Grab the client response to send back to the server + if(output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + maj_stat = gss_release_buffer(&min_stat, &output_token); + } + + // Try to get the user name if we have completed all GSS operations + if (ret == AUTH_GSS_COMPLETE) { + gss_name_t gssuser = GSS_C_NO_NAME; + maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); + + if(GSS_ERROR(maj_stat)) { + response = gss_error(maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + gss_buffer_desc name_token; + name_token.length = 0; + maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); + + if(GSS_ERROR(maj_stat)) { + if(name_token.value) + gss_release_buffer(&min_stat, &name_token); + gss_release_name(&min_stat, &gssuser); + + response = gss_error(maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else { + state->username = (char *)malloc(name_token.length + 1); + if(state->username == NULL) die1("Memory allocation failed"); + strncpy(state->username, (char*) name_token.value, name_token.length); + state->username[name_token.length] = 0; + gss_release_buffer(&min_stat, &name_token); + gss_release_name(&min_stat, &gssuser); + } + } + +end: + if(output_token.value) + gss_release_buffer(&min_stat, &output_token); + if(input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + gss_client_response *response = NULL; + int ret = AUTH_GSS_CONTINUE; + + // Always clear out the old response + if(state->response != NULL) { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if(challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + // Do GSSAPI step + maj_stat = gss_unwrap(&min_stat, + state->context, + &input_token, + &output_token, + NULL, + NULL); + + if(maj_stat != GSS_S_COMPLETE) { + response = gss_error(maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else { + ret = AUTH_GSS_COMPLETE; + } + + // Grab the client response + if(output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + } +end: + if(output_token.value) + gss_release_buffer(&min_stat, &output_token); + if(input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + char buf[4096], server_conf_flags; + unsigned long buf_size; + + // Always clear out the old response + if(state->response != NULL) { + free(state->response); + state->response = NULL; + } + + if(challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + if(user) { + // get bufsize + server_conf_flags = ((char*) input_token.value)[0]; + ((char*) input_token.value)[0] = 0; + buf_size = ntohl(*((long *) input_token.value)); + free(input_token.value); +#ifdef PRINTFS + printf("User: %s, %c%c%c\n", user, + server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', + server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', + server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); + printf("Maximum GSS token size is %ld\n", buf_size); +#endif + + // agree to terms (hack!) + buf_size = htonl(buf_size); // not relevant without integrity/privacy + memcpy(buf, &buf_size, 4); + buf[0] = GSS_AUTH_P_NONE; + // server decides if principal can log in as user + strncpy(buf + 4, user, sizeof(buf) - 4); + input_token.value = buf; + input_token.length = 4 + strlen(user); + } + + // Do GSSAPI wrap + maj_stat = gss_wrap(&min_stat, + state->context, + 0, + GSS_C_QOP_DEFAULT, + &input_token, + NULL, + &output_token); + + if (maj_stat != GSS_S_COMPLETE) { + response = gss_error(maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else + ret = AUTH_GSS_COMPLETE; + // Grab the client response to send back to the server + if (output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; + gss_release_buffer(&min_stat, &output_token); + } +end: + if (output_token.value) + gss_release_buffer(&min_stat, &output_token); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +int authenticate_gss_server_init(const char *service, gss_server_state *state) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_COMPLETE; + + state->context = GSS_C_NO_CONTEXT; + state->server_name = GSS_C_NO_NAME; + state->client_name = GSS_C_NO_NAME; + state->server_creds = GSS_C_NO_CREDENTIAL; + state->client_creds = GSS_C_NO_CREDENTIAL; + state->username = NULL; + state->targetname = NULL; + state->response = NULL; + + // Server name may be empty which means we aren't going to create our own creds + size_t service_len = strlen(service); + if (service_len != 0) + { + // Import server name first + name_token.length = strlen(service); + name_token.value = (char *)service; + + maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); + + if (GSS_ERROR(maj_stat)) + { + set_gss_error(maj_stat, min_stat); + ret = AUTH_GSS_ERROR; + goto end; + } + + // Get credentials + maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, GSS_C_ACCEPT, &state->server_creds, NULL, NULL); + + if (GSS_ERROR(maj_stat)) + { + set_gss_error(maj_stat, min_stat); + ret = AUTH_GSS_ERROR; + goto end; + } + } + +end: + return ret; +} + +int authenticate_gss_server_clean(gss_server_state *state) +{ + OM_uint32 min_stat; + int ret = AUTH_GSS_COMPLETE; + + if (state->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); + if (state->server_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->server_name); + if (state->client_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->client_name); + if (state->server_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&min_stat, &state->server_creds); + if (state->client_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&min_stat, &state->client_creds); + if (state->username != NULL) + { + free(state->username); + state->username = NULL; + } + if (state->targetname != NULL) + { + free(state->targetname); + state->targetname = NULL; + } + if (state->response != NULL) + { + free(state->response); + state->response = NULL; + } + + return ret; +} + +/*int authenticate_gss_server_step(gss_server_state *state, const char *challenge) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + + // Always clear out the old response + if (state->response != NULL) + { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if (challenge && *challenge) + { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + else + { + PyErr_SetString(KrbException_class, "No challenge parameter in request from client"); + ret = AUTH_GSS_ERROR; + goto end; + } + + maj_stat = gss_accept_sec_context(&min_stat, + &state->context, + state->server_creds, + &input_token, + GSS_C_NO_CHANNEL_BINDINGS, + &state->client_name, + NULL, + &output_token, + NULL, + NULL, + &state->client_creds); + + if (GSS_ERROR(maj_stat)) + { + set_gss_error(maj_stat, min_stat); + ret = AUTH_GSS_ERROR; + goto end; + } + + // Grab the server response to send back to the client + if (output_token.length) + { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; + maj_stat = gss_release_buffer(&min_stat, &output_token); + } + + // Get the user name + maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); + if (GSS_ERROR(maj_stat)) + { + set_gss_error(maj_stat, min_stat); + ret = AUTH_GSS_ERROR; + goto end; + } + state->username = (char *)malloc(output_token.length + 1); + strncpy(state->username, (char*) output_token.value, output_token.length); + state->username[output_token.length] = 0; + + // Get the target name if no server creds were supplied + if (state->server_creds == GSS_C_NO_CREDENTIAL) + { + gss_name_t target_name = GSS_C_NO_NAME; + maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); + if (GSS_ERROR(maj_stat)) + { + set_gss_error(maj_stat, min_stat); + ret = AUTH_GSS_ERROR; + goto end; + } + maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); + if (GSS_ERROR(maj_stat)) + { + set_gss_error(maj_stat, min_stat); + ret = AUTH_GSS_ERROR; + goto end; + } + state->targetname = (char *)malloc(output_token.length + 1); + strncpy(state->targetname, (char*) output_token.value, output_token.length); + state->targetname[output_token.length] = 0; + } + + ret = AUTH_GSS_COMPLETE; + +end: + if (output_token.length) + gss_release_buffer(&min_stat, &output_token); + if (input_token.value) + free(input_token.value); + return ret; +} +*/ + +static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min) { + OM_uint32 maj_stat, min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string; + char buf_maj[512]; + char buf_min[512]; + + do { + maj_stat = gss_display_status (&min_stat, + err_maj, + GSS_C_GSS_CODE, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(GSS_ERROR(maj_stat)) + break; + + strncpy(buf_maj, (char*) status_string.value, sizeof(buf_maj)); + gss_release_buffer(&min_stat, &status_string); + + maj_stat = gss_display_status (&min_stat, + err_min, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, + &status_string); + if (!GSS_ERROR(maj_stat)) { + + strncpy(buf_min, (char*) status_string.value , sizeof(buf_min)); + gss_release_buffer(&min_stat, &status_string); + } + } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); +} + +gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min) { + OM_uint32 maj_stat, min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string; + char *buf_maj = calloc(512, sizeof(char)); + if(buf_maj == NULL) die1("Memory allocation failed"); + char *buf_min = calloc(512, sizeof(char)); + if(buf_min == NULL) die1("Memory allocation failed"); + char *message = NULL; + gss_client_response *response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + + do { + maj_stat = gss_display_status (&min_stat, + err_maj, + GSS_C_GSS_CODE, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(GSS_ERROR(maj_stat)) + break; + + strncpy(buf_maj, (char*) status_string.value, 512); + gss_release_buffer(&min_stat, &status_string); + + maj_stat = gss_display_status (&min_stat, + err_min, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, + &status_string); + if(!GSS_ERROR(maj_stat)) { + strncpy(buf_min, (char*) status_string.value , 512); + gss_release_buffer(&min_stat, &status_string); + } + } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); + + // Join the strings + message = calloc(1026, 1); + if(message == NULL) die1("Memory allocation failed"); + // Join the two messages + sprintf(message, "%s, %s", buf_maj, buf_min); + // Free data + free(buf_min); + free(buf_maj); + // Set the message + response->message = message; + // Return the message + return response; +} + +#pragma clang diagnostic pop + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h new file mode 100644 index 0000000..58ac0b7 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2006-2009 Apple Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +#ifndef KERBEROS_GSS_H +#define KERBEROS_GSS_H + +#include +#include +#include + +#define krb5_get_err_text(context,code) error_message(code) + +#define AUTH_GSS_ERROR -1 +#define AUTH_GSS_COMPLETE 1 +#define AUTH_GSS_CONTINUE 0 + +#define GSS_AUTH_P_NONE 1 +#define GSS_AUTH_P_INTEGRITY 2 +#define GSS_AUTH_P_PRIVACY 4 + +typedef struct { + int return_code; + char *message; +} gss_client_response; + +typedef struct { + gss_ctx_id_t context; + gss_name_t server_name; + long int gss_flags; + char* username; + char* response; +} gss_client_state; + +typedef struct { + gss_ctx_id_t context; + gss_name_t server_name; + gss_name_t client_name; + gss_cred_id_t server_creds; + gss_cred_id_t client_creds; + char* username; + char* targetname; + char* response; +} gss_server_state; + +// char* server_principal_details(const char* service, const char* hostname); + +gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); +gss_client_response *authenticate_gss_client_clean(gss_client_state *state); +gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); +gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); +gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); + +int authenticate_gss_server_init(const char* service, gss_server_state* state); +int authenticate_gss_server_clean(gss_server_state *state); +// int authenticate_gss_server_step(gss_server_state *state, const char *challenge); + +gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min); +#endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js new file mode 100644 index 0000000..d9120fb --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js @@ -0,0 +1,15 @@ +// Load the native SSPI classes +var kerberos = require('../build/Release/kerberos') + , Kerberos = kerberos.Kerberos + , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer + , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor + , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials + , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; +var SSPI = function() { +} + +exports.SSPI = SSPI; +exports.SecurityBuffer = SecurityBuffer; +exports.SecurityBufferDescriptor = SecurityBufferDescriptor; +exports.SecurityCredentials = SecurityCredentials; +exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c new file mode 100644 index 0000000..502a021 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +#include "base64.h" + +#include +#include + +// base64 tables +static char basis_64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static signed char index_64[128] = +{ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +}; +#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) + +// base64_encode : base64 encode +// +// value : data to encode +// vlen : length of data +// (result) : new char[] - c-str of result +char *base64_encode(const unsigned char *value, int vlen) +{ + char *result = (char *)malloc((vlen * 4) / 3 + 5); + char *out = result; + unsigned char oval; + + while (vlen >= 3) + { + *out++ = basis_64[value[0] >> 2]; + *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; + *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; + *out++ = basis_64[value[2] & 0x3F]; + value += 3; + vlen -= 3; + } + if (vlen > 0) + { + *out++ = basis_64[value[0] >> 2]; + oval = (value[0] << 4) & 0x30; + if (vlen > 1) oval |= value[1] >> 4; + *out++ = basis_64[oval]; + *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; + *out++ = '='; + } + *out = '\0'; + + return result; +} + +// base64_decode : base64 decode +// +// value : c-str to decode +// rlen : length of decoded result +// (result) : new unsigned char[] - decoded result +unsigned char *base64_decode(const char *value, int *rlen) +{ + int c1, c2, c3, c4; + int vlen = (int)strlen(value); + unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); + unsigned char *out = result; + *rlen = 0; + + while (1) + { + if (value[0]==0) + return result; + c1 = value[0]; + if (CHAR64(c1) == -1) + goto base64_decode_error;; + c2 = value[1]; + if (CHAR64(c2) == -1) + goto base64_decode_error;; + c3 = value[2]; + if ((c3 != '=') && (CHAR64(c3) == -1)) + goto base64_decode_error;; + c4 = value[3]; + if ((c4 != '=') && (CHAR64(c4) == -1)) + goto base64_decode_error;; + + value += 4; + *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); + *rlen += 1; + if (c3 != '=') + { + *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); + *rlen += 1; + if (c4 != '=') + { + *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); + *rlen += 1; + } + } + } + +base64_decode_error: + *result = 0; + *rlen = 0; + return result; +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h new file mode 100644 index 0000000..f0e1f06 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +char *base64_encode(const unsigned char *value, int vlen); +unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc new file mode 100644 index 0000000..c40be18 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc @@ -0,0 +1,53 @@ +#include "kerberos.h" +#include +#include +#include "base64.h" +#include "wrappers/security_buffer.h" +#include "wrappers/security_buffer_descriptor.h" +#include "wrappers/security_context.h" +#include "wrappers/security_credentials.h" + +Persistent Kerberos::constructor_template; + +Kerberos::Kerberos() : ObjectWrap() { +} + +void Kerberos::Initialize(v8::Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("Kerberos")); + + // Set persistent + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("Kerberos"), t->GetFunction()); +} + +NAN_METHOD(Kerberos::New) { + NanScope(); + // Load the security.dll library + load_library(); + // Create a Kerberos instance + Kerberos *kerberos = new Kerberos(); + // Return the kerberos object + kerberos->Wrap(args.This()); + // Return the object + NanReturnValue(args.This()); +} + +// Exporting function +extern "C" void init(Handle target) { + NanScope(); + Kerberos::Initialize(target); + SecurityContext::Initialize(target); + SecurityBuffer::Initialize(target); + SecurityBufferDescriptor::Initialize(target); + SecurityCredentials::Initialize(target); +} + +NODE_MODULE(kerberos, init); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h new file mode 100644 index 0000000..579d04e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h @@ -0,0 +1,60 @@ +#ifndef KERBEROS_H +#define KERBEROS_H + +#include +#include +#include +#include "nan.h" + +extern "C" { + #include "kerberos_sspi.h" + #include "base64.h" +} + +using namespace v8; +using namespace node; + +class Kerberos : public ObjectWrap { + +public: + Kerberos(); + ~Kerberos() {}; + + // Constructor used for creating new Kerberos objects from C++ + static Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Handle target); + + // Method available + static NAN_METHOD(AcquireAlternateCredentials); + static NAN_METHOD(PrepareOutboundPackage); + static NAN_METHOD(DecryptMessage); + static NAN_METHOD(EncryptMessage); + static NAN_METHOD(QueryContextAttributes); + +private: + static NAN_METHOD(New); + + // Pointer to context object + SEC_WINNT_AUTH_IDENTITY m_Identity; + // credentials + CredHandle m_Credentials; + // Expiry time for ticket + TimeStamp Expiration; + // package info + SecPkgInfo m_PkgInfo; + // context + CtxtHandle m_Context; + // Do we have a context + bool m_HaveContext; + // Attributes + DWORD CtxtAttr; + + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c new file mode 100644 index 0000000..d75c9ab --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c @@ -0,0 +1,244 @@ +#include "kerberos_sspi.h" +#include +#include + +static HINSTANCE _sspi_security_dll = NULL; +static HINSTANCE _sspi_secur32_dll = NULL; + +/** + * Encrypt A Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { + // Create function pointer instance + encryptMessage_fn pfn_encryptMessage = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function to library method + pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); + // Check if the we managed to map function pointer + if(!pfn_encryptMessage) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); +} + +/** + * Acquire Credentials + */ +SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( + LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, + void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, + PCredHandle phCredential, PTimeStamp ptsExpiry +) { + SECURITY_STATUS status; + // Create function pointer instance + acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function + #ifdef _UNICODE + pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); + #else + pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_acquireCredentialsHandle) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Status + status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, + pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry + ); + + // Call the function + return status; +} + +/** + * Delete Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { + // Create function pointer instance + deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + // Map function + pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); + + // Check if the we managed to map function pointer + if(!pfn_deleteSecurityContext) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_deleteSecurityContext)(phContext); +} + +/** + * Decrypt Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { + // Create function pointer instance + decryptMessage_fn pfn_decryptMessage = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + // Map function + pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); + + // Check if the we managed to map function pointer + if(!pfn_decryptMessage) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); +} + +/** + * Initialize Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( + PCredHandle phCredential, PCtxtHandle phContext, + LPSTR pszTargetName, unsigned long fContextReq, + unsigned long Reserved1, unsigned long TargetDataRep, + PSecBufferDesc pInput, unsigned long Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, + unsigned long * pfContextAttr, PTimeStamp ptsExpiry +) { + SECURITY_STATUS status; + // Create function pointer instance + initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function + #ifdef _UNICODE + pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); + #else + pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_initializeSecurityContext) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Execute intialize context + status = (*pfn_initializeSecurityContext)( + phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry + ); + + // Call the function + return status; +} +/** + * Query Context Attributes + */ +SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( + PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer +) { + // Create function pointer instance + queryContextAttributes_fn pfn_queryContextAttributes = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + #ifdef _UNICODE + pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); + #else + pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_queryContextAttributes) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_queryContextAttributes)( + phContext, ulAttribute, pBuffer + ); +} + +/** + * InitSecurityInterface + */ +PSecurityFunctionTable _ssip_InitSecurityInterface() { + INIT_SECURITY_INTERFACE InitSecurityInterface; + PSecurityFunctionTable pSecurityInterface = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return NULL; + + #ifdef _UNICODE + // Get the address of the InitSecurityInterface function. + InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( + _sspi_secur32_dll, + TEXT("InitSecurityInterfaceW")); + #else + // Get the address of the InitSecurityInterface function. + InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( + _sspi_secur32_dll, + TEXT("InitSecurityInterfaceA")); + #endif + + if(!InitSecurityInterface) { + printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); + return NULL; + } + + // Use InitSecurityInterface to get the function table. + pSecurityInterface = (*InitSecurityInterface)(); + + if(!pSecurityInterface) { + printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); + return NULL; + } + + return pSecurityInterface; +} + +/** + * Load security.dll dynamically + */ +int load_library() { + DWORD err; + // Load the library + _sspi_security_dll = LoadLibrary("security.dll"); + + // Check if the library loaded + if(_sspi_security_dll == NULL) { + err = GetLastError(); + return err; + } + + // Load the library + _sspi_secur32_dll = LoadLibrary("secur32.dll"); + + // Check if the library loaded + if(_sspi_secur32_dll == NULL) { + err = GetLastError(); + return err; + } + + return 0; +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h new file mode 100644 index 0000000..a3008dc --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h @@ -0,0 +1,106 @@ +#ifndef SSPI_C_H +#define SSPI_C_H + +#define SECURITY_WIN32 1 + +#include +#include + +/** + * Encrypt A Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); + +typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); + +/** + * Acquire Credentials + */ +SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( + LPSTR pszPrincipal, // Name of principal + LPSTR pszPackage, // Name of package + unsigned long fCredentialUse, // Flags indicating use + void * pvLogonId, // Pointer to logon ID + void * pAuthData, // Package specific data + SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func + void * pvGetKeyArgument, // Value to pass to GetKey() + PCredHandle phCredential, // (out) Cred Handle + PTimeStamp ptsExpiry // (out) Lifetime (optional) +); + +typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( + LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, + void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, + PCredHandle phCredential, PTimeStamp ptsExpiry + ); + +/** + * Delete Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( + PCtxtHandle phContext // Context to delete +); + +typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); + +/** + * Decrypt Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( + PCtxtHandle phContext, + PSecBufferDesc pMessage, + unsigned long MessageSeqNo, + unsigned long pfQOP +); + +typedef DWORD (WINAPI *decryptMessage_fn)( + PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); + +/** + * Initialize Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( + PCredHandle phCredential, // Cred to base context + PCtxtHandle phContext, // Existing context (OPT) + LPSTR pszTargetName, // Name of target + unsigned long fContextReq, // Context Requirements + unsigned long Reserved1, // Reserved, MBZ + unsigned long TargetDataRep, // Data rep of target + PSecBufferDesc pInput, // Input Buffers + unsigned long Reserved2, // Reserved, MBZ + PCtxtHandle phNewContext, // (out) New Context handle + PSecBufferDesc pOutput, // (inout) Output Buffers + unsigned long * pfContextAttr, // (out) Context attrs + PTimeStamp ptsExpiry // (out) Life span (OPT) +); + +typedef DWORD (WINAPI *initializeSecurityContext_fn)( + PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, + unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); + +/** + * Query Context Attributes + */ +SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( + PCtxtHandle phContext, // Context to query + unsigned long ulAttribute, // Attribute to query + void * pBuffer // Buffer for attributes +); + +typedef DWORD (WINAPI *queryContextAttributes_fn)( + PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); + +/** + * InitSecurityInterface + */ +PSecurityFunctionTable _ssip_InitSecurityInterface(); + +typedef DWORD (WINAPI *initSecurityInterface_fn) (); + +/** + * Load security.dll dynamically + */ +int load_library(); + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc new file mode 100644 index 0000000..e7a472f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc @@ -0,0 +1,7 @@ +#include "worker.h" + +Worker::Worker() { +} + +Worker::~Worker() { +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h new file mode 100644 index 0000000..fb62b55 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h @@ -0,0 +1,38 @@ +#ifndef WORKER_H_ +#define WORKER_H_ + +#include +#include +#include +#include "nan.h" + +using namespace node; +using namespace v8; + +class Worker { + public: + Worker(); + virtual ~Worker(); + + // libuv's request struct. + uv_work_t request; + // Callback + NanCallback *callback; + // Parameters + void *parameters; + // Results + void *return_value; + // Did we raise an error + bool error; + // The error message + char *error_message; + // Error code if not message + int error_code; + // Any return code + int return_code; + // Method we are going to fire + void (*execute)(Worker *worker); + Handle (*mapper)(Worker *worker); +}; + +#endif // WORKER_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc new file mode 100644 index 0000000..f27ff8f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc @@ -0,0 +1,106 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_buffer.h" + +using namespace node; + +Persistent SecurityBuffer::constructor_template; + +SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() { + this->size = size; + this->data = calloc(size, sizeof(char)); + this->security_type = security_type; + // Set up the data in the sec_buffer + this->sec_buffer.BufferType = security_type; + this->sec_buffer.cbBuffer = (unsigned long)size; + this->sec_buffer.pvBuffer = this->data; +} + +SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() { + this->size = size; + this->data = data; + this->security_type = security_type; + // Set up the data in the sec_buffer + this->sec_buffer.BufferType = security_type; + this->sec_buffer.cbBuffer = (unsigned long)size; + this->sec_buffer.pvBuffer = this->data; +} + +SecurityBuffer::~SecurityBuffer() { + free(this->data); +} + +NAN_METHOD(SecurityBuffer::New) { + NanScope(); + SecurityBuffer *security_obj; + + if(args.Length() != 2) + return NanThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + if(!args[0]->IsInt32()) + return NanThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1])) + return NanThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + // Unpack buffer type + uint32_t buffer_type = args[0]->ToUint32()->Value(); + + // If we have an integer + if(args[1]->IsInt32()) { + security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value()); + } else { + // Get the length of the Buffer + size_t length = Buffer::Length(args[1]->ToObject()); + // Allocate space for the internal void data pointer + void *data = calloc(length, sizeof(char)); + // Write the data to out of V8 heap space + memcpy(data, Buffer::Data(args[1]->ToObject()), length); + // Create new SecurityBuffer + security_obj = new SecurityBuffer(buffer_type, length, data); + } + + // Wrap it + security_obj->Wrap(args.This()); + // Return the object + NanReturnValue(args.This()); +} + +NAN_METHOD(SecurityBuffer::ToBuffer) { + NanScope(); + // Unpack the Security Buffer object + SecurityBuffer *security_obj = ObjectWrap::Unwrap(args.This()); + // Create a Buffer + Local buffer = NanNewBufferHandle((char *)security_obj->data, (uint32_t)security_obj->size); + // Return the buffer + NanReturnValue(buffer); +} + +void SecurityBuffer::Initialize(Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("SecurityBuffer")); + + // Class methods + NODE_SET_PROTOTYPE_METHOD(t, "toBuffer", ToBuffer); + + // Set persistent + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("SecurityBuffer"), t->GetFunction()); +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h new file mode 100644 index 0000000..65b0fdd --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h @@ -0,0 +1,48 @@ +#ifndef SECURITY_BUFFER_H +#define SECURITY_BUFFER_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include "nan.h" + +using namespace v8; +using namespace node; + +class SecurityBuffer : public ObjectWrap { + public: + SecurityBuffer(uint32_t security_type, size_t size); + SecurityBuffer(uint32_t security_type, size_t size, void *data); + ~SecurityBuffer(); + + // Internal values + void *data; + size_t size; + uint32_t security_type; + SecBuffer sec_buffer; + + // Has instance check + static inline bool HasInstance(Handle val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return NanNew(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Handle target); + static NAN_METHOD(ToBuffer); + + // Constructor used for creating new Long objects from C++ + static Persistent constructor_template; + + private: + static NAN_METHOD(New); +}; + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js new file mode 100644 index 0000000..4996163 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js @@ -0,0 +1,12 @@ +var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; + +// Add some attributes +SecurityBufferNative.VERSION = 0; +SecurityBufferNative.EMPTY = 0; +SecurityBufferNative.DATA = 1; +SecurityBufferNative.TOKEN = 2; +SecurityBufferNative.PADDING = 9; +SecurityBufferNative.STREAM = 10; + +// Export the modified class +exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc new file mode 100644 index 0000000..e9ac963 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc @@ -0,0 +1,185 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include "security_buffer_descriptor.h" +#include "security_buffer.h" + +Persistent SecurityBufferDescriptor::constructor_template; + +SecurityBufferDescriptor::SecurityBufferDescriptor() : ObjectWrap() { +} + +SecurityBufferDescriptor::SecurityBufferDescriptor(const Persistent& arrayObjectPersistent) : ObjectWrap() { + SecurityBuffer *security_obj = NULL; + // Get the Local value + Local arrayObject = NanNew(arrayObjectPersistent); + + // Safe reference to array + this->arrayObject = arrayObject; + + // Unpack the array and ensure we have a valid descriptor + this->secBufferDesc.cBuffers = arrayObject->Length(); + this->secBufferDesc.ulVersion = SECBUFFER_VERSION; + + if(arrayObject->Length() == 1) { + // Unwrap the buffer + security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + // Assign the buffer + this->secBufferDesc.pBuffers = &security_obj->sec_buffer; + } else { + this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; + this->secBufferDesc.cBuffers = arrayObject->Length(); + + // Assign the buffers + for(uint32_t i = 0; i < arrayObject->Length(); i++) { + security_obj = ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); + this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; + this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; + this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; + } + } +} + +SecurityBufferDescriptor::~SecurityBufferDescriptor() { +} + +size_t SecurityBufferDescriptor::bufferSize() { + SecurityBuffer *security_obj = NULL; + + if(this->secBufferDesc.cBuffers == 1) { + security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + return security_obj->size; + } else { + int bytesToAllocate = 0; + + for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { + bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; + } + + // Return total size + return bytesToAllocate; + } +} + +char *SecurityBufferDescriptor::toBuffer() { + SecurityBuffer *security_obj = NULL; + char *data = NULL; + + if(this->secBufferDesc.cBuffers == 1) { + security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + data = (char *)malloc(security_obj->size * sizeof(char)); + memcpy(data, security_obj->data, security_obj->size); + } else { + size_t bytesToAllocate = this->bufferSize(); + char *data = (char *)calloc(bytesToAllocate, sizeof(char)); + int offset = 0; + + for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { + memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); + offset +=this->secBufferDesc.pBuffers[i].cbBuffer; + } + + // Return the data + return data; + } + + return data; +} + +NAN_METHOD(SecurityBufferDescriptor::New) { + NanScope(); + SecurityBufferDescriptor *security_obj; + Persistent arrayObject; + + if(args.Length() != 1) + return NanThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + + if(!args[0]->IsInt32() && !args[0]->IsArray()) + return NanThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + + if(args[0]->IsArray()) { + Handle array = Handle::Cast(args[0]); + // Iterate over all items and ensure we the right type + for(uint32_t i = 0; i < array->Length(); i++) { + if(!SecurityBuffer::HasInstance(array->Get(i))) { + return NanThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + } + } + } + + // We have a single integer + if(args[0]->IsInt32()) { + // Create new SecurityBuffer instance + Local argv[] = {NanNew(0x02), args[0]}; + Handle security_buffer = NanNew(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv); + // Create a new array + Local array = NanNew(1); + // Set the first value + array->Set(0, security_buffer); + + // Create persistent handle + Persistent persistenHandler; + NanAssignPersistent(persistenHandler, array); + + // Create descriptor + security_obj = new SecurityBufferDescriptor(persistenHandler); + } else { + // Create a persistent handler + Persistent persistenHandler; + NanAssignPersistent(persistenHandler, Handle::Cast(args[0])); + // Create a descriptor + security_obj = new SecurityBufferDescriptor(persistenHandler); + } + + // Wrap it + security_obj->Wrap(args.This()); + // Return the object + NanReturnValue(args.This()); +} + +NAN_METHOD(SecurityBufferDescriptor::ToBuffer) { + NanScope(); + + // Unpack the Security Buffer object + SecurityBufferDescriptor *security_obj = ObjectWrap::Unwrap(args.This()); + + // Get the buffer + char *buffer_data = security_obj->toBuffer(); + size_t buffer_size = security_obj->bufferSize(); + + // Create a Buffer + Local buffer = NanNewBufferHandle(buffer_data, (uint32_t)buffer_size); + + // Return the buffer + NanReturnValue(buffer); +} + +void SecurityBufferDescriptor::Initialize(Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("SecurityBufferDescriptor")); + + // Class methods + NODE_SET_PROTOTYPE_METHOD(t, "toBuffer", ToBuffer); + + // Set persistent + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("SecurityBufferDescriptor"), t->GetFunction()); +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h new file mode 100644 index 0000000..c4d98e4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h @@ -0,0 +1,46 @@ +#ifndef SECURITY_BUFFER_DESCRIPTOR_H +#define SECURITY_BUFFER_DESCRIPTOR_H + +#include +#include +#include + +#include +#include +#include +#include "nan.h" + +using namespace v8; +using namespace node; + +class SecurityBufferDescriptor : public ObjectWrap { + public: + Local arrayObject; + SecBufferDesc secBufferDesc; + + SecurityBufferDescriptor(); + SecurityBufferDescriptor(const Persistent& arrayObjectPersistent); + ~SecurityBufferDescriptor(); + + // Has instance check + static inline bool HasInstance(Handle val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return NanNew(constructor_template)->HasInstance(obj); + }; + + char *toBuffer(); + size_t bufferSize(); + + // Functions available from V8 + static void Initialize(Handle target); + static NAN_METHOD(ToBuffer); + + // Constructor used for creating new Long objects from C++ + static Persistent constructor_template; + + private: + static NAN_METHOD(New); +}; + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js new file mode 100644 index 0000000..9421392 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js @@ -0,0 +1,3 @@ +var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; +// Export the modified class +exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc new file mode 100644 index 0000000..cd47320 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc @@ -0,0 +1,869 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_context.h" +#include "security_buffer_descriptor.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +static LPSTR DisplaySECError(DWORD ErrCode); + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +static void After(uv_work_t* work_req) { + // Grab the scope of the call from Node + NanScope(); + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(NanNew(worker->error_message)); + Local obj = err->ToObject(); + obj->Set(NanNew("code"), NanNew(worker->error_code)); + Local args[2] = { err, NanNull() }; + // Execute the error + v8::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(args), args); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + } else { + // // Map the data + Handle result = worker->mapper(worker); + // Set up the callback with a null first + Handle args[2] = { NanNull(), result}; + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + v8::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(args), args); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + +Persistent SecurityContext::constructor_template; + +SecurityContext::SecurityContext() : ObjectWrap() { +} + +SecurityContext::~SecurityContext() { + if(this->hasContext) { + _sspi_DeleteSecurityContext(&this->m_Context); + } +} + +NAN_METHOD(SecurityContext::New) { + NanScope(); + + PSecurityFunctionTable pSecurityInterface = NULL; + DWORD dwNumOfPkgs; + SECURITY_STATUS status; + + // Create code object + SecurityContext *security_obj = new SecurityContext(); + // Get security table interface + pSecurityInterface = _ssip_InitSecurityInterface(); + // Call the security interface + status = (*pSecurityInterface->EnumerateSecurityPackages)( + &dwNumOfPkgs, + &security_obj->m_PkgInfo); + if(status != SEC_E_OK) { + printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); + return NanThrowError("Failed in retrieving security packages"); + } + + // Wrap it + security_obj->Wrap(args.This()); + // Return the object + NanReturnValue(args.This()); +} + +// +// Async InitializeContext +// +typedef struct SecurityContextStaticInitializeCall { + char *service_principal_name_str; + char *decoded_input_str; + int decoded_input_str_length; + SecurityContext *context; +} SecurityContextStaticInitializeCall; + +static void _initializeContext(Worker *worker) { + // Status of operation + SECURITY_STATUS status; + BYTE *out_bound_data_str = NULL; + SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; + + // Structures used for c calls + SecBufferDesc ibd, obd; + SecBuffer ib, ob; + + // + // Prepare data structure for returned data from SSPI + ob.BufferType = SECBUFFER_TOKEN; + ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; + // Allocate space for return data + out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; + ob.pvBuffer = out_bound_data_str; + // prepare buffer description + obd.cBuffers = 1; + obd.ulVersion = SECBUFFER_VERSION; + obd.pBuffers = &ob; + + // + // Prepare the data we are passing to the SSPI method + if(call->decoded_input_str_length > 0) { + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = call->decoded_input_str_length; + ib.pvBuffer = call->decoded_input_str; + // prepare buffer description + ibd.cBuffers = 1; + ibd.ulVersion = SECBUFFER_VERSION; + ibd.pBuffers = &ib; + } + + // Perform initialization step + status = _sspi_initializeSecurityContext( + &call->context->security_credentials->m_Credentials + , NULL + , const_cast(call->service_principal_name_str) + , 0x02 // MUTUAL + , 0 + , 0 // Network + , call->decoded_input_str_length > 0 ? &ibd : NULL + , 0 + , &call->context->m_Context + , &obd + , &call->context->CtxtAttr + , &call->context->Expiration + ); + + // If we have a ok or continue let's prepare the result + if(status == SEC_E_OK + || status == SEC_I_COMPLETE_NEEDED + || status == SEC_I_CONTINUE_NEEDED + || status == SEC_I_COMPLETE_AND_CONTINUE + ) { + call->context->hasContext = true; + call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); + + // Set the context + worker->return_code = status; + worker->return_value = call->context; + } else if(status == SEC_E_INSUFFICIENT_MEMORY) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action."; + } else if(status == SEC_E_INTERNAL_ERROR) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code."; + } else if(status == SEC_E_INVALID_HANDLE) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid."; + } else if(status == SEC_E_INVALID_TOKEN) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; + } else if(status == SEC_E_LOGON_DENIED) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_LOGON_DENIED The logon failed."; + } else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; + } else if(status == SEC_E_NO_CREDENTIALS) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package."; + } else if(status == SEC_E_TARGET_UNKNOWN) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized."; + } else if(status == SEC_E_UNSUPPORTED_FUNCTION) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter."; + } else if(status == SEC_E_WRONG_PRINCIPAL) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication."; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } + + // Clean up data + if(call->decoded_input_str != NULL) free(call->decoded_input_str); + if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); +} + +static Handle _map_initializeContext(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return NanObjectWrapHandle(context); +} + +NAN_METHOD(SecurityContext::InitializeContext) { + NanScope(); + char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; + int decoded_input_str_length = NULL; + // Store reference to security credentials + SecurityCredentials *security_credentials = NULL; + + // We need 3 parameters + if(args.Length() != 4) + return NanThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); + + // First parameter must be an instance of SecurityCredentials + if(!SecurityCredentials::HasInstance(args[0])) + return NanThrowError("First parameter for Initialize must be an instance of SecurityCredentials"); + + // Second parameter must be a string + if(!args[1]->IsString()) + return NanThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!args[2]->IsString()) + return NanThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a callback + if(!args[3]->IsFunction()) + return NanThrowError("Third parameter for Initialize must be a callback function"); + + // Let's unpack the values + Local service_principal_name = args[1]->ToString(); + service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); + service_principal_name->WriteUtf8(service_principal_name_str); + + // Unpack the user name + Local input = args[2]->ToString(); + + if(input->Utf8Length() > 0) { + input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); + input->WriteUtf8(input_str); + + // Now let's get the base64 decoded string + decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); + // Free original allocation + free(input_str); + } + + // Unpack the Security credentials + security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); + // Create Security context instance + Local security_context_value = NanNew(constructor_template)->GetFunction()->NewInstance(); + // Unwrap the security context + SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); + // Add a reference to the security_credentials + security_context->security_credentials = security_credentials; + + // Build the call function + SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); + call->context = security_context; + call->decoded_input_str = decoded_input_str; + call->decoded_input_str_length = decoded_input_str_length; + call->service_principal_name_str = service_principal_name_str; + + // Callback + Local callback = Local::Cast(args[3]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new NanCallback(callback); + worker->parameters = call; + worker->execute = _initializeContext; + worker->mapper = _map_initializeContext; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +NAN_GETTER(SecurityContext::PayloadGetter) { + NanScope(); + // Unpack the context object + SecurityContext *context = ObjectWrap::Unwrap(args.This()); + // Return the low bits + NanReturnValue(NanNew(context->payload)); +} + +NAN_GETTER(SecurityContext::HasContextGetter) { + NanScope(); + // Unpack the context object + SecurityContext *context = ObjectWrap::Unwrap(args.This()); + // Return the low bits + NanReturnValue(NanNew(context->hasContext)); +} + +// +// Async InitializeContextStep +// +typedef struct SecurityContextStepStaticInitializeCall { + char *service_principal_name_str; + char *decoded_input_str; + int decoded_input_str_length; + SecurityContext *context; +} SecurityContextStepStaticInitializeCall; + +static void _initializeContextStep(Worker *worker) { + // Outbound data array + BYTE *out_bound_data_str = NULL; + // Status of operation + SECURITY_STATUS status; + // Unpack data + SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; + SecurityContext *context = call->context; + // Structures used for c calls + SecBufferDesc ibd, obd; + SecBuffer ib, ob; + + // + // Prepare data structure for returned data from SSPI + ob.BufferType = SECBUFFER_TOKEN; + ob.cbBuffer = context->m_PkgInfo->cbMaxToken; + // Allocate space for return data + out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; + ob.pvBuffer = out_bound_data_str; + // prepare buffer description + obd.cBuffers = 1; + obd.ulVersion = SECBUFFER_VERSION; + obd.pBuffers = &ob; + + // + // Prepare the data we are passing to the SSPI method + if(call->decoded_input_str_length > 0) { + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = call->decoded_input_str_length; + ib.pvBuffer = call->decoded_input_str; + // prepare buffer description + ibd.cBuffers = 1; + ibd.ulVersion = SECBUFFER_VERSION; + ibd.pBuffers = &ib; + } + + // Perform initialization step + status = _sspi_initializeSecurityContext( + &context->security_credentials->m_Credentials + , context->hasContext == true ? &context->m_Context : NULL + , const_cast(call->service_principal_name_str) + , 0x02 // MUTUAL + , 0 + , 0 // Network + , call->decoded_input_str_length ? &ibd : NULL + , 0 + , &context->m_Context + , &obd + , &context->CtxtAttr + , &context->Expiration + ); + + // If we have a ok or continue let's prepare the result + if(status == SEC_E_OK + || status == SEC_I_COMPLETE_NEEDED + || status == SEC_I_CONTINUE_NEEDED + || status == SEC_I_COMPLETE_AND_CONTINUE + ) { + // Set the new payload + if(context->payload != NULL) free(context->payload); + context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } + + // Clean up data + if(call->decoded_input_str != NULL) free(call->decoded_input_str); + if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); +} + +static Handle _map_initializeContextStep(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return NanObjectWrapHandle(context); +} + +NAN_METHOD(SecurityContext::InitalizeStep) { + NanScope(); + + char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; + int decoded_input_str_length = NULL; + + // We need 3 parameters + if(args.Length() != 3) + return NanThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); + + // Second parameter must be a string + if(!args[0]->IsString()) + return NanThrowError("First parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!args[1]->IsString()) + return NanThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!args[2]->IsFunction()) + return NanThrowError("Third parameter for Initialize must be a callback function"); + + // Let's unpack the values + Local service_principal_name = args[0]->ToString(); + service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); + service_principal_name->WriteUtf8(service_principal_name_str); + + // Unpack the user name + Local input = args[1]->ToString(); + + if(input->Utf8Length() > 0) { + input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); + input->WriteUtf8(input_str); + // Now let's get the base64 decoded string + decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); + // Free input string + free(input_str); + } + + // Unwrap the security context + SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); + + // Create call structure + SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); + call->context = security_context; + call->decoded_input_str = decoded_input_str; + call->decoded_input_str_length = decoded_input_str_length; + call->service_principal_name_str = service_principal_name_str; + + // Callback + Local callback = Local::Cast(args[2]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new NanCallback(callback); + worker->parameters = call; + worker->execute = _initializeContextStep; + worker->mapper = _map_initializeContextStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +// Async EncryptMessage +// +typedef struct SecurityContextEncryptMessageCall { + SecurityContext *context; + SecurityBufferDescriptor *descriptor; + unsigned long flags; +} SecurityContextEncryptMessageCall; + +static void _encryptMessage(Worker *worker) { + SECURITY_STATUS status; + // Unpack call + SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; + // Unpack the security context + SecurityContext *context = call->context; + SecurityBufferDescriptor *descriptor = call->descriptor; + + // Let's execute encryption + status = _sspi_EncryptMessage( + &context->m_Context + , call->flags + , &descriptor->secBufferDesc + , 0 + ); + + // We've got ok + if(status == SEC_E_OK) { + int bytesToAllocate = (int)descriptor->bufferSize(); + // Free up existing payload + if(context->payload != NULL) free(context->payload); + // Save the payload + context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); + // Set result + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Handle _map_encryptMessage(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return NanObjectWrapHandle(context); +} + +NAN_METHOD(SecurityContext::EncryptMessage) { + NanScope(); + + if(args.Length() != 3) + return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!SecurityBufferDescriptor::HasInstance(args[0])) + return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!args[1]->IsUint32()) + return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!args[2]->IsFunction()) + return NanThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + + // Unpack the security context + SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); + + // Unpack the descriptor + SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); + + // Create call structure + SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); + call->context = security_context; + call->descriptor = descriptor; + call->flags = (unsigned long)args[1]->ToInteger()->Value(); + + // Callback + Local callback = Local::Cast(args[2]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new NanCallback(callback); + worker->parameters = call; + worker->execute = _encryptMessage; + worker->mapper = _map_encryptMessage; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +// Async DecryptMessage +// +typedef struct SecurityContextDecryptMessageCall { + SecurityContext *context; + SecurityBufferDescriptor *descriptor; +} SecurityContextDecryptMessageCall; + +static void _decryptMessage(Worker *worker) { + unsigned long quality = 0; + SECURITY_STATUS status; + + // Unpack parameters + SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; + SecurityContext *context = call->context; + SecurityBufferDescriptor *descriptor = call->descriptor; + + // Let's execute encryption + status = _sspi_DecryptMessage( + &context->m_Context + , &descriptor->secBufferDesc + , 0 + , (unsigned long)&quality + ); + + // We've got ok + if(status == SEC_E_OK) { + int bytesToAllocate = (int)descriptor->bufferSize(); + // Free up existing payload + if(context->payload != NULL) free(context->payload); + // Save the payload + context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); + // Set return values + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Handle _map_decryptMessage(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return NanObjectWrapHandle(context); +} + +NAN_METHOD(SecurityContext::DecryptMessage) { + NanScope(); + + if(args.Length() != 2) + return NanThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + if(!SecurityBufferDescriptor::HasInstance(args[0])) + return NanThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + if(!args[1]->IsFunction()) + return NanThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + + // Unpack the security context + SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); + // Unpack the descriptor + SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); + // Create call structure + SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); + call->context = security_context; + call->descriptor = descriptor; + + // Callback + Local callback = Local::Cast(args[1]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new NanCallback(callback); + worker->parameters = call; + worker->execute = _decryptMessage; + worker->mapper = _map_decryptMessage; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +// +// Async QueryContextAttributes +// +typedef struct SecurityContextQueryContextAttributesCall { + SecurityContext *context; + uint32_t attribute; +} SecurityContextQueryContextAttributesCall; + +static void _queryContextAttributes(Worker *worker) { + SECURITY_STATUS status; + + // Cast to data structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; + + // Allocate some space + SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); + // Let's grab the query context attribute + status = _sspi_QueryContextAttributes( + &call->context->m_Context, + call->attribute, + sizes + ); + + if(status == SEC_E_OK) { + worker->return_code = status; + worker->return_value = sizes; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Handle _map_queryContextAttributes(Worker *worker) { + // Cast to data structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; + // Unpack the attribute + uint32_t attribute = call->attribute; + + // Convert data + if(attribute == SECPKG_ATTR_SIZES) { + SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; + // Create object + Local value = NanNew(); + value->Set(NanNew("maxToken"), NanNew(uint32_t(sizes->cbMaxToken))); + value->Set(NanNew("maxSignature"), NanNew(uint32_t(sizes->cbMaxSignature))); + value->Set(NanNew("blockSize"), NanNew(uint32_t(sizes->cbBlockSize))); + value->Set(NanNew("securityTrailer"), NanNew(uint32_t(sizes->cbSecurityTrailer))); + return value; + } + + // Return the value + return NanNull(); +} + +NAN_METHOD(SecurityContext::QueryContextAttributes) { + NanScope(); + + if(args.Length() != 2) + return NanThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + if(!args[0]->IsInt32()) + return NanThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + if(!args[1]->IsFunction()) + return NanThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + + // Unpack the security context + SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); + + // Unpack the int value + uint32_t attribute = args[0]->ToInt32()->Value(); + + // Check that we have a supported attribute + if(attribute != SECPKG_ATTR_SIZES) + return NanThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); + + // Create call structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); + call->attribute = attribute; + call->context = security_context; + + // Callback + Local callback = Local::Cast(args[1]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new NanCallback(callback); + worker->parameters = call; + worker->execute = _queryContextAttributes; + worker->mapper = _map_queryContextAttributes; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +void SecurityContext::Initialize(Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("SecurityContext")); + + // Class methods + NODE_SET_METHOD(t, "initialize", InitializeContext); + + // Set up method for the instance + NODE_SET_PROTOTYPE_METHOD(t, "initialize", InitalizeStep); + NODE_SET_PROTOTYPE_METHOD(t, "decryptMessage", DecryptMessage); + NODE_SET_PROTOTYPE_METHOD(t, "queryContextAttributes", QueryContextAttributes); + NODE_SET_PROTOTYPE_METHOD(t, "encryptMessage", EncryptMessage); + + // Get prototype + Local proto = t->PrototypeTemplate(); + + // Getter for the response + proto->SetAccessor(NanNew("payload"), SecurityContext::PayloadGetter); + proto->SetAccessor(NanNew("hasContext"), SecurityContext::HasContextGetter); + + // Set persistent + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("SecurityContext"), t->GetFunction()); +} + +static LPSTR DisplaySECError(DWORD ErrCode) { + LPSTR pszName = NULL; // WinError.h + + switch(ErrCode) { + case SEC_E_BUFFER_TOO_SMALL: + pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; + break; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; + break; + case SEC_E_INCOMPLETE_MESSAGE: + pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; + break; + + case SEC_E_INVALID_HANDLE: + pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_INVALID_TOKEN: + pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; + break; + + case SEC_E_MESSAGE_ALTERED: + pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_OUT_OF_SEQUENCE: + pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; + break; + + case SEC_E_QOP_NOT_SUPPORTED: + pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; + break; + + case SEC_I_CONTEXT_EXPIRED: + pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; + break; + + case SEC_I_RENEGOTIATE: + pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; + break; + + case SEC_E_ENCRYPT_FAILURE: + pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; + break; + + case SEC_E_DECRYPT_FAILURE: + pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; + break; + case -1: + pszName = "Failed to load security.dll library"; + break; + } + + return pszName; +} + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h new file mode 100644 index 0000000..fee2391 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h @@ -0,0 +1,74 @@ +#ifndef SECURITY_CONTEXT_H +#define SECURITY_CONTEXT_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include +#include "security_credentials.h" +#include "../worker.h" +#include "nan.h" + +extern "C" { + #include "../kerberos_sspi.h" + #include "../base64.h" +} + +using namespace v8; +using namespace node; + +class SecurityContext : public ObjectWrap { + public: + SecurityContext(); + ~SecurityContext(); + + // Security info package + PSecPkgInfo m_PkgInfo; + // Do we have a context + bool hasContext; + // Reference to security credentials + SecurityCredentials *security_credentials; + // Security context + CtxtHandle m_Context; + // Attributes + DWORD CtxtAttr; + // Expiry time for ticket + TimeStamp Expiration; + // Payload + char *payload; + + // Has instance check + static inline bool HasInstance(Handle val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return NanNew(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Handle target); + static NAN_METHOD(InitializeContext); + static NAN_METHOD(InitalizeStep); + static NAN_METHOD(DecryptMessage); + static NAN_METHOD(QueryContextAttributes); + static NAN_METHOD(EncryptMessage); + + // Payload getter + static NAN_GETTER(PayloadGetter); + // hasContext getter + static NAN_GETTER(HasContextGetter); + + // Constructor used for creating new Long objects from C++ + static Persistent constructor_template; + + private: + // Create a new instance + static NAN_METHOD(New); +}; + +#endif diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js new file mode 100644 index 0000000..ef04e92 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js @@ -0,0 +1,3 @@ +var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; +// Export the modified class +exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc new file mode 100644 index 0000000..fc2a3d8 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc @@ -0,0 +1,351 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_credentials.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +static LPSTR DisplaySECError(DWORD ErrCode); + +Persistent SecurityCredentials::constructor_template; + +SecurityCredentials::SecurityCredentials() : ObjectWrap() { +} + +SecurityCredentials::~SecurityCredentials() { +} + +NAN_METHOD(SecurityCredentials::New) { + NanScope(); + // Create security credentials instance + SecurityCredentials *security_credentials = new SecurityCredentials(); + // Wrap it + security_credentials->Wrap(args.This()); + // Return the object + NanReturnValue(args.This()); +} + +// Call structs +typedef struct SecurityCredentialCall { + char *package_str; + char *username_str; + char *password_str; + char *domain_str; + SecurityCredentials *credentials; +} SecurityCredentialCall; + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authSSPIAquire(Worker *worker) { + // Status of operation + SECURITY_STATUS status; + + // Unpack data + SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; + + // // Unwrap the credentials + // SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; + SecurityCredentials *security_credentials = new SecurityCredentials(); + + // If we have domain string + if(call->domain_str != NULL) { + security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); + security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); + } else { + security_credentials->m_Identity.Domain = NULL; + security_credentials->m_Identity.DomainLength = 0; + } + + // Set up the user + security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); + security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); + + // If we have a password string + if(call->password_str != NULL) { + // Set up the password + security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); + security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); + } + + #ifdef _UNICODE + security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; + #else + security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; + #endif + + // Attempt to acquire credentials + status = _sspi_AcquireCredentialsHandle( + NULL, + call->package_str, + SECPKG_CRED_OUTBOUND, + NULL, + call->password_str != NULL ? &security_credentials->m_Identity : NULL, + NULL, NULL, + &security_credentials->m_Credentials, + &security_credentials->Expiration + ); + + // We have an error + if(status != SEC_E_OK) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } else { + worker->return_code = status; + worker->return_value = security_credentials; + } + + // Free up parameter structure + if(call->package_str != NULL) free(call->package_str); + if(call->domain_str != NULL) free(call->domain_str); + if(call->password_str != NULL) free(call->password_str); + if(call->username_str != NULL) free(call->username_str); + free(call); +} + +static Handle _map_authSSPIAquire(Worker *worker) { + return NanNull(); +} + +NAN_METHOD(SecurityCredentials::Aquire) { + NanScope(); + + char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; + // Unpack the variables + if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4 && args.Length() != 5) + return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(!args[0]->IsString()) + return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(!args[1]->IsString()) + return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(args.Length() == 3 && (!args[2]->IsString() && !args[2]->IsFunction())) + return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull()) && !args[3]->IsFunction()) + return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(args.Length() == 5 && !args[4]->IsFunction()) + return NanThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + Local callbackHandle; + + // Figure out which parameter is the callback + if(args.Length() == 5) { + callbackHandle = Local::Cast(args[4]); + } else if(args.Length() == 4) { + callbackHandle = Local::Cast(args[3]); + } else if(args.Length() == 3) { + callbackHandle = Local::Cast(args[2]); + } + + // Unpack the package + Local package = args[0]->ToString(); + package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); + package->WriteUtf8(package_str); + + // Unpack the user name + Local username = args[1]->ToString(); + username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); + username->WriteUtf8(username_str); + + // If we have a password + if(args.Length() == 3 || args.Length() == 4 || args.Length() == 5) { + Local password = args[2]->ToString(); + password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); + password->WriteUtf8(password_str); + } + + // If we have a domain + if((args.Length() == 4 || args.Length() == 5) && args[3]->IsString()) { + Local domain = args[3]->ToString(); + domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); + domain->WriteUtf8(domain_str); + } + + // Allocate call structure + SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); + call->domain_str = domain_str; + call->package_str = package_str; + call->password_str = password_str; + call->username_str = username_str; + + // Unpack the callback + NanCallback *callback = new NanCallback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authSSPIAquire; + worker->mapper = _map_authSSPIAquire; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); + + // Return no value as it's callback based + NanReturnValue(NanUndefined()); +} + +void SecurityCredentials::Initialize(Handle target) { + // Grab the scope of the call from Node + NanScope(); + + // Define a new function template + Local t = NanNew(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(NanNew("SecurityCredentials")); + + // Class methods + NODE_SET_METHOD(t, "aquire", Aquire); + + // Set persistent + NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(NanNew("SecurityCredentials"), t->GetFunction()); + + // Attempt to load the security.dll library + load_library(); +} + +static LPSTR DisplaySECError(DWORD ErrCode) { + LPSTR pszName = NULL; // WinError.h + + switch(ErrCode) { + case SEC_E_BUFFER_TOO_SMALL: + pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; + break; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; + break; + case SEC_E_INCOMPLETE_MESSAGE: + pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; + break; + + case SEC_E_INVALID_HANDLE: + pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_INVALID_TOKEN: + pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; + break; + + case SEC_E_MESSAGE_ALTERED: + pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_OUT_OF_SEQUENCE: + pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; + break; + + case SEC_E_QOP_NOT_SUPPORTED: + pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; + break; + + case SEC_I_CONTEXT_EXPIRED: + pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; + break; + + case SEC_I_RENEGOTIATE: + pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; + break; + + case SEC_E_ENCRYPT_FAILURE: + pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; + break; + + case SEC_E_DECRYPT_FAILURE: + pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; + break; + case -1: + pszName = "Failed to load security.dll library"; + break; + + } + + return pszName; +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +void SecurityCredentials::Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +void SecurityCredentials::After(uv_work_t* work_req) { + // Grab the scope of the call from Node + NanScope(); + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(NanNew(worker->error_message)); + Local obj = err->ToObject(); + obj->Set(NanNew("code"), NanNew(worker->error_code)); + Local args[2] = { err, NanNull() }; + // Execute the error + v8::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(args), args); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + } else { + SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value; + // Create a new instance + Local result = NanNew(constructor_template)->GetFunction()->NewInstance(); + // Unwrap the credentials + SecurityCredentials *security_credentials = ObjectWrap::Unwrap(result); + // Set the values + security_credentials->m_Identity = return_value->m_Identity; + security_credentials->m_Credentials = return_value->m_Credentials; + security_credentials->Expiration = return_value->Expiration; + // Set up the callback with a null first + Handle args[2] = { NanNull(), result}; + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + v8::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(args), args); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h new file mode 100644 index 0000000..b026070 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h @@ -0,0 +1,68 @@ +#ifndef SECURITY_CREDENTIALS_H +#define SECURITY_CREDENTIALS_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include +#include "nan.h" +#include "../worker.h" +#include + +extern "C" { + #include "../kerberos_sspi.h" +} + +// SEC_WINNT_AUTH_IDENTITY makes it unusually hard +// to compile for both Unicode and ansi, so I use this macro: +#ifdef _UNICODE +#define USTR(str) (str) +#else +#define USTR(str) ((unsigned char*)(str)) +#endif + +using namespace v8; +using namespace node; + +class SecurityCredentials : public ObjectWrap { + public: + SecurityCredentials(); + ~SecurityCredentials(); + + // Pointer to context object + SEC_WINNT_AUTH_IDENTITY m_Identity; + // credentials + CredHandle m_Credentials; + // Expiry time for ticket + TimeStamp Expiration; + + // Has instance check + static inline bool HasInstance(Handle val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return NanNew(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Handle target); + static NAN_METHOD(Aquire); + + // Constructor used for creating new Long objects from C++ + static Persistent constructor_template; + + private: + // Create a new instance + static NAN_METHOD(New); + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js new file mode 100644 index 0000000..4215c92 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js @@ -0,0 +1,22 @@ +var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; + +// Add simple kebros helper +SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { + if(typeof password == 'function') { + callback = password; + password = null; + } else if(typeof domain == 'function') { + callback = domain; + domain = null; + } + + // We are going to use the async version + if(typeof callback == 'function') { + return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); + } else { + return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); + } +} + +// Export the modified class +exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc new file mode 100644 index 0000000..e7a472f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc @@ -0,0 +1,7 @@ +#include "worker.h" + +Worker::Worker() { +} + +Worker::~Worker() { +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h new file mode 100644 index 0000000..cbc7f6a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h @@ -0,0 +1,38 @@ +#ifndef WORKER_H_ +#define WORKER_H_ + +#include +#include +#include +#include + +using namespace node; +using namespace v8; + +class Worker { + public: + Worker(); + virtual ~Worker(); + + // libuv's request struct. + uv_work_t request; + // Callback + NanCallback *callback; + // Parameters + void *parameters; + // Results + void *return_value; + // Did we raise an error + bool error; + // The error message + char *error_message; + // Error code if not message + int error_code; + // Any return code + int return_code; + // Method we are going to fire + void (*execute)(Worker *worker); + Handle (*mapper)(Worker *worker); +}; + +#endif // WORKER_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc new file mode 100644 index 0000000..47971da --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc @@ -0,0 +1,30 @@ +## DNT config file +## see https://github.com/rvagg/dnt + +NODE_VERSIONS="\ + master \ + v0.11.13 \ + v0.10.30 \ + v0.10.29 \ + v0.10.28 \ + v0.10.26 \ + v0.10.25 \ + v0.10.24 \ + v0.10.23 \ + v0.10.22 \ + v0.10.21 \ + v0.10.20 \ + v0.10.19 \ + v0.8.28 \ + v0.8.27 \ + v0.8.26 \ + v0.8.24 \ +" +OUTPUT_PREFIX="nan-" +TEST_CMD=" \ + cd /dnt/ && \ + npm install && \ + node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ + node_modules/.bin/tap --gc test/js/*-test.js \ +" + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md new file mode 100644 index 0000000..8e8f052 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md @@ -0,0 +1,294 @@ +# NAN ChangeLog + +**Version 1.8.4: current Node 12: 0.12.2, Node 10: 0.10.38, io.js: 1.8.1** + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 + +### 1.7.0 Feb 28 2015 + + - Feature: Made NanCallback::Call accept optional target 8d54da7 + - Feature: Support atom-shell 0.21 0b7f1bb + +### 1.6.2 Feb 6 2015 + + - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 + +### 1.6.1 Jan 23 2015 + + - Build: version bump + +### 1.5.3 Jan 23 2015 + + - Build: repackage + +### 1.6.0 Jan 23 2015 + + - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af + - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 + - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 + +### 1.5.2 Jan 23 2015 + + - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 + - Bugfix: Readded missing String constructors 18d828f + - Bugfix: Add overload handling NanNew(..) 5ef813b + - Bugfix: Fix uv_work_cb versioning 997e4ae + - Bugfix: Add function factory and test 4eca89c + - Bugfix: Add object template factory and test cdcb951 + - Correctness: Lifted an io.js related typedef c9490be + - Correctness: Make explicit downcasts of String lengths 00074e6 + - Windows: Limit the scope of disabled warning C4530 83d7deb + +### 1.5.1 Jan 15 2015 + + - Build: version bump + +### 1.4.3 Jan 15 2015 + + - Build: version bump + +### 1.4.2 Jan 15 2015 + + - Feature: Support io.js 0dbc5e8 + +### 1.5.0 Jan 14 2015 + + - Feature: Support io.js b003843 + - Correctness: Improved NanNew internals 9cd4f6a + - Feature: Implement progress to NanAsyncWorker 8d6a160 + +### 1.4.1 Nov 8 2014 + + - Bugfix: Handle DEBUG definition correctly + - Bugfix: Accept int as Boolean + +### 1.4.0 Nov 1 2014 + + - Feature: Added NAN_GC_CALLBACK 6a5c245 + - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 + - Correctness: Added constness to references in NanHasInstance 02c61cd + - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 + - Windoze: Shut Visual Studio up when compiling 8d558c1 + - License: Switch to plain MIT from custom hacked MIT license 11de983 + - Build: Added test target to Makefile e232e46 + - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 + - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 + - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 + +### 1.3.0 Aug 2 2014 + + - Added NanNew(std::string) + - Added NanNew(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) + - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) + - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + +### 1.2.0 Jun 5 2014 + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +### 1.1.2 May 28 2014 + + - Release to fix more stuff-ups in 1.1.1 + +### 1.1.1 May 28 2014 + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +### 1.1.0 May 25 2014 + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +### 1.0.0 May 4 2014 + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +### 0.8.0 Jan 9 2014 + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +### 0.7.1 Jan 9 2014 + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +### 0.7.0 Dec 17 2013 + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +### 0.6.0 Nov 21 2013 + + - Introduce NanNewLocal(v8::Handle value) for use in place of + v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 + +### 0.5.2 Nov 16 2013 + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +### 0.5.1 Nov 12 2013 + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +### 0.5.0 Nov 11 2013 + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +### 0.4.4 Nov 2 2013 + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +### 0.4.3 Nov 2 2013 + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +### 0.4.2 Nov 2 2013 + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +### 0.4.1 Sep 16 2013 + + - Added explicit `#include ` as it was removed from node.h for v0.11.8 + +### 0.4.0 Sep 2 2013 + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +### 0.3.2 Aug 30 2013 + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +### 0.3.1 Aug 20 2013 + + - fix "not all control paths return a value" compile warning on some platforms + +### 0.3.0 Aug 19 2013 + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local) to NanThrowError(Handle) + - Fixed leak in NanAsyncWorker when errmsg is used + +### 0.2.2 Aug 5 2013 + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +### 0.2.1 Aug 5 2013 + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +### 0.2.0 Aug 5 2013 + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle, v8::Handle) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +### 0.1.0 Jul 21 2013 + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent&, Handle)` + - Added `Local NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local[])` + - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md new file mode 100644 index 0000000..95c2eb5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2015 NAN contributors +----------------------------------- + +*NAN contributors listed at * + +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/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md new file mode 100644 index 0000000..26f6947 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md @@ -0,0 +1,1402 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** + +***Current version: 1.8.4*** + +*(See [CHANGELOG.md](https://github.com/iojs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) + +[![Build Status](https://api.travis-ci.org/iojs/nan.svg?branch=master)](http://travis-ci.org/iojs/nan) +[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Porting](#porting)** + * **[Governance & Contributing](#governance)** + + +## News & Updates + +### Apr-2015: 1.8.0 release + +* Support V8 4.2 +* Removed support for creating `Signature`s with arguments +* Backported thread local storage routines for libuv + +### Feb-2015: 1.7.0 release + +* Made `NanCallback::Call` accept optional target +* Support atom-shell 0.21 + +Node 0.12.0 is out and supported by NAN. So is atom-shell 0.21. `NanCallback::Call` now accepts an optional `target` argument like `NanMakeCallback`. + +### Jan-2015: 1.6.0 release + +* Deprecated `NanNewContextHandle` in favor of `NanNew` +* Added `NanSetCounterFunction`, `NanSetCreateHistogramFunction`, `NanSetAddHistogramSampleFunction` +* Added `NanIdleNotification`, `NanLowMemoryNotification`, `NanContextDisposedNotification` +* Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` + +### Jan-2015: 1.5.0 release + +* Support [io.js](https://github.com/iojs/io.js) thanks to [Ben Noordhuis](bnoordhuis) +* Rewritten NanNew internals thanks to [David Siegel](agnat) +* NanAsyncWorker now supports progress reporting thanks to [Brett Lawson](brett19) + +### Aug-2014: 1.3.0 release + +* `NanCString()` and `NanRawString()` have been deprecated in favour of new NanAsciiString, NanUtf8String and NanUcs2String. These classes manage the underlying memory for you in a safer way than just handing off an allocated array. You should now `*NanAsciiString(handle)` to access the raw `char` data, you can also allocate on the heap if you need to keep a reference. +* Two more NanMakeCallback overloads have been added to for parity with Node core. +* You can now `NanNew(std::string)` (use `NanNew(std::string&)` to pass by reference) +* NanSetTemplate, NanSetPrototypeTemplate and NanSetInstanceTemplate have been added. + +### May-2014: 1.1.0 release + +* We've deprecated `NanSymbol()`, you should just use `NanNew()` now. +* `NanNull()`, `NanUndefined()`, `NanTrue()`, `NanFalse()` all return `Local`s now. +* `nan_isolate` is gone, it was intended to be internal-only but if you were using it then you should switch to `v8::Isolate::GetCurrent()`. +* `NanNew()` has received some additional overload-love so you should be able to give it many kinds of values without specifying the ``. +* Lots of small fixes and additions to expand the V8 API coverage, *use the source, Luke*. + + +### May-2014: Major changes for V8 3.25 / Node 0.11.13 + +Node 0.11.11 and 0.11.12 were both broken releases for native add-ons, you simply can't properly compile against either of them for different reasons. But we now have a 0.11.13 release that jumps a couple of versions of V8 ahead and includes some more, major (traumatic) API changes. + +Because we are now nearing Node 0.12 and estimate that the version of V8 we are using in Node 0.11.13 will be close to the API we get for 0.12, we have taken the opportunity to not only *fix* NAN for 0.11.13 but make some major changes to improve the NAN API. + +We have **removed support for Node 0.11 versions prior to 0.11.13**. As usual, our tests are run against (and pass) the last 5 versions of Node 0.8 and Node 0.10. We also include Node 0.11.13 obviously. + +The major change is something that [Benjamin Byholm](kkoopa) has put many hours in to. We now have a fantastic new `NanNew(args)` interface for creating new `Local`s, this replaces `NanNewLocal()` and much more. If you look in [./nan.h](nan.h) you'll see a large number of overloaded versions of this method. In general you should be able to `NanNew(arguments)` for any type you want to make a `Local` from. This includes `Persistent` types, so we now have a `Local NanNew(const Persistent arg)` to replace `NanPersistentToLocal()`. + +We also now have `NanUndefined()`, `NanNull()`, `NanTrue()` and `NanFalse()`. Mainly because of the new requirement for an `Isolate` argument for each of the native V8 versions of this. + +V8 has now introduced an `EscapableHandleScope` from which you `scope.Escape(Local value)` to *return* a value from a one scope to another. This replaces the standard `HandleScope` and `scope.Close(Local value)`, although `HandleScope` still exists for when you don't need to return a handle to the caller. For NAN we are exposing it as `NanEscapableScope()` and `NanEscapeScope()`, while `NanScope()` is still how you create a new scope that doesn't need to return handles. For older versions of Node/V8, it'll still map to the older `HandleScope` functionality. + +`NanFromV8String()` was deprecated and has now been removed. You should use `NanCString()` or `NanRawString()` instead. + +Because `node::MakeCallback()` now takes an `Isolate`, and because it doesn't exist in older versions of Node, we've introduced `NanMakeCallback()`. You should *always* use this when calling a JavaScript function from C++. + +There's lots more, check out the Changelog in nan.h or look through [#86](https://github.com/iojs/nan/pull/86) for all the gory details. + +### Dec-2013: NanCString and NanRawString + +Two new functions have been introduced to replace the functionality that's been provided by `NanFromV8String` until now. NanCString has sensible defaults so it's super easy to fetch a null-terminated c-style string out of a `v8::String`. `NanFromV8String` is still around and has defaults that allow you to pass a single handle to fetch a `char*` while `NanRawString` requires a little more attention to arguments. + +### Nov-2013: Node 0.11.9+ breaking V8 change + +The version of V8 that's shipping with Node 0.11.9+ has changed the signature for new `Local`s to: `v8::Local::New(isolate, value)`, i.e. introducing the `isolate` argument and therefore breaking all new `Local` declarations for previous versions. NAN 0.6+ now includes a `NanNewLocal(value)` that can be used in place to work around this incompatibility and maintain compatibility with 0.8->0.11.9+ (minus a few early 0.11 releases). + +For example, if you wanted to return a `null` on a callback you will have to change the argument from `v8::Local::New(v8::Null())` to `NanNewLocal(v8::Null())`. + +### Nov-2013: Change to binding.gyp `"include_dirs"` for NAN + +Inclusion of NAN in a project's binding.gyp is now greatly simplified. You can now just use `" +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: + +``` python +"include_dirs" : [ + "` when compiling your addon. + + +## Example + +See **[LevelDOWN](https://github.com/rvagg/node-leveldown/pull/48)** for a full example of **NAN** in use. + +For a simpler example, see the **[async pi estimation example](https://github.com/iojs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + +Compare to the current 0.10 version of this example, found in the [node-addon-examples](https://github.com/iojs/node-addon-examples/tree/master/9_async_work) repository and also a 0.11 version of the same found [here](https://github.com/kkoopa/node-addon-examples/tree/5c01f58fc993377a567812597e54a83af69686d7/9_async_work). + +Note that there is no embedded version sniffing going on here and also the async work is made much simpler, see below for details on the `NanAsyncWorker` class. + +```c++ +// addon.cc +#include +#include +// ... + +using v8::FunctionTemplate; +using v8::Handle; +using v8::Object; +using v8::String; + +void InitAll(Handle exports) { + exports->Set(NanNew("calculateSync"), + NanNew(CalculateSync)->GetFunction()); + + exports->Set(NanNew("calculateAsync"), + NanNew(CalculateAsync)->GetFunction()); +} + +NODE_MODULE(addon, InitAll) +``` + +```c++ +// sync.h +#include +#include + +NAN_METHOD(CalculateSync); +``` + +```c++ +// sync.cc +#include +#include +#include "./sync.h" +// ... + +using v8::Number; + +// Simple synchronous access to the `Estimate()` function +NAN_METHOD(CalculateSync) { + NanScope(); + + // expect a number as the first argument + int points = args[0]->Uint32Value(); + double est = Estimate(points); + + NanReturnValue(NanNew(est)); +} +``` + +```c++ +// async.h +#include +#include + +NAN_METHOD(CalculateAsync); +``` + +```c++ +// async.cc +#include +#include +#include "./async.h" + +// ... + +using v8::Function; +using v8::Local; +using v8::Null; +using v8::Number; +using v8::Value; + +class PiWorker : public NanAsyncWorker { + public: + PiWorker(NanCallback *callback, int points) + : NanAsyncWorker(callback), points(points) {} + ~PiWorker() {} + + // Executed inside the worker-thread. + // It is not safe to access V8, or V8 data structures + // here, so everything we need for input and output + // should go on `this`. + void Execute () { + estimate = Estimate(points); + } + + // Executed when the async work is complete + // this function will be run inside the main event loop + // so it is safe to use V8 again + void HandleOKCallback () { + NanScope(); + + Local argv[] = { + NanNull() + , NanNew(estimate) + }; + + callback->Call(2, argv); + }; + + private: + int points; + double estimate; +}; + +// Asynchronous access to the `Estimate()` function +NAN_METHOD(CalculateAsync) { + NanScope(); + + int points = args[0]->Uint32Value(); + NanCallback *callback = new NanCallback(args[1].As()); + + NanAsyncQueueWorker(new PiWorker(callback, points)); + NanReturnUndefined(); +} +``` + + +## API + + * NAN_METHOD + * NAN_GETTER + * NAN_SETTER + * NAN_PROPERTY_GETTER + * NAN_PROPERTY_SETTER + * NAN_PROPERTY_ENUMERATOR + * NAN_PROPERTY_DELETER + * NAN_PROPERTY_QUERY + * NAN_INDEX_GETTER + * NAN_INDEX_SETTER + * NAN_INDEX_ENUMERATOR + * NAN_INDEX_DELETER + * NAN_INDEX_QUERY + * NAN_GC_CALLBACK + * NAN_WEAK_CALLBACK + * NAN_DEPRECATED + * NAN_INLINE + * NanNew + * NanUndefined + * NanNull + * NanTrue + * NanFalse + * NanReturnValue + * NanReturnUndefined + * NanReturnNull + * NanReturnEmptyString + * NanReturnThis + * NanReturnHolder + * NanScope + * NanEscapableScope + * NanEscapeScope + * NanLocker + * NanUnlocker + * NanGetInternalFieldPointer + * NanSetInternalFieldPointer + * NanObjectWrapHandle + * NanSymbol + * NanGetPointerSafe + * NanSetPointerSafe + * NanRawString + * NanCString + * NanAsciiString + * NanUtf8String + * NanUcs2String + * NanBooleanOptionValue + * NanUInt32OptionValue + * NanError, NanTypeError, NanRangeError + * NanThrowError, NanThrowTypeError, NanThrowRangeError, NanThrowError(Handle), NanThrowError(Handle, int) + * NanNewBufferHandle(char *, size_t, FreeCallback, void *), NanNewBufferHandle(char *, uint32_t), NanNewBufferHandle(uint32_t) + * NanBufferUse(char *, uint32_t) + * NanNewContextHandle + * NanGetCurrentContext + * NanHasInstance + * NanDisposePersistent + * NanAssignPersistent + * NanMakeWeakPersistent + * NanSetTemplate + * NanSetPrototypeTemplate + * NanSetInstanceTemplate + * NanMakeCallback + * NanEncode + * NanDecodeBytes + * NanDecodeWrite + * NanCompileScript + * NanRunScript + * NanAdjustExternalMemory + * NanAddGCEpilogueCallback + * NanAddGCPrologueCallback + * NanRemoveGCEpilogueCallback + * NanRemoveGCPrologueCallback + * NanGetHeapStatistics + * NanSetCounterFunction + * NanSetCreateHistogramFunction + * NanSetAddHistogramSampleFunction + * NanIdleNotification + * NanLowMemoryNotification + * NanContextDisposedNotification + * NanCallback + * NanAsyncWorker + * NanAsyncQueueWorker + + +### NAN_METHOD(methodname) + +Use `NAN_METHOD` to define your V8 accessible methods: + +```c++ +// .h: +class Foo : public node::ObjectWrap { + ... + + static NAN_METHOD(Bar); + static NAN_METHOD(Baz); +} + + +// .cc: +NAN_METHOD(Foo::Bar) { + ... +} + +NAN_METHOD(Foo::Baz) { + ... +} +``` + +The reason for this macro is because of the method signature change in 0.11: + +```c++ +// 0.10 and below: +Handle name(const Arguments& args) + +// 0.11 and above +void name(const FunctionCallbackInfo& args) +``` + +The introduction of `FunctionCallbackInfo` brings additional complications: + + +### NAN_GETTER(methodname) + +Use `NAN_GETTER` to declare your V8 accessible getters. You get a `Local` `property` and an appropriately typed `args` object that can act like the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_GETTER`. + + +### NAN_SETTER(methodname) + +Use `NAN_SETTER` to declare your V8 accessible setters. Same as `NAN_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_GETTER(cbname) +Use `NAN_PROPERTY_GETTER` to declare your V8 accessible property getters. You get a `Local` `property` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_GETTER`. + + +### NAN_PROPERTY_SETTER(cbname) +Use `NAN_PROPERTY_SETTER` to declare your V8 accessible property setters. Same as `NAN_PROPERTY_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_ENUMERATOR(cbname) +Use `NAN_PROPERTY_ENUMERATOR` to declare your V8 accessible property enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_PROPERTY_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_ENUMERATOR`. + + +### NAN_PROPERTY_DELETER(cbname) +Use `NAN_PROPERTY_DELETER` to declare your V8 accessible property deleters. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_DELETER`. + + +### NAN_PROPERTY_QUERY(cbname) +Use `NAN_PROPERTY_QUERY` to declare your V8 accessible property queries. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_QUERY`. + + +### NAN_INDEX_GETTER(cbname) +Use `NAN_INDEX_GETTER` to declare your V8 accessible index getters. You get a `uint32_t` `index` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_GETTER`. + + +### NAN_INDEX_SETTER(cbname) +Use `NAN_INDEX_SETTER` to declare your V8 accessible index setters. Same as `NAN_INDEX_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_INDEX_ENUMERATOR(cbname) +Use `NAN_INDEX_ENUMERATOR` to declare your V8 accessible index enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_INDEX_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_ENUMERATOR`. + + +### NAN_INDEX_DELETER(cbname) +Use `NAN_INDEX_DELETER` to declare your V8 accessible index deleters. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_DELETER`. + + +### NAN_INDEX_QUERY(cbname) +Use `NAN_INDEX_QUERY` to declare your V8 accessible index queries. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_QUERY`. + + +### NAN_GC_CALLBACK(cbname) +Use `NAN_GC_CALLBACK` to declare your callbacks for `NanAddGCEpilogueCallback` and `NanAddGCPrologueCallback`. You get arguments `GCType type` and `GCCallbackFlags flags`. + +```c++ +static Persistent callback; + +NAN_GC_CALLBACK(gcPrologueCallback) { + Local argv[] = {NanNew("prologue")}; + NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv); +} + +NAN_METHOD(Hook) { + NanScope(); + NanAssignPersistent(callback, args[0].As()); + NanAddGCPrologueCallback(gcPrologueCallback); + NanReturnValue(args.Holder()); +} +``` + + +### NAN_WEAK_CALLBACK(cbname) + +Use `NAN_WEAK_CALLBACK` to define your V8 WeakReference callbacks. There is an argument object `const _NanWeakCallbackData &data` allowing access to the weak object and the supplied parameter through its `GetValue` and `GetParameter` methods. You can even access the weak callback info object through the `GetCallbackInfo()`method, but you probably should not. `Revive()` keeps the weak object alive until the next GC round. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + int *parameter = data.GetParameter(); + NanMakeCallback(NanGetCurrentContext()->Global(), data.GetValue(), 0, NULL); + if ((*parameter)++ == 0) { + data.Revive(); + } else { + delete parameter; + } +} +``` + + +### NAN_DEPRECATED +Declares a function as deprecated. + +```c++ +static NAN_DEPRECATED NAN_METHOD(foo) { + ... +} +``` + + +### NAN_INLINE +Inlines a function. + +```c++ +NAN_INLINE int foo(int bar) { + ... +} +``` + + +### Local<T> NanNew<T>( ... ) + +Use `NanNew` to construct almost all v8 objects (bound `Script`s are constructed with `NanCompileScript(Handle)`) and make new local handles. + +```c++ +Local s = NanNew("value"); + +... + +Persistent o; + +... + +Local lo = NanNew(o); + +``` + + +### Local<Primitive> NanUndefined() + +Use instead of `Undefined()` + + +### Local<Primitive> NanNull() + +Use instead of `Null()` + + +### Local<Boolean> NanTrue() + +Use instead of `True()` + + +### Local<Boolean> NanFalse() + +Use instead of `False()` + + +### NanReturnValue(Handle<Value>) + +Use `NanReturnValue` when you want to return a value from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Bar) { + ... + + NanReturnValue(NanNew("FooBar!")); +} +``` + +No `return` statement required. + +For convenience, `NanReturnValue` also accepts common primitives directly by implicitly performing an overloaded `NanNew(T)`. + +```c++ +NanReturnValue("FooBar!"); +NanReturnValue(true); +NanReturnValue(12); +NanReturnValue(3.14); +``` + + +### NanReturnUndefined() + +Use `NanReturnUndefined` when you don't want to return anything from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnUndefined(); +} +``` + + +### NanReturnNull() + +Use `NanReturnNull` when you want to return `Null` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnNull(); +} +``` + + +### NanReturnEmptyString() + +Use `NanReturnEmptyString` when you want to return an empty `String` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnEmptyString(); +} +``` + + +### NanReturnThis() + +Use `NanReturnThis` when you want to return `This` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnThis(); +} +``` + + +### NanReturnHolder() + +Use `NanReturnHolder` when you want to return `Holder` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnHolder(); +} +``` + + +### NanScope() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanScope()` necessary, use it in place of `HandleScope scope` when you do not wish to return handles (`Handle` or `Local`) to the surrounding scope (or in functions directly exposed to V8, as they do not return values in the normal sense): + +```c++ +NAN_METHOD(Foo::Bar) { + NanScope(); + + NanReturnValue(NanNew("FooBar!")); +} +``` + +This method is not directly exposed to V8, nor does it return a handle, so it uses an unescapable scope: + +```c++ +bool Foo::Bar() { + NanScope(); + + Local val = NanFalse(); + ... + return val->Value(); +} +``` + + +### NanEscapableScope() + +The separation of handle scopes into escapable and inescapable scopes makes `NanEscapableScope()` necessary, use it in place of `HandleScope scope` when you later wish to return a handle (`Handle` or `Local`) from the scope, this is for internal functions not directly exposed to V8: + +```c++ +Handle Foo::Bar() { + NanEscapableScope(); + + return NanEscapeScope(NanNew("FooBar!")); +} +``` + + +### Local<T> NanEscapeScope(Handle<T> value); +Use together with `NanEscapableScope` to escape the scope. Corresponds to `HandleScope::Close` or `EscapableHandleScope::Escape`. + + +### NanLocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanLocker()` necessary, use it in place of `Locker locker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### NanUnlocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanUnlocker()` necessary, use it in place of `Unlocker unlocker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### void * NanGetInternalFieldPointer(Handle<Object>, int) + +Gets a pointer to the internal field with at `index` from a V8 `Object` handle. + +```c++ +Local obj; +... +NanGetInternalFieldPointer(obj, 0); +``` + +### void NanSetInternalFieldPointer(Handle<Object>, int, void *) + +Sets the value of the internal field at `index` on a V8 `Object` handle. + +```c++ +static Persistent dataWrapperCtor; +... +Local wrapper = NanNew(dataWrapperCtor)->NewInstance(); +NanSetInternalFieldPointer(wrapper, 0, this); +``` + + +### Local<Object> NanObjectWrapHandle(const node::ObjectWrap &obj) + +When you want to fetch the V8 object handle from a native object you've wrapped with Node's `ObjectWrap`, you should use `NanObjectWrapHandle`: + +```c++ +NanObjectWrapHandle(iterator)->Get(NanNew("end")) +``` + + +### ~~Local<String> NanSymbol(const char *)~~ + +Deprecated. Use `NanNew` instead. +~~Use to create string symbol objects (i.e. `v8::String::NewSymbol(x)`), for getting and setting object properties, or names of objects.~~ + +```c++ +bool foo = false; +if (obj->Has(NanNew("foo"))) + foo = optionsObj->Get(NanNew("foo"))->BooleanValue() +``` + + +### Type NanGetPointerSafe(Type *[, Type]) + +A helper for getting values from optional pointers. If the pointer is `NULL`, the function returns the optional default value, which defaults to `0`. Otherwise, the function returns the value the pointer points to. + +```c++ +char *plugh(uint32_t *optional) { + char res[] = "xyzzy"; + uint32_t param = NanGetPointerSafe(optional, 0x1337); + switch (param) { + ... + } + NanSetPointerSafe(optional, 0xDEADBEEF); +} +``` + + +### bool NanSetPointerSafe(Type *, Type) + +A helper for setting optional argument pointers. If the pointer is `NULL`, the function simply returns `false`. Otherwise, the value is assigned to the variable the pointer points to. + +```c++ +const char *plugh(size_t *outputsize) { + char res[] = "xyzzy"; + if !(NanSetPointerSafe(outputsize, strlen(res) + 1)) { + ... + } + + ... +} +``` + + +### ~~void* NanRawString(Handle<Value>, enum Nan::Encoding, size_t *, void *, size_t, int)~~ + +Deprecated. Use something else. + +~~When you want to convert a V8 `String` to a `char*` buffer, use `NanRawString`. You have to supply an encoding as well as a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows setting `String::WriteOptions`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:~~ + +```c++ +size_t count; +void* decoded = NanRawString(args[1], Nan::BASE64, &count, NULL, 0, String::HINT_MANY_WRITES_EXPECTED); +... +delete[] reinterpret_cast(decoded); +``` + + +### ~~char* NanCString(Handle<Value>, size_t *[, char *, size_t, int])~~ + +Deprecated. Use `String::Utf8Value` or `NanUtf8String` instead. + +~~When you want to convert a V8 `String` to a null-terminated C `char*` use `NanCString`. The resulting `char*` will be UTF-8-encoded, and you need to supply a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows optionally setting `String::WriteOptions`, which default to `v8::String::NO_OPTIONS`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:~~ + +```c++ +size_t count; +char* name = NanCString(args[0], &count); +... +delete[] name; +``` + + +### NanAsciiString + +Contrary to the name, this is not actually an ASCII string, it is a one-byte string with no particular encoding. Do not use unless you actually need this incorrect legacy behavior. Consider fixing your broken code instead. If you actually have a proper ASCII-string, use UTF-8, which is a proper superset of ASCII. +Convert a `String` to zero-terminated, sort-of Ascii-encoded `char *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanAsciiString(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanAsciiString baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanAsciiString *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanAsciiString(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + +### NanUtf8String + +Equivalent to `String::Utf8Value`, it only exists for the sake of completeness. +Convert a `String` to zero-terminated, Utf8-encoded `char *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUtf8String(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanUtf8String baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanUtf8String *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanUtf8String(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + + +### NanUcs2String + +Equivalent to `String::Value`, it only exists for the sake of completeness. +Convert a `String` to zero-terminated, Ucs2-encoded `uint16_t *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUcs2String(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanUcs2String baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanUcs2String *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanUcs2String(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + +### bool NanBooleanOptionValue(Handle<Value>, Handle<String>[, bool]) + +When you have an "options" object that you need to fetch properties from, boolean options can be fetched with this pair. They check first if the object exists (`IsEmpty`), then if the object has the given property (`Has`) then they get and convert/coerce the property to a `bool`. + +The optional last parameter is the *default* value, which is `false` if left off: + +```c++ +// `foo` is false unless the user supplies a truthy value for it +bool foo = NanBooleanOptionValue(optionsObj, NanNew("foo")); +// `bar` is true unless the user supplies a falsy value for it +bool bar = NanBooleanOptionValueDefTrue(optionsObj, NanNew("bar"), true); +``` + + +### uint32_t NanUInt32OptionValue(Handle<Value>, Handle<String>, uint32_t) + +Similar to `NanBooleanOptionValue`, use `NanUInt32OptionValue` to fetch an integer option from your options object. Can be any kind of JavaScript `Number` and it will be coerced to an unsigned 32-bit integer. + +Requires all 3 arguments as a default is not optional: + +```c++ +uint32_t count = NanUInt32OptionValue(optionsObj, NanNew("count"), 1024); +``` + + +### NanError(message), NanTypeError(message), NanRangeError(message) + +For making `Error`, `TypeError` and `RangeError` objects. + +```c++ +Local res = NanError("you must supply a callback argument"); +``` + + +### NanThrowError(message), NanThrowTypeError(message), NanThrowRangeError(message), NanThrowError(Local<Value>), NanThrowError(Local<Value>, int) + +For throwing `Error`, `TypeError` and `RangeError` objects. + +```c++ +NanThrowError("you must supply a callback argument"); +``` + +Can also handle any custom object you may want to throw. If used with the error code argument, it will add the supplied error code to the error object as a property called `code`. + + +### Local<Object> NanNewBufferHandle(char *, uint32_t), Local<Object> NanNewBufferHandle(uint32_t) + +The `Buffer` API has changed a little in Node 0.11, this helper provides consistent access to `Buffer` creation: + +```c++ +NanNewBufferHandle((char*)value.data(), value.size()); +``` + +Can also be used to initialize a `Buffer` with just a `size` argument. + +Can also be supplied with a `NanFreeCallback` and a hint for the garbage collector. + + +### Local<Object> NanBufferUse(char*, uint32_t) + +`Buffer::New(char*, uint32_t)` prior to 0.11 would make a copy of the data. +While it was possible to get around this, it required a shim by passing a +callback. So the new API `Buffer::Use(char*, uint32_t)` was introduced to remove +needing to use this shim. + +`NanBufferUse` uses the `char*` passed as the backing data, and will free the +memory automatically when the weak callback is called. Keep this in mind, as +careless use can lead to "double free or corruption" and other cryptic failures. + + +### bool NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>) + +Can be used to check the type of an object to determine it is of a particular class you have already defined and have a `Persistent` handle for. + + +### ~~Local<Context> NanNewContextHandle([ExtensionConfiguration*, Handle<ObjectTemplate>, Handle<Value>])~~ + +Deprecated. Use `NanNew` instead. + +~~Creates a new `Local` handle.~~ + +```c++ +Local ftmpl = NanNew(); +Local otmpl = ftmpl->InstanceTemplate(); +Local ctx = NanNewContextHandle(NULL, otmpl); +``` + + +### Local<Context> NanGetCurrentContext() + +Gets the current context. + +```c++ +Local ctx = NanGetCurrentContext(); +``` + + +### void NanDisposePersistent(Persistent<T> &) + +Use `NanDisposePersistent` to dispose a `Persistent` handle. + +```c++ +NanDisposePersistent(persistentHandle); +``` + + +### NanAssignPersistent(handle, object) + +Use `NanAssignPersistent` to assign a non-`Persistent` handle to a `Persistent` one. You can no longer just declare a `Persistent` handle and assign directly to it later, you have to `Reset` it in Node 0.11, so this makes it easier. + +In general it is now better to place anything you want to protect from V8's garbage collector as properties of a generic `Object` and then assign that to a `Persistent`. This works in older versions of Node also if you use `NanAssignPersistent`: + +```c++ +Persistent persistentHandle; + +... + +Local obj = NanNew(); +obj->Set(NanNew("key"), keyHandle); // where keyHandle might be a Local +NanAssignPersistent(persistentHandle, obj) +``` + + +### _NanWeakCallbackInfo<T, P>* NanMakeWeakPersistent(Handle<T>, P*, _NanWeakCallbackInfo<T, P>::Callback) + +Creates a weak persistent handle with the supplied parameter and `NAN_WEAK_CALLBACK`. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + +... + +} + +Local func; + +... + +int *parameter = new int(0); +NanMakeWeakPersistent(func, parameter, &weakCallback); +``` + + +### NanSetTemplate(templ, name, value [, attributes]) + +Use to add properties on object and function templates. + + +### NanSetPrototypeTemplate(templ, name, value [, attributes]) + +Use to add prototype properties on function templates. + + +### NanSetInstanceTemplate(templ, name, value [, attributes]) + +Use to add instance properties on function templates. + + +### NanMakeCallback(target, func, argc, argv) + +Use instead of `node::MakeCallback` to call javascript functions. This (or `NanCallback`) is the only proper way of calling functions. You must _*never, ever*_ directly use `Function::Call`, it will lead to run-time failures. + + +### NanEncode(const void*, size_t[, enum Nan::Encoding]) + +Replaces `node::Encode`. + + +### NanDecodeBytes(v8::Handle<v8::Value>[, enum Nan::Encoding]) + +Replaces `node::DecodeBytes`. + + +### NanDecodeWrite(char *, size_t, v8::Handle<v8::Value>[, enum Nan::Encoding]) + +Replaces `node::DecodeWrite`. + + +### NanCompileScript(Handle s [, const ScriptOrigin& origin]) + +Use to create new scripts bound to the current context. + + +### NanRunScript(script) + +Use to run both bound and unbound scripts. + + +### NanAdjustExternalMemory(int change_in_bytes) + +Simply does `AdjustAmountOfExternalAllocatedMemory`, note that the argument and returned value have type `int`. + + +### NanAddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCEpilogueCallback` + + +### NanAddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCPrologueCallback` + + +### NanRemoveGCEpilogueCallback(GCEpilogueCallback callback) + +Simply does `RemoveGCEpilogueCallback` + + +### NanRemoveGCPrologueCallback(GCPrologueCallback callback) + +Simply does `RemoveGCPrologueCallback` + + +### NanGetHeapStatistics(HeapStatistics *heap_statistics) + +Simply does `GetHeapStatistics` + + +### NanSetCounterFunction(CounterLookupCallback cb) + +Simply does `SetCounterFunction` + + +### NanSetCreateHistogramFunction(CreateHistogramCallback cb) + +Simply does `SetCreateHistogramFunction` + + +### NanSetAddHistogramSampleFunction(AddHistogramSampleCallback cb) + +Simply does `SetAddHistogramSampleFunction` + + +### NanIdleNotification(int idle_time_in_ms) + +Simply does `IdleNotification` + + +### NanLowMemoryNotification() + +Simply does `LowMemoryNotification` + + +### NanContextDisposedNotification() + +Simply does `ContextDisposedNotification` + + +### NanCallback + +Because of the difficulties imposed by the changes to `Persistent` handles in V8 in Node 0.11, creating `Persistent` versions of your `Handle` is annoyingly tricky. `NanCallback` makes it easier by taking your handle, making it persistent until the `NanCallback` is deleted and even providing a handy `Call()` method to fetch and execute the callback `Function`. + +```c++ +Local callbackHandle = args[0].As(); +NanCallback *callback = new NanCallback(callbackHandle); +// pass `callback` around and it's safe from GC until you: +delete callback; +``` + +You can execute the callback like so: + +```c++ +// no arguments: +callback->Call(0, NULL); + +// an error argument: +Handle argv[] = { + NanError(NanNew("fail!")) +}; +callback->Call(1, argv); + +// a success argument: +Handle argv[] = { + NanNull(), + NanNew("w00t!") +}; +callback->Call(2, argv); +``` + +`NanCallback` also has a `Local GetFunction()` method that you can use +to fetch a local handle to the underlying callback function, as well as a +`void SetFunction(Handle)` for setting the callback on the +`NanCallback`. You can check if a `NanCallback` is empty with the `bool IsEmpty()` method. Additionally a generic constructor is available for using +`NanCallback` without performing heap allocations. + + +### NanAsyncWorker + +`NanAsyncWorker` is an abstract class that you can subclass to have much of the annoying async queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the async work is in progress. + +See a rough outline of the implementation: + +```c++ +class NanAsyncWorker { +public: + NanAsyncWorker (NanCallback *callback); + + // Clean up persistent handles and delete the *callback + virtual ~NanAsyncWorker (); + + // Check the `ErrorMessage()` and call HandleOKCallback() + // or HandleErrorCallback depending on whether it has been set or not + virtual void WorkComplete (); + + // You must implement this to do some async work. If there is an + // error then use `SetErrorMessage()` to set an error message and the callback will + // be passed that string in an Error object + virtual void Execute (); + + // Save a V8 object in a Persistent handle to protect it from GC + void SaveToPersistent(const char *key, Local &obj); + + // Fetch a stored V8 object (don't call from within `Execute()`) + Local GetFromPersistent(const char *key); + + // Get the error message (or NULL) + const char *ErrorMessage(); + + // Set an error message + void SetErrorMessage(const char *msg); + +protected: + // Default implementation calls the callback function with no arguments. + // Override this to return meaningful data + virtual void HandleOKCallback (); + + // Default implementation calls the callback function with an Error object + // wrapping the `errmsg` string + virtual void HandleErrorCallback (); +}; +``` + + +### NanAsyncQueueWorker(NanAsyncWorker *) + +`NanAsyncQueueWorker` will run a `NanAsyncWorker` asynchronously via libuv. Both the *execute* and *after_work* steps are taken care of for you—most of the logic for this is embedded in `NanAsyncWorker`. + + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + +## Porting + +Follows is a guide to porting your C++ node to NAN. + + + + + + + + + + + + + + + + + +
AspectWithout NANWith NAN
Function declaration
class MyClass : public ObjectWrap {
+    ....
+    static Handle ToString(const Arguments& args);
+    ....
+}
class MyClass : public ObjectWrap {
+    ....
+    static NAN_METHOD(ToString);
+    ....
+}
Function definition
Handle
+MyClass::ToString(const Arguments& args)
+{
+	HandleScope scope;
+	....
+}
+NAN_METHOD(MyClass::ToString)
+{
+  NanScope();
+  ....
+}
Return a value
return scope.Close(result);
NanReturnValue(result);
Return undefined
return Undefined();
NanReturnUndefined();
Throw an error
return ThrowException(
+  Exception::Error(
+    String::New("Error text...")));
return NanThrowError("Error text...");
New v8 string literal
String::NewSymbol("my text")
NanNew("my text")
+ +## Contributors + + + +## Governance & Contributing + +NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +### Developer's Certificate of Origin 1.0 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or +* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or +* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. + + +### WG Members / Collaborators + + + + + + + + + +
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
David SiegelGitHub/agnat-
+ +## Licence & copyright + +Copyright (c) 2015 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml new file mode 100644 index 0000000..3429453 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml @@ -0,0 +1,38 @@ +# http://www.appveyor.com/docs/appveyor-yml + +# Test against these versions of Io.js and Node.js. +environment: + matrix: + # node.js + - nodejs_version: "0.8" + - nodejs_version: "0.10" + - nodejs_version: "0.12" + # io.js + - nodejs_version: "1" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node 0.STABLE.latest + - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} + - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} + - IF NOT %nodejs_version% == 1 npm -g install npm + - IF NOT %nodejs_version% == 1 set PATH=%APPDATA%\npm;%PATH% + # Typical npm stuff. + - npm install + - IF %nodejs_version% == 0.8 node node_modules\node-gyp\bin\node-gyp.js rebuild --directory test + - IF NOT %nodejs_version% == 0.8 npm run rebuild-tests + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - IF NOT %nodejs_version% == 1 npm test + - IF %nodejs_version% == 1 iojs node_modules\tap\bin\tap.js --gc test\js\*-test.js + +# Don't actually build. +build: off + +# Set build version format here instead of in the admin panel. +version: "{build}" diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js new file mode 100644 index 0000000..4f1dfb4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js @@ -0,0 +1 @@ +console.log(require('path').relative('.', __dirname)); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h new file mode 100644 index 0000000..fb025a9 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h @@ -0,0 +1,2322 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors: + * - Rod Vagg + * - Benjamin Byholm + * - Trevor Norris + * - Nathan Rajlich + * - Brett Lawson + * - Ben Noordhuis + * - David Siegel + * + * MIT License + * + * Version 1.8.4: current Node 12: 0.12.2, Node 10: 0.10.38, io.js: 1.8.1 + * + * See https://github.com/rvagg/nan for the latest update to this file + **********************************************************************************/ + +#ifndef NAN_H_ +#define NAN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# pragma warning( pop ) +#else +# include +#endif + +#if defined(__GNUC__) && !(defined(DEBUG) && DEBUG) +# define NAN_INLINE inline __attribute__((always_inline)) +#elif defined(_MSC_VER) && !(defined(DEBUG) && DEBUG) +# define NAN_INLINE __forceinline +#else +# define NAN_INLINE inline +#endif + +#if defined(__GNUC__) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __declspec(deprecated) +#else +# define NAN_DEPRECATED +#endif + +#define NODE_0_10_MODULE_VERSION 11 +#define NODE_0_12_MODULE_VERSION 12 +#define ATOM_0_21_MODULE_VERSION 41 +#define IOJS_1_0_MODULE_VERSION 42 +#define IOJS_1_1_MODULE_VERSION 43 + +#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) +typedef v8::InvocationCallback NanFunctionCallback; +typedef v8::Script NanUnboundScript; +typedef v8::Script NanBoundScript; +#else +typedef v8::FunctionCallback NanFunctionCallback; +typedef v8::UnboundScript NanUnboundScript; +typedef v8::Script NanBoundScript; +#endif + +#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) +typedef v8::String::ExternalAsciiStringResource + NanExternalOneByteStringResource; +#else +typedef v8::String::ExternalOneByteStringResource + NanExternalOneByteStringResource; +#endif + +#include "nan_new.h" // NOLINT(build/include) + +// uv helpers +#ifdef UV_VERSION_MAJOR +#ifndef UV_VERSION_PATCH +#define UV_VERSION_PATCH 0 +#endif +#define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ + (UV_VERSION_MINOR << 8) | \ + (UV_VERSION_PATCH)) +#else +#define NAUV_UVVERSION 0x000b00 +#endif + + +#if NAUV_UVVERSION < 0x000b17 +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async, int) +#else +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async) +#endif + +#if NAUV_UVVERSION >= 0x000b0b + +typedef uv_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t *key) { + return uv_key_create(key); +} + +inline void nauv_key_delete(nauv_key_t *key) { + uv_key_delete(key); +} + +inline void* nauv_key_get(nauv_key_t *key) { + return uv_key_get(key); +} + +inline void nauv_key_set(nauv_key_t *key, void *value) { + uv_key_set(key, value); +} + +#else + +/* Implement thread local storage for older versions of libuv. + * This is essentially a backport of libuv commit 5d2434bf + * written by Ben Noordhuis, adjusted for names and inline. + */ + +#ifndef WIN32 + +#include + +typedef pthread_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + return -pthread_key_create(key, NULL); +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (pthread_key_delete(*key)) + abort(); +} + +inline void* nauv_key_get(nauv_key_t* key) { + return pthread_getspecific(*key); +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (pthread_setspecific(*key, value)) + abort(); +} + +#else + +#include + +typedef struct { + DWORD tls_index; +} nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + key->tls_index = TlsAlloc(); + if (key->tls_index == TLS_OUT_OF_INDEXES) + return UV_ENOMEM; + return 0; +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (TlsFree(key->tls_index) == FALSE) + abort(); + key->tls_index = TLS_OUT_OF_INDEXES; +} + +inline void* nauv_key_get(nauv_key_t* key) { + void* value = TlsGetValue(key->tls_index); + if (value == NULL) + if (GetLastError() != ERROR_SUCCESS) + abort(); + return value; +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (TlsSetValue(key->tls_index, value) == FALSE) + abort(); +} + +#endif +#endif + +// some generic helpers + +template NAN_INLINE bool NanSetPointerSafe( + T *var + , T val +) { + if (var) { + *var = val; + return true; + } else { + return false; + } +} + +template NAN_INLINE T NanGetPointerSafe( + T *var + , T fallback = reinterpret_cast(0) +) { + if (var) { + return *var; + } else { + return fallback; + } +} + +NAN_INLINE bool NanBooleanOptionValue( + v8::Local optionsObj + , v8::Handle opt, bool def +) { + if (def) { + return optionsObj.IsEmpty() + || !optionsObj->Has(opt) + || optionsObj->Get(opt)->BooleanValue(); + } else { + return !optionsObj.IsEmpty() + && optionsObj->Has(opt) + && optionsObj->Get(opt)->BooleanValue(); + } +} + +NAN_INLINE bool NanBooleanOptionValue( + v8::Local optionsObj + , v8::Handle opt +) { + return NanBooleanOptionValue(optionsObj, opt, false); +} + +NAN_INLINE uint32_t NanUInt32OptionValue( + v8::Local optionsObj + , v8::Handle opt + , uint32_t def +) { + return !optionsObj.IsEmpty() + && optionsObj->Has(opt) + && optionsObj->Get(opt)->IsNumber() + ? optionsObj->Get(opt)->Uint32Value() + : def; +} + +template +v8::Local NanNew(v8::Handle); + +template +NAN_INLINE v8::Local _NanEnsureLocal(v8::Handle val) { + return NanNew(val); +} + +template +NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { + return val; +} + +template +NAN_INLINE v8::Local _NanEnsureLocal(T val) { + return NanNew(val); +} + +/* io.js 1.0 */ +#if NODE_MODULE_VERSION >= IOJS_1_0_MODULE_VERSION \ + || NODE_VERSION_AT_LEAST(0, 11, 15) + NAN_INLINE + void NanSetCounterFunction(v8::CounterLookupCallback cb) { + v8::Isolate::GetCurrent()->SetCounterFunction(cb); + } + + NAN_INLINE + void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); + } + + NAN_INLINE + void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); + } + + NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { + return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); + } + + NAN_INLINE void NanLowMemoryNotification() { + v8::Isolate::GetCurrent()->LowMemoryNotification(); + } + + NAN_INLINE void NanContextDisposedNotification() { + v8::Isolate::GetCurrent()->ContextDisposedNotification(); + } +#else + NAN_INLINE + void NanSetCounterFunction(v8::CounterLookupCallback cb) { + v8::V8::SetCounterFunction(cb); + } + + NAN_INLINE + void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::V8::SetCreateHistogramFunction(cb); + } + + NAN_INLINE + void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::V8::SetAddHistogramSampleFunction(cb); + } + + NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { + return v8::V8::IdleNotification(idle_time_in_ms); + } + + NAN_INLINE void NanLowMemoryNotification() { + v8::V8::LowMemoryNotification(); + } + + NAN_INLINE void NanContextDisposedNotification() { + v8::V8::ContextDisposedNotification(); + } +#endif + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) +// Node 0.11+ (0.11.12 and below won't compile with these) + +# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& +# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args +# define _NAN_METHOD_RETURN_TYPE void + +# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& +# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args +# define _NAN_GETTER_RETURN_TYPE void + +# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& +# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args +# define _NAN_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args +# define _NAN_PROPERTY_GETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args +# define _NAN_PROPERTY_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args +# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void + +# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_DELETER_ARGS \ + _NAN_PROPERTY_DELETER_ARGS_TYPE args +# define _NAN_PROPERTY_DELETER_RETURN_TYPE void + +# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args +# define _NAN_PROPERTY_QUERY_RETURN_TYPE void + +# define _NAN_INDEX_GETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args +# define _NAN_INDEX_GETTER_RETURN_TYPE void + +# define _NAN_INDEX_SETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args +# define _NAN_INDEX_SETTER_RETURN_TYPE void + +# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args +# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void + +# define _NAN_INDEX_DELETER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args +# define _NAN_INDEX_DELETER_RETURN_TYPE void + +# define _NAN_INDEX_QUERY_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args +# define _NAN_INDEX_QUERY_RETURN_TYPE void + +# define NanScope() v8::HandleScope scope(v8::Isolate::GetCurrent()) +# define NanEscapableScope() \ + v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()) + +# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val)) +# define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) +# define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) +# define NanReturnValue(value) return args.GetReturnValue().Set(_NanEnsureLocal(value)) +# define NanReturnUndefined() return +# define NanReturnHolder() NanReturnValue(args.Holder()) +# define NanReturnThis() NanReturnValue(args.This()) +# define NanReturnNull() return args.GetReturnValue().SetNull() +# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() + + NAN_INLINE v8::Local NanObjectWrapHandle(const node::ObjectWrap *obj) { + return const_cast(obj)->handle(); + } + + NAN_INLINE v8::Local NanUndefined() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanNull() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanTrue() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanFalse() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE int NanAdjustExternalMemory(int bc) { + return static_cast( + v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , const char *name + , v8::Handle value) { + templ->Set(v8::Isolate::GetCurrent(), name, value); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + NAN_INLINE v8::Local NanGetCurrentContext() { + return v8::Isolate::GetCurrent()->GetCurrentContext(); + } + + NAN_INLINE void* NanGetInternalFieldPointer( + v8::Handle object + , int index) { + return object->GetAlignedPointerFromInternalField(index); + } + + NAN_INLINE void NanSetInternalFieldPointer( + v8::Handle object + , int index + , void* value) { + object->SetAlignedPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) + + NAN_INLINE void NanAddGCEpilogueCallback( + v8::Isolate::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); + } + + NAN_INLINE void NanRemoveGCEpilogueCallback( + v8::Isolate::GCEpilogueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); + } + + NAN_INLINE void NanAddGCPrologueCallback( + v8::Isolate::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); + } + + NAN_INLINE void NanRemoveGCPrologueCallback( + v8::Isolate::GCPrologueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); + } + + NAN_INLINE void NanGetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( + const char* data, int length = -1) { + return NanNew(data, length); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , v8::Handle obj) { + handle.Reset(v8::Isolate::GetCurrent(), obj); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , const v8::Persistent& obj) { + handle.Reset(v8::Isolate::GetCurrent(), obj); + } + + template + class _NanWeakCallbackData; + + template + struct _NanWeakCallbackInfo { + typedef void (*Callback)(const _NanWeakCallbackData& data); + NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) + : parameter(param), callback(cb) { + NanAssignPersistent(persistent, handle); + } + + NAN_INLINE ~_NanWeakCallbackInfo() { + persistent.Reset(); + } + + P* const parameter; + Callback const callback; + v8::Persistent persistent; + }; + + template + class _NanWeakCallbackData { + public: + NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) + : info_(info) { } + + NAN_INLINE v8::Local GetValue() const { + return NanNew(info_->persistent); + } + + NAN_INLINE P* GetParameter() const { return info_->parameter; } + + NAN_INLINE bool IsNearDeath() const { + return info_->persistent.IsNearDeath(); + } + + NAN_INLINE void Revive() const; + + NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { + return info_; + } + + NAN_DEPRECATED NAN_INLINE void Dispose() const { + } + + private: + _NanWeakCallbackInfo* info_; + }; + + template + static void _NanWeakCallbackDispatcher( + const v8::WeakCallbackData > &data) { + _NanWeakCallbackInfo *info = data.GetParameter(); + _NanWeakCallbackData wcbd(info); + info->callback(wcbd); + if (wcbd.IsNearDeath()) { + delete wcbd.GetCallbackInfo(); + } + } + + template + NAN_INLINE void _NanWeakCallbackData::Revive() const { + info_->persistent.SetWeak(info_, &_NanWeakCallbackDispatcher); + } + +template +NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( + v8::Handle handle + , P* parameter + , typename _NanWeakCallbackInfo::Callback callback) { + _NanWeakCallbackInfo *cbinfo = + new _NanWeakCallbackInfo(handle, parameter, callback); + cbinfo->persistent.SetWeak(cbinfo, &_NanWeakCallbackDispatcher); + return cbinfo; +} + +# define NAN_WEAK_CALLBACK(name) \ + template \ + static void name(const _NanWeakCallbackData &data) + +# define _NAN_ERROR(fun, errmsg) fun(NanNew(errmsg)) + +# define _NAN_THROW_ERROR(fun, errmsg) \ + do { \ + NanScope(); \ + v8::Isolate::GetCurrent()->ThrowException(_NAN_ERROR(fun, errmsg)); \ + } while (0); + + NAN_INLINE v8::Local NanError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE void NanThrowError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE void NanThrowError(v8::Handle error) { + NanScope(); + v8::Isolate::GetCurrent()->ThrowException(error); + } + + NAN_INLINE v8::Local NanError( + const char *msg + , const int errorNumber + ) { + v8::Local err = v8::Exception::Error(NanNew(msg)); + v8::Local obj = err.As(); + obj->Set(NanNew("code"), NanNew(errorNumber)); + return err; + } + + NAN_INLINE void NanThrowError( + const char *msg + , const int errorNumber + ) { + NanThrowError(NanError(msg, errorNumber)); + } + + NAN_INLINE v8::Local NanTypeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE void NanThrowTypeError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanRangeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::RangeError, errmsg); + } + + NAN_INLINE void NanThrowRangeError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); + } + + template NAN_INLINE void NanDisposePersistent( + v8::Persistent &handle + ) { + handle.Reset(); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + char *data + , size_t length + , node::smalloc::FreeCallback callback + , void *hint + ) { + return node::Buffer::New( + v8::Isolate::GetCurrent(), data, length, callback, hint); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + const char *data + , uint32_t size + ) { + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); + } + + NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { + return node::Buffer::New(v8::Isolate::GetCurrent(), size); + } + + NAN_INLINE v8::Local NanBufferUse( + char* data + , uint32_t size + ) { + return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); + } + + NAN_INLINE bool NanHasInstance( + const v8::Persistent& function_template + , v8::Handle value + ) { + return NanNew(function_template)->HasInstance(value); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( + v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle() + ) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return v8::Local::New( + isolate + , v8::Context::New(isolate, extensions, tmpl, obj) + ); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + , const v8::ScriptOrigin& origin + ) { + v8::ScriptCompiler::Source source(s, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + ) { + v8::ScriptCompiler::Source source(s); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + NAN_INLINE v8::Local NanRunScript( + v8::Handle script + ) { + return script->BindToCurrentContext()->Run(); + } + + NAN_INLINE v8::Local NanRunScript( + v8::Handle script + ) { + return script->Run(); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle func + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv)); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle symbol + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv)); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , const char* method + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv)); + } + + template + NAN_INLINE void NanSetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(0, data); + } + + template + NAN_INLINE T *NanGetIsolateData( + v8::Isolate *isolate + ) { + return static_cast(isolate->GetData(0)); + } + + class NanAsciiString { + public: + NAN_INLINE explicit NanAsciiString(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new char[size + 1]; + size = toStr->WriteOneByte(reinterpret_cast(buf)); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanAsciiString() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanAsciiString(const NanAsciiString&); + void operator=(const NanAsciiString&); + + char *buf; + int size; + }; + + class NanUtf8String { + public: + NAN_INLINE explicit NanUtf8String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Utf8Length(); + buf = new char[size + 1]; + toStr->WriteUtf8(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanUtf8String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUtf8String(const NanUtf8String&); + void operator=(const NanUtf8String&); + + char *buf; + int size; + }; + + class NanUcs2String { + public: + NAN_INLINE explicit NanUcs2String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new uint16_t[size + 1]; + toStr->Write(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE uint16_t* operator*() { return buf; } + NAN_INLINE const uint16_t* operator*() const { return buf; } + + NAN_INLINE ~NanUcs2String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUcs2String(const NanUcs2String&); + void operator=(const NanUcs2String&); + + uint16_t *buf; + int size; + }; + +#else +// Node 0.8 and 0.10 + +# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& +# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args +# define _NAN_METHOD_RETURN_TYPE v8::Handle + +# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & +# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args +# define _NAN_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & +# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args +# define _NAN_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args +# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args +# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args +# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args +# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args +# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args +# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args +# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args +# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args +# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args +# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle + + NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( + const char* data, int length = -1) { + return v8::String::NewSymbol(data, length); + } + +# define NanScope() v8::HandleScope scope +# define NanEscapableScope() v8::HandleScope scope +# define NanEscapeScope(val) scope.Close(val) +# define NanLocker() v8::Locker locker +# define NanUnlocker() v8::Unlocker unlocker +# define NanReturnValue(value) return scope.Close(_NanEnsureLocal(value)) +# define NanReturnHolder() NanReturnValue(args.Holder()) +# define NanReturnThis() NanReturnValue(args.This()) +# define NanReturnUndefined() return v8::Undefined() +# define NanReturnNull() return v8::Null() +# define NanReturnEmptyString() return v8::String::Empty() + + NAN_INLINE v8::Local NanObjectWrapHandle(const node::ObjectWrap *obj) { + return v8::Local::New(obj->handle_); + } + + NAN_INLINE v8::Local NanUndefined() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Undefined())); + } + + NAN_INLINE v8::Local NanNull() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Null())); + } + + NAN_INLINE v8::Local NanTrue() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::True())); + } + + NAN_INLINE v8::Local NanFalse() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::False())); + } + + NAN_INLINE int NanAdjustExternalMemory(int bc) { + return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , const char *name + , v8::Handle value) { + templ->Set(name, value); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + NAN_INLINE v8::Local NanGetCurrentContext() { + return v8::Context::GetCurrent(); + } + + NAN_INLINE void* NanGetInternalFieldPointer( + v8::Handle object + , int index) { + return object->GetPointerFromInternalField(index); + } + + NAN_INLINE void NanSetInternalFieldPointer( + v8::Handle object + , int index + , void* value) { + object->SetPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::GCType type, v8::GCCallbackFlags flags) + + NAN_INLINE void NanAddGCEpilogueCallback( + v8::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); + } + NAN_INLINE void NanRemoveGCEpilogueCallback( + v8::GCEpilogueCallback callback) { + v8::V8::RemoveGCEpilogueCallback(callback); + } + NAN_INLINE void NanAddGCPrologueCallback( + v8::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCPrologueCallback(callback, gc_type_filter); + } + NAN_INLINE void NanRemoveGCPrologueCallback( + v8::GCPrologueCallback callback) { + v8::V8::RemoveGCPrologueCallback(callback); + } + NAN_INLINE void NanGetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::V8::GetHeapStatistics(heap_statistics); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , v8::Handle obj) { + handle.Dispose(); + handle = v8::Persistent::New(obj); + } + + template + class _NanWeakCallbackData; + + template + struct _NanWeakCallbackInfo { + typedef void (*Callback)(const _NanWeakCallbackData &data); + NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) + : parameter(param) + , callback(cb) + , persistent(v8::Persistent::New(handle)) { } + + NAN_INLINE ~_NanWeakCallbackInfo() { + persistent.Dispose(); + persistent.Clear(); + } + + P* const parameter; + Callback const callback; + v8::Persistent persistent; + }; + + template + class _NanWeakCallbackData { + public: + NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) + : info_(info) { } + + NAN_INLINE v8::Local GetValue() const { + return NanNew(info_->persistent); + } + + NAN_INLINE P* GetParameter() const { return info_->parameter; } + + NAN_INLINE bool IsNearDeath() const { + return info_->persistent.IsNearDeath(); + } + + NAN_INLINE void Revive() const; + + NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { + return info_; + } + + NAN_DEPRECATED NAN_INLINE void Dispose() const { + } + + private: + _NanWeakCallbackInfo* info_; + }; + + template + static void _NanWeakPersistentDispatcher( + v8::Persistent object, void *data) { + _NanWeakCallbackInfo* info = + static_cast<_NanWeakCallbackInfo*>(data); + _NanWeakCallbackData wcbd(info); + info->callback(wcbd); + if (wcbd.IsNearDeath()) { + delete wcbd.GetCallbackInfo(); + } + } + + template + NAN_INLINE void _NanWeakCallbackData::Revive() const { + info_->persistent.MakeWeak( + info_ + , &_NanWeakPersistentDispatcher); + } + + template + NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( + v8::Handle handle + , P* parameter + , typename _NanWeakCallbackInfo::Callback callback) { + _NanWeakCallbackInfo *cbinfo = + new _NanWeakCallbackInfo(handle, parameter, callback); + cbinfo->persistent.MakeWeak( + cbinfo + , &_NanWeakPersistentDispatcher); + return cbinfo; + } + +# define NAN_WEAK_CALLBACK(name) \ + template \ + static void name(const _NanWeakCallbackData &data) + +# define _NAN_ERROR(fun, errmsg) \ + fun(v8::String::New(errmsg)) + +# define _NAN_THROW_ERROR(fun, errmsg) \ + do { \ + NanScope(); \ + return v8::Local::New( \ + v8::ThrowException(_NAN_ERROR(fun, errmsg))); \ + } while (0); + + NAN_INLINE v8::Local NanError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE v8::Local NanThrowError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE v8::Local NanThrowError( + v8::Handle error + ) { + NanScope(); + return v8::Local::New(v8::ThrowException(error)); + } + + NAN_INLINE v8::Local NanError( + const char *msg + , const int errorNumber + ) { + v8::Local err = v8::Exception::Error(v8::String::New(msg)); + v8::Local obj = err.As(); + obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); + return err; + } + + NAN_INLINE v8::Local NanThrowError( + const char *msg + , const int errorNumber + ) { + return NanThrowError(NanError(msg, errorNumber)); + } + + NAN_INLINE v8::Local NanTypeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanThrowTypeError( + const char* errmsg + ) { + _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanRangeError( + const char* errmsg + ) { + return _NAN_ERROR(v8::Exception::RangeError, errmsg); + } + + NAN_INLINE v8::Local NanThrowRangeError( + const char* errmsg + ) { + _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); + } + + template + NAN_INLINE void NanDisposePersistent( + v8::Persistent &handle) { // NOLINT(runtime/references) + handle.Dispose(); + handle.Clear(); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + char *data + , size_t length + , node::Buffer::free_callback callback + , void *hint + ) { + return NanNew( + node::Buffer::New(data, length, callback, hint)->handle_); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + const char *data + , uint32_t size + ) { +#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION + return NanNew(node::Buffer::New(data, size)->handle_); +#else + return NanNew( + node::Buffer::New(const_cast(data), size)->handle_); +#endif + } + + NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { + return NanNew(node::Buffer::New(size)->handle_); + } + + NAN_INLINE void FreeData(char *data, void *hint) { + delete[] data; + } + + NAN_INLINE v8::Local NanBufferUse( + char* data + , uint32_t size + ) { + return NanNew( + node::Buffer::New(data, size, FreeData, NULL)->handle_); + } + + NAN_INLINE bool NanHasInstance( + const v8::Persistent& function_template + , v8::Handle value + ) { + return function_template->HasInstance(value); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( + v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle() + ) { + v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local lctx = NanNew(ctx); + ctx.Dispose(); + return lctx; + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + , const v8::ScriptOrigin& origin + ) { + return v8::Script::Compile(s, const_cast(&origin)); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + ) { + return v8::Script::Compile(s); + } + + NAN_INLINE v8::Local NanRunScript(v8::Handle script) { + return script->Run(); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle func + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, func, argc, argv)); +# else + v8::TryCatch try_catch; + v8::Local result = func->Call(target, argc, argv); + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + return result; +# endif + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle symbol + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, symbol, argc, argv)); +# else + v8::Local callback = target->Get(symbol).As(); + return NanMakeCallback(target, callback, argc, argv); +# endif + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , const char* method + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, method, argc, argv)); +# else + return NanMakeCallback(target, NanNew(method), argc, argv); +# endif + } + + template + NAN_INLINE void NanSetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(data); + } + + template + NAN_INLINE T *NanGetIsolateData( + v8::Isolate *isolate + ) { + return static_cast(isolate->GetData()); + } + + class NanAsciiString { + public: + NAN_INLINE explicit NanAsciiString(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new char[size + 1]; + size = toStr->WriteAscii(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanAsciiString() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanAsciiString(const NanAsciiString&); + void operator=(const NanAsciiString&); + + char *buf; + int size; + }; + + class NanUtf8String { + public: + NAN_INLINE explicit NanUtf8String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Utf8Length(); + buf = new char[size + 1]; + toStr->WriteUtf8(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + NAN_INLINE const char* operator*() const { return buf; } + + NAN_INLINE ~NanUtf8String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUtf8String(const NanUtf8String&); + void operator=(const NanUtf8String&); + + char *buf; + int size; + }; + + class NanUcs2String { + public: + NAN_INLINE explicit NanUcs2String(v8::Handle from) { + v8::Local toStr = from->ToString(); + size = toStr->Length(); + buf = new uint16_t[size + 1]; + toStr->Write(buf); + } + + NAN_DEPRECATED NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE int length() const { + return size; + } + + NAN_INLINE uint16_t* operator*() { return buf; } + NAN_INLINE const uint16_t* operator*() const { return buf; } + + NAN_INLINE ~NanUcs2String() { + delete[] buf; + } + + private: + // disallow copying and assigning + NanUcs2String(const NanUcs2String&); + void operator=(const NanUcs2String&); + + uint16_t *buf; + int size; + }; + +#endif // NODE_MODULE_VERSION + +typedef void (*NanFreeCallback)(char *data, void *hint); + +#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) +#define NAN_GETTER(name) \ + _NAN_GETTER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_GETTER_ARGS) +#define NAN_SETTER(name) \ + _NAN_SETTER_RETURN_TYPE name( \ + v8::Local property \ + , v8::Local value \ + , _NAN_SETTER_ARGS) +#define NAN_PROPERTY_GETTER(name) \ + _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_GETTER_ARGS) +#define NAN_PROPERTY_SETTER(name) \ + _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ + v8::Local property \ + , v8::Local value \ + , _NAN_PROPERTY_SETTER_ARGS) +#define NAN_PROPERTY_ENUMERATOR(name) \ + _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) +#define NAN_PROPERTY_DELETER(name) \ + _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_DELETER_ARGS) +#define NAN_PROPERTY_QUERY(name) \ + _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_QUERY_ARGS) +# define NAN_INDEX_GETTER(name) \ + _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) +#define NAN_INDEX_SETTER(name) \ + _NAN_INDEX_SETTER_RETURN_TYPE name( \ + uint32_t index \ + , v8::Local value \ + , _NAN_INDEX_SETTER_ARGS) +#define NAN_INDEX_ENUMERATOR(name) \ + _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) +#define NAN_INDEX_DELETER(name) \ + _NAN_INDEX_DELETER_RETURN_TYPE name( \ + uint32_t index \ + , _NAN_INDEX_DELETER_ARGS) +#define NAN_INDEX_QUERY(name) \ + _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) + +class NanCallback { + public: + NanCallback() { + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(handle, obj); + } + + explicit NanCallback(const v8::Handle &fn) { + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(handle, obj); + SetFunction(fn); + } + + ~NanCallback() { + if (handle.IsEmpty()) return; + NanDisposePersistent(handle); + } + + bool operator==(const NanCallback &other) const { + NanScope(); + v8::Local a = NanNew(handle)->Get(kCallbackIndex); + v8::Local b = NanNew(other.handle)->Get(kCallbackIndex); + return a->StrictEquals(b); + } + + bool operator!=(const NanCallback &other) const { + return !this->operator==(other); + } + + NAN_INLINE void SetFunction(const v8::Handle &fn) { + NanScope(); + NanNew(handle)->Set(kCallbackIndex, fn); + } + + NAN_INLINE v8::Local GetFunction() const { + NanEscapableScope(); + return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex) + .As()); + } + + NAN_INLINE bool IsEmpty() const { + NanScope(); + return NanNew(handle)->Get(kCallbackIndex)->IsUndefined(); + } + + NAN_INLINE v8::Handle + Call(v8::Handle target + , int argc + , v8::Handle argv[]) const { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, target, argc, argv); +#else + return Call_(target, argc, argv); +#endif + } + + NAN_INLINE v8::Handle + Call(int argc, v8::Handle argv[]) const { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv); +#else + return Call_(v8::Context::GetCurrent()->Global(), argc, argv); +#endif + } + + private: + v8::Persistent handle; + static const uint32_t kCallbackIndex = 0; + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Handle Call_(v8::Isolate *isolate + , v8::Handle target + , int argc + , v8::Handle argv[]) const { +#else + v8::Handle Call_(v8::Handle target + , int argc + , v8::Handle argv[]) const { +#endif + NanEscapableScope(); +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + v8::Local callback = NanNew(handle)-> + Get(kCallbackIndex).As(); + return NanEscapeScope(node::MakeCallback( + isolate + , target + , callback + , argc + , argv + )); +#else +#if NODE_VERSION_AT_LEAST(0, 8, 0) + v8::Local callback = handle-> + Get(kCallbackIndex).As(); + return NanEscapeScope(node::MakeCallback( + target + , callback + , argc + , argv + )); +#else + v8::Local callback = handle-> + Get(kCallbackIndex).As(); + return NanEscapeScope(NanMakeCallback( + target, callback, argc, argv)); +#endif +#endif + } +}; + +/* abstract */ class NanAsyncWorker { + public: + explicit NanAsyncWorker(NanCallback *callback_) + : callback(callback_), errmsg_(NULL) { + request.data = this; + + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(persistentHandle, obj); + } + + virtual ~NanAsyncWorker() { + NanScope(); + + if (!persistentHandle.IsEmpty()) + NanDisposePersistent(persistentHandle); + if (callback) + delete callback; + if (errmsg_) + delete[] errmsg_; + } + + virtual void WorkComplete() { + NanScope(); + + if (errmsg_ == NULL) + HandleOKCallback(); + else + HandleErrorCallback(); + delete callback; + callback = NULL; + } + + NAN_INLINE void SaveToPersistent( + const char *key, const v8::Local &obj) { + v8::Local handle = NanNew(persistentHandle); + handle->Set(NanNew(key), obj); + } + + v8::Local GetFromPersistent(const char *key) const { + NanEscapableScope(); + v8::Local handle = NanNew(persistentHandle); + return NanEscapeScope(handle->Get(NanNew(key)).As()); + } + + virtual void Execute() = 0; + + uv_work_t request; + + virtual void Destroy() { + delete this; + } + + protected: + v8::Persistent persistentHandle; + NanCallback *callback; + + virtual void HandleOKCallback() { + callback->Call(0, NULL); + } + + virtual void HandleErrorCallback() { + NanScope(); + + v8::Local argv[] = { + v8::Exception::Error(NanNew(ErrorMessage())) + }; + callback->Call(1, argv); + } + + void SetErrorMessage(const char *msg) { + if (errmsg_) { + delete[] errmsg_; + } + + size_t size = strlen(msg) + 1; + errmsg_ = new char[size]; + memcpy(errmsg_, msg, size); + } + + const char* ErrorMessage() const { + return errmsg_; + } + + private: + char *errmsg_; +}; + +/* abstract */ class NanAsyncProgressWorker : public NanAsyncWorker { + public: + explicit NanAsyncProgressWorker(NanCallback *callback_) + : NanAsyncWorker(callback_), asyncdata_(NULL), asyncsize_(0) { + async = new uv_async_t; + uv_async_init( + uv_default_loop() + , async + , AsyncProgress_ + ); + async->data = this; + + uv_mutex_init(&async_lock); + } + + virtual ~NanAsyncProgressWorker() { + uv_mutex_destroy(&async_lock); + + if (asyncdata_) { + delete[] asyncdata_; + } + } + + void WorkProgress() { + uv_mutex_lock(&async_lock); + char *data = asyncdata_; + size_t size = asyncsize_; + asyncdata_ = NULL; + uv_mutex_unlock(&async_lock); + + // Dont send progress events after we've already completed. + if (callback) { + HandleProgressCallback(data, size); + } + delete[] data; + } + + class ExecutionProgress { + friend class NanAsyncProgressWorker; + public: + // You could do fancy generics with templates here. + void Send(const char* data, size_t size) const { + that_->SendProgress_(data, size); + } + + private: + explicit ExecutionProgress(NanAsyncProgressWorker* that) : that_(that) {} + // Prohibit copying and assignment. + ExecutionProgress(const ExecutionProgress&); + void operator=(const ExecutionProgress&); + #if __cplusplus >= 201103L + // Prohibit C++11 move semantics. + ExecutionProgress(ExecutionProgress&&) = delete; + void operator=(ExecutionProgress&&) = delete; + #endif + NanAsyncProgressWorker* const that_; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void HandleProgressCallback(const char *data, size_t size) = 0; + + virtual void Destroy() { + uv_close(reinterpret_cast(async), AsyncClose_); + } + + private: + void Execute() /*final override*/ { + ExecutionProgress progress(this); + Execute(progress); + } + + void SendProgress_(const char *data, size_t size) { + char *new_data = new char[size]; + memcpy(new_data, data, size); + + uv_mutex_lock(&async_lock); + char *old_data = asyncdata_; + asyncdata_ = new_data; + asyncsize_ = size; + uv_mutex_unlock(&async_lock); + + if (old_data) { + delete[] old_data; + } + uv_async_send(async); + } + + NAN_INLINE static NAUV_WORK_CB(AsyncProgress_) { + NanAsyncProgressWorker *worker = + static_cast(async->data); + worker->WorkProgress(); + } + + NAN_INLINE static void AsyncClose_(uv_handle_t* handle) { + NanAsyncProgressWorker *worker = + static_cast(handle->data); + delete reinterpret_cast(handle); + delete worker; + } + + uv_async_t *async; + uv_mutex_t async_lock; + char *asyncdata_; + size_t asyncsize_; +}; + +NAN_INLINE void NanAsyncExecute (uv_work_t* req) { + NanAsyncWorker *worker = static_cast(req->data); + worker->Execute(); +} + +NAN_INLINE void NanAsyncExecuteComplete (uv_work_t* req) { + NanAsyncWorker* worker = static_cast(req->data); + worker->WorkComplete(); + worker->Destroy(); +} + +NAN_INLINE void NanAsyncQueueWorker (NanAsyncWorker* worker) { + uv_queue_work( + uv_default_loop() + , &worker->request + , NanAsyncExecute + , (uv_after_work_cb)NanAsyncExecuteComplete + ); +} + +//// Base 64 //// + +#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + +// Doesn't check for padding at the end. Can be 1-2 bytes over. +NAN_INLINE size_t _nan_base64_decoded_size_fast(size_t size) { + size_t remainder = size % 4; + + size = (size / 4) * 3; + if (remainder) { + if (size == 0 && remainder == 1) { + // special case: 1-byte input cannot be decoded + size = 0; + } else { + // non-padded input, add 1 or 2 extra bytes + size += 1 + (remainder == 3); + } + } + + return size; +} + +template +NAN_INLINE size_t _nan_base64_decoded_size( + const T* src + , size_t size +) { + if (size == 0) + return 0; + + if (src[size - 1] == '=') + size--; + if (size > 0 && src[size - 1] == '=') + size--; + + return _nan_base64_decoded_size_fast(size); +} + +// supports regular and URL-safe base64 +static const int _nan_unbase64_table[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 + , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 + , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 + , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 + , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 + , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 +}; + +#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] + +template static size_t _nan_base64_decode( + char* buf + , size_t len + , const T* src + , const size_t srcLen +) { + char* dst = buf; + char* dstEnd = buf + len; + const T* srcEnd = src + srcLen; + + while (src < srcEnd && dst < dstEnd) { + ptrdiff_t remaining = srcEnd - src; + char a, b, c, d; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining == 0 || *src == '=') break; + a = _nan_unbase64(*src++); + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 1 || *src == '=') break; + b = _nan_unbase64(*src++); + + *dst++ = (a << 2) | ((b & 0x30) >> 4); + if (dst == dstEnd) break; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 2 || *src == '=') break; + c = _nan_unbase64(*src++); + + *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); + if (dst == dstEnd) break; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 3 || *src == '=') break; + d = _nan_unbase64(*src++); + + *dst++ = ((c & 0x03) << 6) | (d & 0x3F); + } + + return dst - buf; +} + +//// HEX //// + +template unsigned _nan_hex2bin(T c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); + if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); + return static_cast(-1); +} + +template static size_t _nan_hex_decode( + char* buf + , size_t len + , const T* src + , const size_t srcLen +) { + size_t i; + for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { + unsigned a = _nan_hex2bin(src[i * 2 + 0]); + unsigned b = _nan_hex2bin(src[i * 2 + 1]); + if (!~a || !~b) return i; + buf[i] = a * 16 + b; + } + + return i; +} + +namespace NanIntern { + +inline +NanExternalOneByteStringResource const* +GetExternalResource(v8::Local str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->GetExternalAsciiStringResource(); +#else + return str->GetExternalOneByteStringResource(); +#endif +} + +inline +bool +IsExternal(v8::Local str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->IsExternalAscii(); +#else + return str->IsExternalOneByte(); +#endif +} + +} // end of namespace NanIntern + +static bool _NanGetExternalParts( + v8::Handle val + , const char** data + , size_t* len +) { + if (node::Buffer::HasInstance(val)) { + *data = node::Buffer::Data(val.As()); + *len = node::Buffer::Length(val.As()); + return true; + } + + assert(val->IsString()); + v8::Local str = NanNew(val.As()); + + if (NanIntern::IsExternal(str)) { + const NanExternalOneByteStringResource* ext; + ext = NanIntern::GetExternalResource(str); + *data = ext->data(); + *len = ext->length(); + return true; + } + + if (str->IsExternal()) { + const v8::String::ExternalStringResource* ext; + ext = str->GetExternalStringResource(); + *data = reinterpret_cast(ext->data()); + *len = ext->length(); + return true; + } + + return false; +} + +namespace Nan { + enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; +} + +#if !NODE_VERSION_AT_LEAST(0, 10, 0) +# include "nan_string_bytes.h" // NOLINT(build/include) +#endif + +NAN_INLINE v8::Local NanEncode( + const void *buf, size_t len, enum Nan::Encoding encoding = Nan::BINARY) { +#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + node::encoding node_enc = static_cast(encoding); + + if (encoding == Nan::UCS2) { + return node::Encode( + isolate + , reinterpret_cast(buf) + , len / 2); + } else { + return node::Encode( + isolate + , reinterpret_cast(buf) + , len + , node_enc); + } +#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::Encode( + v8::Isolate::GetCurrent() + , buf, len + , static_cast(encoding)); +#else +# if NODE_VERSION_AT_LEAST(0, 10, 0) + return node::Encode(buf, len, static_cast(encoding)); +# else + return NanIntern::Encode(reinterpret_cast(buf), len, encoding); +# endif +#endif +} + +NAN_INLINE ssize_t NanDecodeBytes( + v8::Handle val, enum Nan::Encoding encoding = Nan::BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeBytes( + v8::Isolate::GetCurrent() + , val + , static_cast(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == Nan::BUFFER) { + return node::DecodeBytes(val, node::BINARY); + } +# endif + return node::DecodeBytes(val, static_cast(encoding)); +#endif +} + +NAN_INLINE ssize_t NanDecodeWrite( + char *buf + , size_t len + , v8::Handle val + , enum Nan::Encoding encoding = Nan::BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeWrite( + v8::Isolate::GetCurrent() + , buf + , len + , val + , static_cast(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == Nan::BUFFER) { + return node::DecodeWrite(buf, len, val, node::BINARY); + } +# endif + return node::DecodeWrite( + buf + , len + , val + , static_cast(encoding)); +#endif +} + +/* NAN_DEPRECATED */ NAN_INLINE void* _NanRawString( + v8::Handle from + , enum Nan::Encoding encoding + , size_t *datalen + , void *buf + , size_t buflen + , int flags +) { + NanScope(); + + size_t sz_; + size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); + char *data = NULL; + size_t len; + bool is_extern = _NanGetExternalParts( + from + , const_cast(&data) + , &len); + + if (is_extern && !term_len) { + NanSetPointerSafe(datalen, len); + return data; + } + + v8::Local toStr = from->ToString(); + + char *to = static_cast(buf); + + switch (encoding) { + case Nan::ASCII: +#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , toStr->WriteAscii(to, 0, static_cast(sz_ + term_len), flags)); + return to; +#endif + case Nan::BINARY: + case Nan::BUFFER: + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } +#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION + { + uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; + + size_t somelen = toStr->Write(twobytebuf, 0, + static_cast(sz_ + term_len), flags); + + for (size_t i = 0; i < sz_ + term_len && i < somelen + term_len; i++) { + unsigned char *b = reinterpret_cast(&twobytebuf[i]); + to[i] = *b; + } + + NanSetPointerSafe(datalen, somelen); + + delete[] twobytebuf; + return to; + } +#else + NanSetPointerSafe( + datalen, + toStr->WriteOneByte( + reinterpret_cast(to) + , 0 + , static_cast(sz_ + term_len) + , flags)); + return to; +#endif + case Nan::UTF8: + sz_ = toStr->Utf8Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , toStr->WriteUtf8(to, static_cast(sz_ + term_len) + , NULL, flags) + - term_len); + return to; + case Nan::BASE64: + { + v8::String::Value value(toStr); + sz_ = _nan_base64_decoded_size(*value, value.length()); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len); + } + NanSetPointerSafe( + datalen + , _nan_base64_decode(to, sz_, *value, value.length())); + if (term_len) { + to[sz_] = '\0'; + } + return to; + } + case Nan::UCS2: + { + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[(sz_ + term_len) * 2]; + } else { + assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); + } + + int bc = 2 * toStr->Write( + reinterpret_cast(to) + , 0 + , static_cast(sz_ + term_len) + , flags); + NanSetPointerSafe(datalen, bc); + return to; + } + case Nan::HEX: + { + v8::String::Value value(toStr); + sz_ = value.length(); + assert(!(sz_ & 1) && "bad hex data"); + if (to == NULL) { + to = new char[sz_ / 2 + term_len]; + } else { + assert(buflen >= sz_ / 2 + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , _nan_hex_decode(to, sz_ / 2, *value, value.length())); + } + if (term_len) { + to[sz_ / 2] = '\0'; + } + return to; + default: + assert(0 && "unknown encoding"); + } + return to; +} + +NAN_DEPRECATED NAN_INLINE void* NanRawString( + v8::Handle from + , enum Nan::Encoding encoding + , size_t *datalen + , void *buf + , size_t buflen + , int flags +) { + return _NanRawString(from, encoding, datalen, buf, buflen, flags); +} + + +NAN_DEPRECATED NAN_INLINE char* NanCString( + v8::Handle from + , size_t *datalen + , char *buf = NULL + , size_t buflen = 0 + , int flags = v8::String::NO_OPTIONS +) { + return static_cast( + _NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags) + ); +} + +NAN_INLINE void NanSetPrototypeTemplate( + v8::Local templ + , const char *name + , v8::Handle value +) { + NanSetTemplate(templ->PrototypeTemplate(), name, value); +} + +NAN_INLINE void NanSetPrototypeTemplate( + v8::Local templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes +) { + NanSetTemplate(templ->PrototypeTemplate(), name, value, attributes); +} + +NAN_INLINE void NanSetInstanceTemplate( + v8::Local templ + , const char *name + , v8::Handle value +) { + NanSetTemplate(templ->InstanceTemplate(), name, value); +} + +NAN_INLINE void NanSetInstanceTemplate( + v8::Local templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes +) { + NanSetTemplate(templ->InstanceTemplate(), name, value, attributes); +} + +//=== Export ================================================================== + +inline +void +NanExport(v8::Handle target, const char * name, + NanFunctionCallback f) { + target->Set(NanNew(name), + NanNew(f)->GetFunction()); +} + +//=== Tap Reverse Binding ===================================================== + +struct NanTap { + explicit NanTap(v8::Handle t) : t_() { + NanAssignPersistent(t_, t->ToObject()); + } + + ~NanTap() { NanDisposePersistent(t_); } // not sure if neccessary + + inline void plan(int i) { + v8::Handle arg = NanNew(i); + NanMakeCallback(NanNew(t_), "plan", 1, &arg); + } + + inline void ok(bool isOk, const char * msg = NULL) { + v8::Handle args[2]; + args[0] = NanNew(isOk); + if (msg) args[1] = NanNew(msg); + NanMakeCallback(NanNew(t_), "ok", msg ? 2 : 1, args); + } + + private: + v8::Persistent t_; +}; + +#define NAN_STRINGIZE2(x) #x +#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) +#define NAN_TEST_EXPRESSION(expression) \ + ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression + +#define return_NanValue(v) NanReturnValue(v) +#define return_NanUndefined() NanReturnUndefined() +#define NAN_EXPORT(target, function) NanExport(target, #function, function) + +#endif // NAN_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h new file mode 100644 index 0000000..fc0e0ac --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h @@ -0,0 +1,261 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors + * + * MIT License + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_12_INL_H_ +#define NAN_IMPLEMENTATION_12_INL_H_ +//============================================================================== +// node v0.11 implementation +//============================================================================== + +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# pragma warning( pop ) +#else +# include +#endif + +namespace NanIntern { + +//=== Array ==================================================================== + +Factory::return_t +Factory::New() { + return v8::Array::New(v8::Isolate::GetCurrent()); +} + +Factory::return_t +Factory::New(int length) { + return v8::Array::New(v8::Isolate::GetCurrent(), length); +} + +//=== Boolean ================================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::Boolean::New(v8::Isolate::GetCurrent(), value); +} + +//=== Boolean Object =========================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::BooleanObject::New(value).As(); +} + +//=== Context ================================================================== + +Factory::return_t +Factory::New( v8::ExtensionConfiguration* extensions + , v8::Handle tmpl + , v8::Handle obj) { + return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); +} + +//=== Date ===================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); +} + +//=== External ================================================================= + +Factory::return_t +Factory::New(void * value) { + return v8::External::New(v8::Isolate::GetCurrent(), value); +} + +//=== Function ================================================================= + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data) { + return v8::Function::New( v8::Isolate::GetCurrent() + , callback + , data); +} + +//=== Function Template ======================================================== + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data + , v8::Handle signature) { + return v8::FunctionTemplate::New( v8::Isolate::GetCurrent() + , callback + , data + , signature); +} + +//=== Number =================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Number::New(v8::Isolate::GetCurrent(), value); +} + +//=== Number Object ============================================================ + +Factory::return_t +Factory::New(double value) { + return v8::NumberObject::New( v8::Isolate::GetCurrent() + , value).As(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template +typename IntegerFactory::return_t +IntegerFactory::New(int32_t value) { + return To(T::New(v8::Isolate::GetCurrent(), value)); +} + +template +typename IntegerFactory::return_t +IntegerFactory::New(uint32_t value) { + return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory::return_t +Factory::New(int32_t value) { + return To( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory::return_t +Factory::New(uint32_t value) { + return To( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +//=== Object =================================================================== + +Factory::return_t +Factory::New() { + return v8::Object::New(v8::Isolate::GetCurrent()); +} + +//=== Object Template ========================================================== + +Factory::return_t +Factory::New() { + return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); +} + +//=== RegExp =================================================================== + +Factory::return_t +Factory::New( + v8::Handle pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} + +//=== Script =================================================================== + +Factory::return_t +Factory::New( v8::Local source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} + +Factory::return_t +Factory::New( v8::Local source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} + +//=== Signature ================================================================ + +Factory::return_t +Factory::New(Factory::FTH receiver) { + return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); +} + +//=== String =================================================================== + +Factory::return_t +Factory::New() { + return v8::String::Empty(v8::Isolate::GetCurrent()); +} + +Factory::return_t +Factory::New(const char * value, int length) { + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory::return_t +Factory::New(std::string const& value) { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), + value.data(), v8::String::kNormalString, static_cast(value.size())); +} + +Factory::return_t +Factory::New(const uint8_t * value, int length) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory::return_t +Factory::New(const uint16_t * value, int length) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory::return_t +Factory::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} + +Factory::return_t +Factory::New(NanExternalOneByteStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} + +//=== String Object ============================================================ + +Factory::return_t +Factory::New(v8::Handle value) { + return v8::StringObject::New(value).As(); +} + +//=== Unbound Script =========================================================== + +Factory::return_t +Factory::New(v8::Local source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} + +Factory::return_t +Factory::New( v8::Local source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} + +} // end of namespace NanIntern + +//=== Presistents and Handles ================================================== + +template +inline v8::Local NanNew(v8::Handle h) { + return v8::Local::New(v8::Isolate::GetCurrent(), h); +} + +template +inline v8::Local NanNew(v8::Persistent const& p) { + return v8::Local::New(v8::Isolate::GetCurrent(), p); +} + +#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h new file mode 100644 index 0000000..e995a14 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h @@ -0,0 +1,267 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors + * + * MIT License + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ +#define NAN_IMPLEMENTATION_PRE_12_INL_H_ + +#include + +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# include +# pragma warning( pop ) +#else +# include +# include +#endif + +//============================================================================== +// node v0.10 implementation +//============================================================================== + +namespace NanIntern { + +//=== Array ==================================================================== + +Factory::return_t +Factory::New() { + return v8::Array::New(); +} + +Factory::return_t +Factory::New(int length) { + return v8::Array::New(length); +} + +//=== Boolean ================================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::Boolean::New(value)->ToBoolean(); +} + +//=== Boolean Object =========================================================== + +Factory::return_t +Factory::New(bool value) { + return v8::BooleanObject::New(value).As(); +} + +//=== Context ================================================================== + +Factory::return_t +Factory::New( v8::ExtensionConfiguration* extensions + , v8::Handle tmpl + , v8::Handle obj) { + v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local lctx = v8::Local::New(ctx); + ctx.Dispose(); + return lctx; +} + +//=== Date ===================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Date::New(value).As(); +} + +//=== External ================================================================= + +Factory::return_t +Factory::New(void * value) { + return v8::External::New(value); +} + +//=== Function ================================================================= + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data) { + return Factory::New( callback + , data + , v8::Handle() + )->GetFunction(); +} + + +//=== FunctionTemplate ========================================================= + +Factory::return_t +Factory::New( NanFunctionCallback callback + , v8::Handle data + , v8::Handle signature) { + // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find + // a way. Have at it though... + return v8::FunctionTemplate::New( callback + , data + , signature); +} + +//=== Number =================================================================== + +Factory::return_t +Factory::New(double value) { + return v8::Number::New(value); +} + +//=== Number Object ============================================================ + +Factory::return_t +Factory::New(double value) { + return v8::NumberObject::New(value).As(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template +typename IntegerFactory::return_t +IntegerFactory::New(int32_t value) { + return To(T::New(value)); +} + +template +typename IntegerFactory::return_t +IntegerFactory::New(uint32_t value) { + return To(T::NewFromUnsigned(value)); +} + +Factory::return_t +Factory::New(int32_t value) { + return To(v8::Uint32::NewFromUnsigned(value)); +} + +Factory::return_t +Factory::New(uint32_t value) { + return To(v8::Uint32::NewFromUnsigned(value)); +} + + +//=== Object =================================================================== + +Factory::return_t +Factory::New() { + return v8::Object::New(); +} + +//=== Object Template ========================================================== + +Factory::return_t +Factory::New() { + return v8::ObjectTemplate::New(); +} + +//=== RegExp =================================================================== + +Factory::return_t +Factory::New( + v8::Handle pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} + +//=== Script =================================================================== + +Factory::return_t +Factory::New( v8::Local source) { + return v8::Script::New(source); +} +Factory::return_t +Factory::New( v8::Local source + , v8::ScriptOrigin const& origin) { + return v8::Script::New(source, const_cast(&origin)); +} + +//=== Signature ================================================================ + +Factory::return_t +Factory::New(Factory::FTH receiver) { + return v8::Signature::New(receiver); +} + +//=== String =================================================================== + +Factory::return_t +Factory::New() { + return v8::String::Empty(); +} + +Factory::return_t +Factory::New(const char * value, int length) { + return v8::String::New(value, length); +} + +Factory::return_t +Factory::New(std::string const& value) { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::New( value.data(), static_cast(value.size())); +} + +inline +void +widenString(std::vector *ws, const uint8_t *s, int l = -1) { + size_t len = static_cast(l); + if (l < 0) { + len = strlen(reinterpret_cast(s)); + } + assert(len <= INT_MAX && "string too long"); + ws->resize(len); + std::copy(s, s + len, ws->begin()); +} + +Factory::return_t +Factory::New(const uint16_t * value, int length) { + return v8::String::New(value, length); +} + +Factory::return_t +Factory::New(const uint8_t * value, int length) { + std::vector wideString; + widenString(&wideString, value, length); + if (wideString.size() == 0) { + return v8::String::Empty(); + } else { + return v8::String::New(&wideString.front() + , static_cast(wideString.size())); + } +} + +Factory::return_t +Factory::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(value); +} + +Factory::return_t +Factory::New(v8::String::ExternalAsciiStringResource * value) { + return v8::String::NewExternal(value); +} + +//=== String Object ============================================================ + +Factory::return_t +Factory::New(v8::Handle value) { + return v8::StringObject::New(value).As(); +} + +} // end of namespace NanIntern + +//=== Presistents and Handles ================================================== + +template +inline v8::Local NanNew(v8::Handle h) { + return v8::Local::New(h); +} + +template +inline v8::Local NanNew(v8::Persistent const& p) { + return v8::Local::New(p); +} + +#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h new file mode 100644 index 0000000..c189092 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h @@ -0,0 +1,328 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2015 NAN contributors + * + * MIT License + ********************************************************************/ + +#ifndef NAN_NEW_H_ +#define NAN_NEW_H_ + +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include +# pragma warning( pop ) +#else +# include +#endif + +namespace NanIntern { // scnr + +// TODO(agnat): Generalize +template v8::Local To(v8::Handle i); + +template <> +inline +v8::Local +To(v8::Handle i) { return i->ToInteger(); } + +template <> +inline +v8::Local +To(v8::Handle i) { return i->ToInt32(); } + +template <> +inline +v8::Local +To(v8::Handle i) { return i->ToUint32(); } + +template struct FactoryBase { typedef v8::Local return_t; }; + +template struct Factory; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); + static inline return_t New(int length); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(bool value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(bool value); +}; + +template <> +struct Factory : FactoryBase { + static inline + return_t + New( v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle()); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(double value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(void *value); +}; + +template <> +struct Factory : FactoryBase { + static inline + return_t + New( NanFunctionCallback callback + , v8::Handle data = v8::Handle()); +}; + +template <> +struct Factory : FactoryBase { + static inline + return_t + New( NanFunctionCallback callback = NULL + , v8::Handle data = v8::Handle() + , v8::Handle signature = v8::Handle()); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(double value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(double value); +}; + +template +struct IntegerFactory : FactoryBase { + typedef typename FactoryBase::return_t return_t; + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory : IntegerFactory {}; + +template <> +struct Factory : IntegerFactory {}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New( + v8::Handle pattern, v8::RegExp::Flags flags); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New( v8::Local source); + static inline return_t New( v8::Local source + , v8::ScriptOrigin const& origin); +}; + +template <> +struct Factory : FactoryBase { + typedef v8::Handle FTH; + static inline return_t New(FTH receiver = FTH()); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(); + static inline return_t New(const char *value, int length = -1); + static inline return_t New(const uint16_t *value, int length = -1); + static inline return_t New(std::string const& value); + + static inline return_t New(v8::String::ExternalStringResource * value); + static inline return_t New(NanExternalOneByteStringResource * value); + + // TODO(agnat): Deprecate. + static inline return_t New(const uint8_t * value, int length = -1); +}; + +template <> +struct Factory : FactoryBase { + static inline return_t New(v8::Handle value); +}; + +} // end of namespace NanIntern + +#if (NODE_MODULE_VERSION >= 12) + +namespace NanIntern { + +template <> +struct Factory : FactoryBase { + static inline return_t New( v8::Local source); + static inline return_t New( v8::Local source + , v8::ScriptOrigin const& origin); +}; + +} // end of namespace NanIntern + +# include "nan_implementation_12_inl.h" + +#else // NODE_MODULE_VERSION >= 12 + +# include "nan_implementation_pre_12_inl.h" + +#endif + +//=== API ====================================================================== + +template +typename NanIntern::Factory::return_t +NanNew() { + return NanIntern::Factory::New(); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0) { + return NanIntern::Factory::New(arg0); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0, A1 arg1) { + return NanIntern::Factory::New(arg0, arg1); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0, A1 arg1, A2 arg2) { + return NanIntern::Factory::New(arg0, arg1, arg2); +} + +template +typename NanIntern::Factory::return_t +NanNew(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { + return NanIntern::Factory::New(arg0, arg1, arg2, arg3); +} + +// Note(agnat): When passing overloaded function pointers to template functions +// as generic arguments the compiler needs help in picking the right overload. +// These two functions handle NanNew and NanNew with +// all argument variations. + +// v8::Function and v8::FunctionTemplate with one or two arguments +template +typename NanIntern::Factory::return_t +NanNew( NanFunctionCallback callback + , v8::Handle data = v8::Handle()) { + return NanIntern::Factory::New(callback, data); +} + +// v8::Function and v8::FunctionTemplate with three arguments +template +typename NanIntern::Factory::return_t +NanNew( NanFunctionCallback callback + , v8::Handle data = v8::Handle() + , A2 a2 = A2()) { + return NanIntern::Factory::New(callback, data, a2); +} + +// Convenience + +template inline v8::Local NanNew(v8::Handle h); +template inline v8::Local NanNew(v8::Persistent const& p); + +inline +NanIntern::Factory::return_t +NanNew(bool value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(int32_t value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(uint32_t value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(double value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(std::string const& value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(const char * value, int length) { + return NanNew(value, length); +} + +inline +NanIntern::Factory::return_t +NanNew(const char * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(const uint8_t * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(const uint16_t * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(v8::String::ExternalStringResource * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(NanExternalOneByteStringResource * value) { + return NanNew(value); +} + +inline +NanIntern::Factory::return_t +NanNew(v8::Handle pattern, v8::RegExp::Flags flags) { + return NanNew(pattern, flags); +} + +#endif // NAN_NEW_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h new file mode 100644 index 0000000..9deecfb --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h @@ -0,0 +1,312 @@ +// 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. + +#ifndef NAN_STRING_BYTES_H_ +#define NAN_STRING_BYTES_H_ + +// Decodes a v8::Handle or Buffer to a raw char* + +#include +#include +#include +#include // memcpy +#include + +namespace NanIntern { + +using v8::Local; +using v8::Handle; +using v8::Object; +using v8::String; +using v8::Value; + + +//// Base 64 //// + +#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + + + +//// Nan::HEX //// + +static bool contains_non_ascii_slow(const char* buf, size_t len) { + for (size_t i = 0; i < len; ++i) { + if (buf[i] & 0x80) return true; + } + return false; +} + + +static bool contains_non_ascii(const char* src, size_t len) { + if (len < 16) { + return contains_non_ascii_slow(src, len); + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned unaligned = reinterpret_cast(src) & align_mask; + + if (unaligned > 0) { + const unsigned n = bytes_per_word - unaligned; + if (contains_non_ascii_slow(src, n)) return true; + src += n; + len -= n; + } + + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = 0x8080808080808080ll; +#else + const uintptr_t mask = 0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast(src); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + if (srcw[i] & mask) return true; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + if (contains_non_ascii_slow(src + offset, remainder)) return true; + } + + return false; +} + + +static void force_ascii_slow(const char* src, char* dst, size_t len) { + for (size_t i = 0; i < len; ++i) { + dst[i] = src[i] & 0x7f; + } +} + + +static void force_ascii(const char* src, char* dst, size_t len) { + if (len < 16) { + force_ascii_slow(src, dst, len); + return; + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned src_unalign = reinterpret_cast(src) & align_mask; + const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; + + if (src_unalign > 0) { + if (src_unalign == dst_unalign) { + const unsigned unalign = bytes_per_word - src_unalign; + force_ascii_slow(src, dst, unalign); + src += unalign; + dst += unalign; + len -= src_unalign; + } else { + force_ascii_slow(src, dst, len); + return; + } + } + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = ~0x8080808080808080ll; +#else + const uintptr_t mask = ~0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast(src); + uintptr_t* dstw = reinterpret_cast(dst); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + dstw[i] = srcw[i] & mask; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + force_ascii_slow(src + offset, dst + offset, remainder); + } +} + + +static size_t base64_encode(const char* src, + size_t slen, + char* dst, + size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= base64_encoded_size(slen) && + "not enough space provided for base64 encode"); + + dlen = base64_encoded_size(slen); + + unsigned a; + unsigned b; + unsigned c; + unsigned i; + unsigned k; + unsigned n; + + static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + i = 0; + k = 0; + n = slen / 3 * 3; + + while (i < n) { + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + c = src[i + 2] & 0xff; + + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; + dst[k + 3] = table[c & 0x3f]; + + i += 3; + k += 4; + } + + if (n != slen) { + switch (slen - n) { + case 1: + a = src[i + 0] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[(a & 3) << 4]; + dst[k + 2] = '='; + dst[k + 3] = '='; + break; + + case 2: + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[(b & 0x0f) << 2]; + dst[k + 3] = '='; + break; + } + } + + return dlen; +} + + +static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= slen * 2 && + "not enough space provided for hex encode"); + + dlen = slen * 2; + for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { + static const char hex[] = "0123456789abcdef"; + uint8_t val = static_cast(src[i]); + dst[k + 0] = hex[val >> 4]; + dst[k + 1] = hex[val & 15]; + } + + return dlen; +} + + + +static Local Encode(const char* buf, + size_t buflen, + enum Nan::Encoding encoding) { + assert(buflen <= node::Buffer::kMaxLength); + if (!buflen && encoding != Nan::BUFFER) + return NanNew(""); + + Local val; + switch (encoding) { + case Nan::BUFFER: + return NanNewBufferHandle(buf, buflen); + + case Nan::ASCII: + if (contains_non_ascii(buf, buflen)) { + char* out = new char[buflen]; + force_ascii(buf, out, buflen); + val = NanNew(out, buflen); + delete[] out; + } else { + val = NanNew(buf, buflen); + } + break; + + case Nan::UTF8: + val = NanNew(buf, buflen); + break; + + case Nan::BINARY: { + // TODO(isaacs) use ExternalTwoByteString? + const unsigned char *cbuf = reinterpret_cast(buf); + uint16_t * twobytebuf = new uint16_t[buflen]; + for (size_t i = 0; i < buflen; i++) { + // XXX is the following line platform independent? + twobytebuf[i] = cbuf[i]; + } + val = NanNew(twobytebuf, buflen); + delete[] twobytebuf; + break; + } + + case Nan::BASE64: { + size_t dlen = base64_encoded_size(buflen); + char* dst = new char[dlen]; + + size_t written = base64_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = NanNew(dst, dlen); + delete[] dst; + break; + } + + case Nan::UCS2: { + const uint16_t* data = reinterpret_cast(buf); + val = NanNew(data, buflen / 2); + break; + } + + case Nan::HEX: { + size_t dlen = buflen * 2; + char* dst = new char[dlen]; + size_t written = hex_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = NanNew(dst, dlen); + delete[] dst; + break; + } + + default: + assert(0 && "unknown encoding"); + break; + } + + return val; +} + +#undef base64_encoded_size + +} // namespace NanIntern + +#endif // NAN_STRING_BYTES_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json new file mode 100644 index 0000000..b69238b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json @@ -0,0 +1,90 @@ +{ + "name": "nan", + "version": "1.8.4", + "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", + "main": "include_dirs.js", + "repository": { + "type": "git", + "url": "git://github.com/iojs/nan.git" + }, + "scripts": { + "test": "tap --gc test/js/*-test.js", + "rebuild-tests": "pangyp rebuild --directory test" + }, + "contributors": [ + { + "name": "Rod Vagg", + "email": "r@va.gg", + "url": "https://github.com/rvagg" + }, + { + "name": "Benjamin Byholm", + "email": "bbyholm@abo.fi", + "url": "https://github.com/kkoopa/" + }, + { + "name": "Trevor Norris", + "email": "trev.norris@gmail.com", + "url": "https://github.com/trevnorris" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "https://github.com/TooTallNate" + }, + { + "name": "Brett Lawson", + "email": "brett19@gmail.com", + "url": "https://github.com/brett19" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl", + "url": "https://github.com/bnoordhuis" + }, + { + "name": "David Siegel", + "email": "david@artcom.de", + "url": "https://github.com/agnat" + } + ], + "devDependencies": { + "bindings": "~1.2.1", + "node-gyp": "~1.0.2", + "pangyp": "~2.0.1", + "tap": "~0.7.1", + "xtend": "~4.0.0" + }, + "license": "MIT", + "gitHead": "ed3bbf4ced0cf7937b4e4164766797f71aa97f3d", + "bugs": { + "url": "https://github.com/iojs/nan/issues" + }, + "homepage": "https://github.com/iojs/nan#readme", + "_id": "nan@1.8.4", + "_shasum": "3c76b5382eab33e44b758d2813ca9d92e9342f34", + "_from": "nan@>=1.8.0 <1.9.0", + "_npmVersion": "2.8.3", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "kkoopa", + "email": "bbyholm@abo.fi" + }, + "maintainers": [ + { + "name": "rvagg", + "email": "rod@vagg.org" + }, + { + "name": "kkoopa", + "email": "bbyholm@abo.fi" + } + ], + "dist": { + "shasum": "3c76b5382eab33e44b758d2813ca9d92e9342f34", + "tarball": "http://registry.npmjs.org/nan/-/nan-1.8.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/nan/-/nan-1.8.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json new file mode 100644 index 0000000..c3f0a8f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json @@ -0,0 +1,56 @@ +{ + "name": "kerberos", + "version": "0.0.12", + "description": "Kerberos library for Node.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/kerberos.git" + }, + "keywords": [ + "kerberos", + "security", + "authentication" + ], + "dependencies": { + "nan": "~1.8" + }, + "devDependencies": { + "nodeunit": "latest" + }, + "scripts": { + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "nodeunit ./test" + }, + "author": { + "name": "Christian Amor Kvalheim" + }, + "license": "Apache 2.0", + "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", + "bugs": { + "url": "https://github.com/christkv/kerberos/issues" + }, + "homepage": "https://github.com/christkv/kerberos", + "_id": "kerberos@0.0.12", + "_shasum": "7d25ccab74a2325c186b1a56761043a4789c8972", + "_from": "kerberos@>=0.0.0 <0.1.0", + "_npmVersion": "2.7.6", + "_nodeVersion": "1.7.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "7d25ccab74a2325c186b1a56761043a4789c8972", + "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.12.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.12.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js new file mode 100644 index 0000000..a06c5fd --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js @@ -0,0 +1,34 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Simple initialize of Kerberos object'] = function(test) { + var Kerberos = require('../lib/kerberos.js').Kerberos; + var kerberos = new Kerberos(); + // console.dir(kerberos) + + // Initiate kerberos client + kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { + console.log("===================================== authGSSClientInit") + test.equal(null, err); + test.ok(context != null && typeof context == 'object'); + // console.log("===================================== authGSSClientInit") + console.dir(err) + console.dir(context) + // console.dir(typeof result) + + // Perform the first step + kerberos.authGSSClientStep(context, function(err, result) { + console.log("===================================== authGSSClientStep") + console.dir(err) + console.dir(result) + console.dir(context) + + test.done(); + }); + }); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js new file mode 100644 index 0000000..d2f7046 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js @@ -0,0 +1,19 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Simple initialize of Kerberos win32 object'] = function(test) { + var KerberosNative = require('../build/Release/kerberos').Kerberos; + // console.dir(KerberosNative) + var kerberos = new KerberosNative(); + console.log("=========================================== 0") + console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); + console.log("=========================================== 1") + console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); + console.log("=========================================== 2") + test.done(); +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js new file mode 100644 index 0000000..3531b6b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js @@ -0,0 +1,41 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a security Buffer Descriptor'] = function(test) { + var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor + SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + + // Create descriptor with single Buffer + var securityDescriptor = new SecurityBufferDescriptor(100); + try { + // Fail to work due to no valid Security Buffer + securityDescriptor = new SecurityBufferDescriptor(["hello"]); + test.ok(false); + } catch(err){} + + // Should Correctly construct SecurityBuffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + securityDescriptor = new SecurityBufferDescriptor([buffer]); + // Should correctly return a buffer + var result = securityDescriptor.toBuffer(); + test.equal(100, result.length); + + // Should Correctly construct SecurityBuffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + securityDescriptor = new SecurityBufferDescriptor([buffer]); + var result = securityDescriptor.toBuffer(); + test.equal("hello world", result.toString()); + + // Test passing in more than one Buffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); + securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); + var result = securityDescriptor.toBuffer(); + test.equal("hello worldadam and eve", result.toString()); + test.done(); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js new file mode 100644 index 0000000..b52b959 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js @@ -0,0 +1,22 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a security Buffer'] = function(test) { + var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + // Create empty buffer + var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + var buffer = securityBuffer.toBuffer(); + test.equal(100, buffer.length); + + // Access data passed in + var allocated_buffer = new Buffer(256); + securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); + buffer = securityBuffer.toBuffer(); + test.deepEqual(allocated_buffer, buffer); + test.done(); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js new file mode 100644 index 0000000..7758180 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js @@ -0,0 +1,55 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a set of security credentials'] = function(test) { + var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; + + // Aquire some credentials + try { + var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); + } catch(err) { + console.dir(err) + test.ok(false); + } + + + + // console.dir(SecurityCredentials); + + // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor + // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + + // // Create descriptor with single Buffer + // var securityDescriptor = new SecurityBufferDescriptor(100); + // try { + // // Fail to work due to no valid Security Buffer + // securityDescriptor = new SecurityBufferDescriptor(["hello"]); + // test.ok(false); + // } catch(err){} + + // // Should Correctly construct SecurityBuffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + // securityDescriptor = new SecurityBufferDescriptor([buffer]); + // // Should correctly return a buffer + // var result = securityDescriptor.toBuffer(); + // test.equal(100, result.length); + + // // Should Correctly construct SecurityBuffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + // securityDescriptor = new SecurityBufferDescriptor([buffer]); + // var result = securityDescriptor.toBuffer(); + // test.equal("hello world", result.toString()); + + // // Test passing in more than one Buffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); + // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); + // var result = securityDescriptor.toBuffer(); + // test.equal("hello worldadam and eve", result.toString()); + test.done(); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..52926e1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json @@ -0,0 +1,65 @@ +{ + "name": "mongodb-core", + "version": "1.1.32", + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "main": "index.js", + "scripts": { + "test": "node test/runner.js -t functional" + }, + "repository": { + "type": "git", + "url": "git://github.com/christkv/mongodb-core.git" + }, + "keywords": [ + "mongodb", + "core" + ], + "dependencies": { + "bson": "~0.3", + "kerberos": "~0.0" + }, + "devDependencies": { + "integra": "0.1.8", + "optimist": "latest", + "jsdoc": "3.3.0-alpha8", + "semver": "4.1.0", + "gleak": "0.5.0", + "mongodb-tools": "~1.0", + "mkdirp": "0.5.0", + "rimraf": "2.2.6", + "mongodb-version-manager": "^0.5.0" + }, + "optionalDependencies": { + "kerberos": "~0.0" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/mongodb-core/issues" + }, + "homepage": "https://github.com/christkv/mongodb-core", + "gitHead": "9d487e6648eae1017aa597894da9e50006bd15d3", + "_id": "mongodb-core@1.1.32", + "_shasum": "f863549c08881ab2b382b8e878641b3e06fd76cc", + "_from": "mongodb-core@1.1.32", + "_npmVersion": "2.7.6", + "_nodeVersion": "1.7.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "f863549c08881ab2b382b8e878641b3e06fd76cc", + "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.1.32.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.1.32.tgz" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md new file mode 100644 index 0000000..34c1189 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; + + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; + + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} + +function emitReadable_(stream) { + stream.emit('readable'); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } + + function onend() { + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); + + state.flowing = true; + process.nextTick(function() { + flow(src); + }); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; +} + +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } + + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } + + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; + + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } + + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; +} + +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; + +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; + +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; + + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } + + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + process.nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + cb(er); + }); + else + cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..9074e8e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..b673333 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,37 @@ +{ + "name": "core-util-is", + "version": "1.0.1", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.1", + "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz", + "_from": "core-util-is@>=1.0.0 <1.1.0" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js new file mode 100644 index 0000000..007fa10 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && objectToString(e) === '[object Error]'; +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..933382a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,35 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "homepage": "https://github.com/isaacs/inherits#readme", + "_id": "inherits@2.0.1", + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "_from": "inherits@>=2.0.1 <2.1.0" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..fb1eb37 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,38 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "readme": "\n# isarray\n\n`Array#isArray` for older browsers.\n\n## Usage\n\n```js\nvar isArray = require('isarray');\n\nconsole.log(isArray([])); // => true\nconsole.log(isArray({})); // => false\n```\n\n## Installation\n\nWith [npm](http://npmjs.org) do\n\n```bash\n$ npm install isarray\n```\n\nThen bundle for the browser with\n[browserify](https://github.com/substack/browserify).\n\nWith [component](http://component.io) do\n\n```bash\n$ component install juliangruber/isarray\n```\n\n## License\n\n(MIT)\n\nCopyright (c) 2013 Julian Gruber <julian@juliangruber.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies 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 THE\nSOFTWARE.\n", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "_id": "isarray@0.0.1", + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "_from": "isarray@0.0.1" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..ee70702 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "readme": "**string_decoder.js** (`require('string_decoder')`) from Node.js core\n\nCopyright Joyent, Inc. and other Node contributors. See LICENCE file for details.\n\nVersion numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**\n\nThe *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.", + "readmeFilename": "README.md", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_from": "string_decoder@>=0.10.0 <0.11.0" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json new file mode 100644 index 0000000..2dc3a25 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json @@ -0,0 +1,69 @@ +{ + "name": "readable-stream", + "version": "1.0.31", + "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "devDependencies": { + "tap": "~0.2.6" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream", + "_id": "readable-stream@1.0.31", + "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "_from": "readable-stream@1.0.31", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..4d1ddfc --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js @@ -0,0 +1,6 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/mongoose/node_modules/mongodb/package.json b/node_modules/mongoose/node_modules/mongodb/package.json new file mode 100644 index 0000000..44c28af --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/package.json @@ -0,0 +1,64 @@ +{ + "name": "mongodb", + "version": "2.0.33", + "description": "MongoDB legacy driver emulation layer on top of mongodb-core", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "legacy" + ], + "dependencies": { + "mongodb-core": "1.1.32", + "readable-stream": "1.0.31" + }, + "devDependencies": { + "integra": "0.1.8", + "optimist": "0.6.1", + "bson": "~0.3", + "jsdoc": "3.3.0-beta3", + "semver": "4.1.0", + "rimraf": "2.2.6", + "gleak": "0.5.0", + "mongodb-version-manager": "^0.5.0", + "mongodb-tools": "~1.0" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "scripts": { + "test": "node test/runner.js -t functional" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "gitHead": "711c2564985232e04323f3fdc75ddfe329e19989", + "_id": "mongodb@2.0.33", + "_shasum": "0ff6918c003423f92ca76e85da1624080359f313", + "_from": "mongodb@2.0.33", + "_npmVersion": "2.7.6", + "_nodeVersion": "1.7.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "0ff6918c003423f92ca76e85da1624080359f313", + "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.0.33.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.0.33.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/mongodb/t.js b/node_modules/mongoose/node_modules/mongodb/t.js new file mode 100644 index 0000000..96c1f22 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/t.js @@ -0,0 +1,28 @@ +// var MongoClient = require('./').MongoClient; + +// function healthCheck(callback) { +// MongoClient.connect('mongodb://localhost:31000,localhost:31001,localhost:31002/test', function(err, db) { +// var r = err; + +// // setTimeout(function() { +// db.close(true, function(err, result) { +// callback(r); +// }); +// // }, 1000) +// }); +// } + +// function routine() { +// healthCheck(function(r) { +// console.log(r); +// }); + +// setTimeout(routine, 30000); +// } + +// routine(); + +MongoClient.connect('mongodb://ole:ole@localhost:27017/test', function(err, db) { + console.dir(err) + console.dir(db) +}); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/t1.js b/node_modules/mongoose/node_modules/mongodb/t1.js new file mode 100644 index 0000000..f93547f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/t1.js @@ -0,0 +1,59 @@ +var database = null; + +var MongoClient = require('./').MongoClient; + +function connect_to_mongo(callback) { + if (database != null) { + callback(null, database); + } else { + var connection = "mongodb://127.0.0.1:27017/test_db"; + MongoClient.connect(connection, { + server : { + reconnectTries : 5, + reconnectInterval: 1000, + autoReconnect : true + } + }, function (err, db) { + database = db; + callback(err, db); + }); + } +} + +function log(message) { + console.log(new Date(), message); +} + +var queryNumber = 0; + +function make_query(db) { + var currentNumber = queryNumber; + ++queryNumber; + log("query " + currentNumber + ": started"); + + setTimeout(function() { + make_query(db); + }, 5000); + + var collection = db.collection('test_collection'); + collection.findOne({}, + function (err, result) { + if (err != null) { + log("query " + currentNumber + ": find one error: " + err.message); + return; + } + log("query " + currentNumber + ": find one result: " + result); + } + ); +} + +connect_to_mongo( + function(err, db) { + if (err != null) { + log(err.message); + return; + } + + make_query(db); + } +); diff --git a/node_modules/mongoose/node_modules/mongodb/wercker.yml b/node_modules/mongoose/node_modules/mongodb/wercker.yml new file mode 100644 index 0000000..b64845f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/wercker.yml @@ -0,0 +1,19 @@ +box: wercker/nodejs +services: + - wercker/mongodb@1.0.1 +# Build definition +build: + # The steps that will be executed on build + steps: + # A step that executes `npm install` command + - npm-install + # A step that executes `npm test` command + - npm-test + + # A custom script step, name value is used in the UI + # and the code value contains the command that get executed + - script: + name: echo nodejs information + code: | + echo "node version $(node -v) running" + echo "npm version $(npm -v) running" diff --git a/node_modules/mongoose/node_modules/mpath/.npmignore b/node_modules/mongoose/node_modules/mpath/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/node_modules/mongoose/node_modules/mpath/.travis.yml b/node_modules/mongoose/node_modules/mpath/.travis.yml new file mode 100644 index 0000000..09c230f --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/mongoose/node_modules/mpath/History.md b/node_modules/mongoose/node_modules/mpath/History.md new file mode 100644 index 0000000..4fbf338 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/History.md @@ -0,0 +1,16 @@ + +0.1.1 / 2012-12-21 +================== + + * added; map support + +0.1.0 / 2012-12-13 +================== + + * added; set('array.property', val, object) support + * added; get('array.property', object) support + +0.0.1 / 2012-11-03 +================== + + * initial release diff --git a/node_modules/mongoose/node_modules/mpath/LICENSE b/node_modules/mongoose/node_modules/mpath/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.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. diff --git a/node_modules/mongoose/node_modules/mpath/Makefile b/node_modules/mongoose/node_modules/mpath/Makefile new file mode 100644 index 0000000..b0bb081 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/Makefile @@ -0,0 +1,5 @@ + +test: + @node_modules/mocha/bin/mocha -A $(T) + +.PHONY: test diff --git a/node_modules/mongoose/node_modules/mpath/README.md b/node_modules/mongoose/node_modules/mpath/README.md new file mode 100644 index 0000000..9831dd0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/README.md @@ -0,0 +1,278 @@ +#mpath + +{G,S}et javascript object values using MongoDB-like path notation. + +###Getting + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.1.title', obj) // 'exciting!' +``` + +`mpath.get` supports array property notation as well. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj) // ['funny', 'exciting!'] +``` + +Array property and indexing syntax, when used together, are very powerful. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +var found = mpath.get('array.o.array.x.b.1', obj); + +console.log(found); // prints.. + + [ [6, undefined] + , [2, undefined, undefined] + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + +``` + +#####Field selection rules: + +The following rules are iteratively applied to each `segment` in the passed `path`. For example: + +```js +var path = 'one.two.14'; // path +'one' // segment 0 +'two' // segment 1 +14 // segment 2 +``` + +- 1) when value of the segment parent is not an array, return the value of `parent.segment` +- 2) when value of the segment parent is an array + - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` + - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. + +#####Maps + +`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj, function (val) { + return 'funny' == val + ? 'amusing' + : val; +}); +// ['amusing', 'exciting!'] +``` + +###Setting + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.1.title', 'hilarious', obj) +console.log(obj.comments[1].title) // 'hilarious' +``` + +`mpath.set` supports the same array property notation as `mpath.get`. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +Array property and indexing syntax can be used together also when setting. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ] +} + +mpath.set('array.1.o', 'this was changed', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +mpath.set('array.o.array.x', 'this was changed too', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too', y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} +``` + +####Setting arrays + +By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: ['hilarious', 'fruity'] }, + { title: ['hilarious', 'fruity'] } + ]} +``` + +####Field assignment rules + +The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. + +#####Maps + +`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { + return val.length; +}); + +console.log(obj); // prints.. + + { comments: [ + { title: 9 }, + { title: 6 } + ]} +``` + +### Custom object types + +Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'exciting!', _doc: { title: 'great!' }} + ] +} + +mpath.get('comments.0.title', obj, '_doc') // 'great!' +mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') +mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' +mpath.get('comments.0.title', obj) // 'exciting' +``` + +When used with a `map`, the `map` argument comes last. + +```js +mpath.get(path, obj, '_doc', map); +mpath.set(path, val, obj, '_doc', map); +``` + +[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) + diff --git a/node_modules/mongoose/node_modules/mpath/index.js b/node_modules/mongoose/node_modules/mpath/index.js new file mode 100644 index 0000000..f7b65dd --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib'); diff --git a/node_modules/mongoose/node_modules/mpath/lib/index.js b/node_modules/mongoose/node_modules/mpath/lib/index.js new file mode 100644 index 0000000..24e1e83 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/lib/index.js @@ -0,0 +1,183 @@ + +/** + * Returns the value of object `o` at the given `path`. + * + * ####Example: + * + * var obj = { + * comments: [ + * { title: 'exciting!', _doc: { title: 'great!' }} + * , { title: 'number dos' } + * ] + * } + * + * mpath.get('comments.0.title', o) // 'exciting!' + * mpath.get('comments.0.title', o, '_doc') // 'great!' + * mpath.get('comments.title', o) // ['exciting!', 'number dos'] + * + * // summary + * mpath.get(path, o) + * mpath.get(path, o, special) + * mpath.get(path, o, map) + * mpath.get(path, o, special, map) + * + * @param {String} path + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. + */ + +exports.get = function (path, o, special, map) { + if ('function' == typeof special) { + map = special; + special = undefined; + } + + map || (map = K); + + var parts = 'string' == typeof path + ? path.split('.') + : path + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + var obj = o + , part; + + for (var i = 0; i < parts.length; ++i) { + part = parts[i]; + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + // reading a property from the array items + var paths = parts.slice(i); + + return obj.map(function (item) { + return item + ? exports.get(paths, item, special, map) + : map(undefined); + }); + } + + obj = special && obj[special] + ? obj[special][part] + : obj[part]; + + if (!obj) return map(obj); + } + + return map(obj); +} + +/** + * Sets the `val` at the given `path` of object `o`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. + + */ + +exports.set = function (path, val, o, special, map, _copying) { + if ('function' == typeof special) { + map = special; + special = undefined; + } + + map || (map = K); + + var parts = 'string' == typeof path + ? path.split('.') + : path + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + if (null == o) return; + + // the existance of $ in a path tells us if the user desires + // the copying of an array instead of setting each value of + // the array to the one by one to matching positions of the + // current array. + var copy = _copying || /\$/.test(path) + , obj = o + , part + + for (var i = 0, len = parts.length - 1; i < len; ++i) { + part = parts[i]; + + if ('$' == part) { + if (i == len - 1) { + break; + } else { + continue; + } + } + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + var paths = parts.slice(i); + if (!copy && Array.isArray(val)) { + for (var j = 0; j < obj.length && j < val.length; ++j) { + // assignment of single values of array + exports.set(paths, val[j], obj[j], special, map, copy); + } + } else { + for (var j = 0; j < obj.length; ++j) { + // assignment of entire value + exports.set(paths, val, obj[j], special, map, copy); + } + } + return; + } + + obj = special && obj[special] + ? obj[special][part] + : obj[part]; + + if (!obj) return; + } + + // process the last property of the path + + part = parts[len]; + + // use the special property if exists + if (special && obj[special]) { + obj = obj[special]; + } + + // set the value on the last branch + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + if (!copy && Array.isArray(val)) { + for (var item, j = 0; j < obj.length && j < val.length; ++j) { + item = obj[j]; + if (item) { + if (item[special]) item = item[special]; + item[part] = map(val[j]); + } + } + } else { + for (var j = 0; j < obj.length; ++j) { + item = obj[j]; + if (item) { + if (item[special]) item = item[special]; + item[part] = map(val); + } + } + } + } else { + obj[part] = map(val); + } +} + +/*! + * Returns the value passed to it. + */ + +function K (v) { + return v; +} diff --git a/node_modules/mongoose/node_modules/mpath/package.json b/node_modules/mongoose/node_modules/mpath/package.json new file mode 100644 index 0000000..7bc97d7 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/package.json @@ -0,0 +1,52 @@ +{ + "name": "mpath", + "version": "0.1.1", + "description": "{G,S}et object values using MongoDB path notation", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mpath.git" + }, + "keywords": [ + "mongodb", + "path", + "get", + "set" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.6.0" + }, + "_id": "mpath@0.1.1", + "dist": { + "shasum": "23da852b7c232ee097f4759d29c0ee9cd22d5e46", + "tarball": "http://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz" + }, + "_npmVersion": "1.1.59", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "23da852b7c232ee097f4759d29c0ee9cd22d5e46", + "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz", + "_from": "mpath@0.1.1", + "bugs": { + "url": "https://github.com/aheckmann/mpath/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/aheckmann/mpath" +} diff --git a/node_modules/mongoose/node_modules/mpath/test/index.js b/node_modules/mongoose/node_modules/mpath/test/index.js new file mode 100644 index 0000000..98e119a --- /dev/null +++ b/node_modules/mongoose/node_modules/mpath/test/index.js @@ -0,0 +1,1630 @@ + +/** + * Test dependencies. + */ + +var mpath = require('../') +var assert = require('assert') + +/** + * logging helper + */ + +function log (o) { + console.log(); + console.log(require('util').inspect(o, false, 1000)); +} + +/** + * special path for override tests + */ + +var special = '_doc'; + +/** + * Tests + */ + +describe('mpath', function(){ + + /** + * test doc creator + */ + + function doc () { + var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; + o.comments = [ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + o.arr = [ + { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ] + return o; + } + + describe('get', function(){ + var o = doc(); + + it('`path` must be a string or array', function(done){ + assert.throws(function () { + mpath.get({}, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(4, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(function(){}, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(/asdf/, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(Math, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(Buffer, o); + }, /Must be either string or array/); + assert.doesNotThrow(function () { + mpath.get('string', o); + }); + assert.doesNotThrow(function () { + mpath.get([], o); + }); + done(); + }) + + describe('without `special`', function(){ + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); + assert.deepEqual('one', mpath.get('comments.0.name', o)); + assert.deepEqual('two', mpath.get('comments.1.name', o)); + assert.deepEqual('three', mpath.get('comments.2.name', o)); + + assert.deepEqual([{},{ comments: [{val: 'twoo'}]}] + , mpath.get('comments.2.comments', o)); + + assert.deepEqual({ comments: [{val: 'twoo'}]} + , mpath.get('comments.2.comments.1', o)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); + + done(); + }) + + it('handles array.property dot-notation', function(done){ + assert.deepEqual( + ['one', 'two', 'three'] + , mpath.get('comments.name', o) + ); + done(); + }) + + it('handles array.array notation', function(done){ + assert.deepEqual( + [undefined, undefined, [{}, {comments:[{val:'twoo'}]}]] + , mpath.get('comments.comments', o) + ); + done(); + }) + + it('handles prop.prop.prop.arrayProperty notation', function(done){ + assert.deepEqual( + [undefined, 'aaron', undefined] + , mpath.get('first.second.third.name', o) + ); + assert.deepEqual( + [1, 'aaron', 1] + , mpath.get('first.second.third.name', o, function (v) { + return undefined === v ? 1 : v; + }) + ); + done(); + }) + + it('handles array.prop.array', function(done){ + assert.deepEqual( + [ [{x: {b: [4,6,8]}}, { y: 10} ] + , [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] + , [{x: {b: null }}, { x: { b: [null, 1]}}] + , [{x: null }] + , [{y: 3 }] + , [3, 0, null] + , undefined + ] + , mpath.get('array.o.array', o) + ); + done(); + }) + + it('handles array.prop.array.index', function(done){ + assert.deepEqual( + [ {x: {b: [4,6,8]}} + , {x: {b: [1,2,3]}} + , {x: {b: null }} + , {x: null } + , {y: 3 } + , 3 + , undefined + ] + , mpath.get('array.o.array.0', o) + ); + done(); + }) + + it('handles array.prop.array.index.prop', function(done){ + assert.deepEqual( + [ {b: [4,6,8]} + , {b: [1,2,3]} + , {b: null } + , null + , undefined + , undefined + , undefined + ] + , mpath.get('array.o.array.0.x', o) + ); + done(); + }) + + it('handles array.prop.array.prop', function(done){ + assert.deepEqual( + [ [undefined, 10 ] + , [undefined, undefined, undefined] + , [undefined, undefined] + , [undefined] + , [3] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.y', o) + ); + assert.deepEqual( + [ [{b: [4,6,8]}, undefined] + , [{b: [1,2,3]}, {z: 10 }, {b: 'hi'}] + , [{b: null }, { b: [null, 1]}] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x', o) + ); + done(); + }) + + it('handles array.prop.array.prop.prop', function(done){ + assert.deepEqual( + [ [[4,6,8], undefined] + , [[1,2,3], undefined, 'hi'] + , [null, [null, 1]] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x.b', o) + ); + done(); + }) + + it('handles array.prop.array.prop.prop.index', function(done){ + assert.deepEqual( + [ [6, undefined] + , [2, undefined, 'i'] // undocumented feature (string indexing) + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x.b.1', o) + ); + assert.deepEqual( + [ [6, 0] + , [2, 0, 'i'] // undocumented feature (string indexing) + , [null, 1] + , [null] + , [0] + , [0, 0, 0] + , 0 + ] + , mpath.get('array.o.array.x.b.1', o, function (v) { + return undefined === v ? 0 : v; + }) + ); + done(); + }) + + it('handles array.index.prop.prop', function(done){ + assert.deepEqual( + [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] + , mpath.get('array.1.o.array', o) + ); + assert.deepEqual( + ['hi','hi','hi'] + , mpath.get('array.1.o.array', o, function (v) { + if (Array.isArray(v)) { + return v.map(function (val) { + return 'hi'; + }) + } + return v; + }) + ); + done(); + }) + + it('handles array.array.index', function(done){ + assert.deepEqual( + [{ a: { c: 48 }}, undefined] + , mpath.get('arr.arr.1', o) + ); + assert.deepEqual( + ['woot', undefined] + , mpath.get('arr.arr.1', o, function (v) { + if (v && v.a && v.a.c) return 'woot'; + return v; + }) + ); + done(); + }) + + it('handles array.array.index.prop', function(done){ + assert.deepEqual( + [{ c: 48 }, 'woot'] + , mpath.get('arr.arr.1.a', o, function (v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + assert.deepEqual( + [{ c: 48 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{c:49},undefined], o) + assert.deepEqual( + [{ c: 49 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{c:48},undefined], o) + done(); + }) + + it('handles array.array.index.prop.prop', function(done){ + assert.deepEqual( + [48, undefined] + , mpath.get('arr.arr.1.a.c', o) + ); + assert.deepEqual( + [48, 'woot'] + , mpath.get('arr.arr.1.a.c', o, function (v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + done(); + }) + + }) + + describe('with `special`', function(){ + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function (v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('2', mpath.get('comments.1.name', o, special)); + assert.deepEqual('3', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { + return '3' === v ? 'nice' : v; + })); + + assert.deepEqual([{},{ _doc: { comments: [{ val: 2 }] }}] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ _doc: { comments: [{val: 2}]}} + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); + done(); + }) + + it('handles array.property dot-notation', function(done){ + assert.deepEqual( + ['one', '2', '3'] + , mpath.get('comments.name', o, special) + ); + assert.deepEqual( + ['one', 2, '3'] + , mpath.get('comments.name', o, special, function (v) { + return '2' === v ? 2 : v + }) + ); + done(); + }) + + it('handles array.array notation', function(done){ + assert.deepEqual( + [undefined, undefined, [{}, {_doc: { comments:[{val:2}]}}]] + , mpath.get('comments.comments', o, special) + ); + done(); + }) + + it('handles array.array.index.array', function(done){ + assert.deepEqual( + [undefined, undefined, [{val:2}]] + , mpath.get('comments.comments.1.comments', o, special) + ); + done(); + }) + + it('handles array.array.index.array.prop', function(done){ + assert.deepEqual( + [undefined, undefined, [2]] + , mpath.get('comments.comments.1.comments.val', o, special) + ); + assert.deepEqual( + ['nil', 'nil', [2]] + , mpath.get('comments.comments.1.comments.val', o, special, function (v) { + return undefined === v ? 'nil' : v; + }) + ); + done(); + }) + }) + + }) + + describe('set', function(){ + describe('without `special`', function(){ + var o = doc(); + + it('works', function(done){ + mpath.set('name', 'a new val', o, function (v) { + return 'a new val' === v ? 'changed' : v; + }); + assert.deepEqual('changed', o.name); + + mpath.set('name', 'changed', o); + assert.deepEqual('changed', o.name); + + mpath.set('first.second.third', [1,{name:'x'},9], o); + assert.deepEqual([1,{name:'x'},9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'y', o) + assert.deepEqual([1,{name:'y'},9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o); + assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' }}, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); + assert.deepEqual( + { val: 'twoo', expand: 'added'} + , o.comments[2].comments[1].comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'added', o); + assert.equal(3, o.comments[2].comments[1].comments.length); + assert.deepEqual( + { val: 'twoo', expand: 'added'} + , o.comments[2].comments[1].comments[0]); + assert.deepEqual( + undefined + , o.comments[2].comments[1].comments[1]); + assert.deepEqual( + 'added' + , o.comments[2].comments[1].comments[2]); + + done(); + }) + + describe('array.path', function(){ + describe('with single non-array value', function(){ + it('works', function(done){ + mpath.set('arr.yep', false, o, function (v) { + return false === v ? true: v; + }); + assert.deepEqual([ + { yep: true, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ], o.arr); + + mpath.set('arr.yep', false, o); + + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: false } + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('that are equal in length', function(done){ + mpath.set('arr.yep', ['one',2], o, function (v) { + return 'one' === v ? 1 : v; + }); + assert.deepEqual([ + { yep: 1, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + mpath.set('arr.yep', ['one',2], o); + + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + done(); + }) + + it('that is less than length', function(done){ + mpath.set('arr.yep', [47], o, function (v) { + return 47 === v ? 4 : v; + }); + assert.deepEqual([ + { yep: 4, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + mpath.set('arr.yep', [47], o); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + done(); + }) + + it('that is greater than length', function(done){ + mpath.set('arr.yep', [5,6,7], o, function (v) { + return 5 === v ? 'five' : v; + }); + assert.deepEqual([ + { yep: 'five', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 6 } + ], o.arr); + + mpath.set('arr.yep', [5,6,7], o); + assert.deepEqual([ + { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 6 } + ], o.arr); + + done(); + }) + }) + }) + + describe('array.$.path', function(){ + describe('with single non-array value', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', {xtra: 'double good'}, o, function (v) { + return v && v.xtra ? 'hi' : v; + }); + assert.deepEqual([ + { yep: 'hi', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 'hi'} + ], o.arr); + + mpath.set('arr.$.yep', {xtra: 'double good'}, o); + assert.deepEqual([ + { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: {xtra:'double good'}} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', [15], o, function (v) { + return v.length === 1 ? [] : v; + }); + assert.deepEqual([ + { yep: [], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: []} + ], o.arr); + + mpath.set('arr.$.yep', [15], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: [15]} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.index.path', function(){ + it('works', function(done){ + mpath.set('arr.1.yep', 0, o, function (v) { + return 0 === v ? 'zero' : v; + }); + assert.deepEqual([ + { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 'zero' } + ], o.arr); + + mpath.set('arr.1.yep', 0, o); + assert.deepEqual([ + { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.e', 35, o, function (v) { + return 35 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 3}, { a: { c: 48 }, e: 3}, { d: 'yep', e: 3 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.e', ['a','b'], o, function (v) { + return 'a' === v ? 'x' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'x'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', ['a','b'], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.a.b', 36, o, function (v) { + return 36 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 3 }, e: 'a'}, { a: { c: 48, b: 3 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, function (v) { + return 2 === v ? 'two' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 'two' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1,2,3,4], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.$.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.$.a.b', '$', o, function (v) { + return '$' === v ? 'dolla billz' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a'}, { a: { c: 48, b: 'dolla billz' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.$.a.b', [1], o, function (v) { + return Array.isArray(v) ? {} : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.array.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.0.a', 'single', o, function (v) { + return 'single' === v ? 'double' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'double', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, function (v) { + return 4 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 3, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: false } + ], o.arr); + + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: false } + ], o.arr); + + done(); + }) + }) + + describe('array.array.$.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.$.0.a', 'singles', o, function (v) { + return 0; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 0, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, function (v) { + return 'nope' + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'nope', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + done(); + }) + }) + + describe('array.array.path.index', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.a.7', 47, o, function (v) { + return 1 + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,1], e: 'a'}, { a: { c: 48, b: [1], '7': 1 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + done(); + }) + it('with array', function(done){ + o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o); + + var a1 = []; + var a2 = []; + a1[7] = undefined; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0, arr: [{a:a1},{a:a2},{a:null}] } + ], o.arr); + + done(); + }) + }) + + describe('handles array.array.path', function(){ + it('with single', function(done){ + o.arr[1].arr = [{},{}]; + assert.deepEqual([{},{}], o.arr[1].arr); + o.arr.push({ arr: 'something else' }); + o.arr.push({ arr: ['something else'] }); + o.arr.push({ arr: [[]] }); + o.arr.push({ arr: [5] }); + + var weird = []; + weird.e = 'xmas'; + + // test + mpath.set('arr.arr.e', 47, o, function (v) { + return 'xmas' + }); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 'xmas'} + , { a: { c: 48, b: [1], '7': 46 }, e: 'xmas'} + , { d: 'yep', e: 'xmas' } + ] + } + , { yep: 0, arr: [{e: 'xmas'}, {e:'xmas'}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + weird.e = 47; + + mpath.set('arr.arr.e', 47, o); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 47} + , { a: { c: 48, b: [1], '7': 46 }, e: 47} + , { d: 'yep', e: 47 } + ] + } + , { yep: 0, arr: [{e: 47}, {e:47}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + done(); + }) + it('with arrays', function(done){ + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, function (v) { + return 10; + }); + + var weird = []; + weird.e = 10; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 10} + , { a: { c: 48, b: [1], '7': 46 }, e: 10} + , { d: 'yep', e: 10 } + ] + } + , { yep: 0, arr: [{e: 10}, {e:10}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o); + + weird.e = 6; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 1} + , { a: { c: 48, b: [1], '7': 46 }, e: 2} + , { d: 'yep', e: 3 } + ] + } + , { yep: 0, arr: [{e: 4}, {e:5}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + done(); + }) + }) + }) + + describe('with `special`', function(){ + var o = doc(); + + it('works', function(done){ + mpath.set('name', 'chan', o, special, function (v) { + return 'hi'; + }); + assert.deepEqual('hi', o.name); + + mpath.set('name', 'changer', o, special); + assert.deepEqual('changer', o.name); + + mpath.set('first.second.third', [1,{name:'y'},9], o, special); + assert.deepEqual([1,{name:'y'},9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'z', o, special) + assert.deepEqual([1,{name:'z'},9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o, special); + assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' }}, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function (v) { + return 'super' + }); + assert.deepEqual( + { val: 2, expander: 'super'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); + assert.deepEqual( + { val: 2, expander: 'adder'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'set', o, special); + assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); + assert.deepEqual( + { val: 2, expander: 'adder'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + assert.deepEqual( + undefined + , o.comments[2]._doc.comments[1]._doc.comments[1]); + assert.deepEqual( + 'set' + , o.comments[2]._doc.comments[1]._doc.comments[2]); + done(); + }) + + describe('array.path', function(){ + describe('with single non-array value', function(){ + it('works', function(done){ + o.arr[1]._doc = { special: true } + + mpath.set('arr.yep', false, o, special, function (v) { + return 'yes'; + }); + assert.deepEqual([ + { yep: 'yes', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 'yes'}} + ], o.arr); + + mpath.set('arr.yep', false, o, special); + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: false }} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('that are equal in length', function(done){ + mpath.set('arr.yep', ['one',2], o, special, function (v) { + return 2 === v ? 20 : v; + }); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 20}} + ], o.arr); + + mpath.set('arr.yep', ['one',2], o, special); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + done(); + }) + + it('that is less than length', function(done){ + mpath.set('arr.yep', [47], o, special, function (v) { + return 80; + }); + assert.deepEqual([ + { yep: 80, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + mpath.set('arr.yep', [47], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + // add _doc to first element + o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + + mpath.set('arr.yep', [20], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + done(); + }) + + it('that is greater than length', function(done){ + mpath.set('arr.yep', [5,6,7], o, special, function () { + return 'x'; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 'x'}} + ], o.arr); + + mpath.set('arr.yep', [5,6,7], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 6}} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.$.path', function(){ + describe('with single non-array value', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', {xtra: 'double good'}, o, special, function (v) { + return 9; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: 9, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 9}} + ], o.arr); + + mpath.set('arr.$.yep', {xtra: 'double good'}, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: {xtra:'double good'}}} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', [15], o, special, function (v) { + return 'array' + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: 'array', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 'array'}} + ], o.arr); + + mpath.set('arr.$.yep', [15], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: [15]}} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.index.path', function(){ + it('works', function(done){ + mpath.set('arr.1.yep', 0, o, special, function (v) { + return 1; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 1}} + ], o.arr); + + mpath.set('arr.1.yep', 0, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.e', 35, o, special, function (v) { + return 30 + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30}, { a: { c: 48 }, e: 30}, { d: 'yep', e: 30 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.e', ['a','b'], o, special, function (v) { + return 'a' === v ? 'A' : v; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.e', ['a','b'], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.a.b', 36, o, special, function (v) { + return 20 + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a'}, { a: { c: 48, b: 20 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special, function (v) { + return v*2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a'}, { a: { c: 48, b: 4 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.$.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.$.a.b', '$', o, special, function (v) { + return 'dollaz' + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a'}, { a: { c: 48, b: 'dollaz' }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.$.a.b', [1], o, special, function (v) { + return {}; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.0.a', 'single', o, special, function (v) { + return 88; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 88, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special, function (v) { + return v*2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 8, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.$.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.$.0.a', 'singles', o, special, function (v) { + return v.toUpperCase(); + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special, function (v) { + return Array + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: Array, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.path.index', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.a.7', 47, o, special, function (v) { + return Object; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,Object], e: 'a'}, { a: { c: 48, b: [1], '7': Object }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special, function (v) { + return undefined === v ? 'nope' : v; + }); + + var a1 = []; + var a2 = []; + a1[7] = 'nope'; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special); + + a1[7] = undefined; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('handles array.array.path', function(){ + it('with single', function(done){ + o.arr[1]._doc.arr = [{},{}]; + assert.deepEqual([{},{}], o.arr[1]._doc.arr); + o.arr.push({ _doc: { arr: 'something else' }}); + o.arr.push({ _doc: { arr: ['something else'] }}); + o.arr.push({ _doc: { arr: [[]] }}); + o.arr.push({ _doc: { arr: [5] }}); + + // test + mpath.set('arr.arr.e', 47, o, special); + + var weird = []; + weird.e = 47; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { + yep: [15] + , arr: [ + { a: [4,8,15,16,23,42,108,null], e: 47} + , { a: { c: 48, b: [1], '7': 46 }, e: 47} + , { d: 'yep', e: 47 } + ] + } + } + , { yep: true + , _doc: { + arr: [ + {e:47} + , {e:47} + ] + , special: true + , yep: 0 + } + } + , { _doc: { arr: 'something else' }} + , { _doc: { arr: ['something else'] }} + , { _doc: { arr: [weird] }} + , { _doc: { arr: [5] }} + ] + , o.arr); + + done(); + }) + it('with arrays', function(done){ + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, special); + + var weird = []; + weird.e = 6; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { + yep: [15] + , arr: [ + { a: [4,8,15,16,23,42,108,null], e: 1} + , { a: { c: 48, b: [1], '7': 46 }, e: 2} + , { d: 'yep', e: 3 } + ] + } + } + , { yep: true + , _doc: { + arr: [ + {e:4} + , {e:5} + ] + , special: true + , yep: 0 + } + } + , { _doc: { arr: 'something else' }} + , { _doc: { arr: ['something else'] }} + , { _doc: { arr: [weird] }} + , { _doc: { arr: [5] }} + ] + , o.arr); + + done(); + }) + }) + + }) + + describe('get/set integration', function(){ + var o = doc(); + + it('works', function(done){ + var vals = mpath.get('array.o.array.x.b', o); + + vals[0][0][2] = 10; + vals[1][0][1] = 0; + vals[1][1] = 'Rambaldi'; + vals[1][2] = [12,14]; + vals[2] = [{changed:true}, [null, ['changed','to','array']]]; + + mpath.set('array.o.array.x.b', vals, o); + + var t = [ + { o: { array: [{x: {b: [4,6,10]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,0,3]}}, { x: {b:'Rambaldi',z: 10 }}, { x: {b: [12,14]}}] }} + , { o: { array: [{x: {b: {changed:true}}}, { x: { b: [null, ['changed','to','array']]}}]}} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + assert.deepEqual(t, o.array); + done(); + }) + + it('array.prop', function(done){ + mpath.set('comments.name', ['this', 'was', 'changed'], o); + + assert.deepEqual([ + { name: 'this' } + , { name: 'was', _doc: { name: '2' }} + , { name: 'changed' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ], o.comments); + + mpath.set('comments.name', ['also', 'changed', 'this'], o, special); + + assert.deepEqual([ + { name: 'also' } + , { name: 'was', _doc: { name: 'changed' }} + , { name: 'changed' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: 'this', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ], o.comments); + + done(); + }) + + }) + + describe('multiple $ use', function(){ + var o = doc(); + it('is ok', function(done){ + assert.doesNotThrow(function () { + mpath.set('arr.$.arr.$.a', 35, o); + }); + done(); + }) + }) + + it('ignores setting a nested path that doesnt exist', function(done){ + var o = doc(); + assert.doesNotThrow(function(){ + mpath.set('thing.that.is.new', 10, o); + }) + done(); + }) + }) + +}) diff --git a/node_modules/mongoose/node_modules/mpromise/.npmignore b/node_modules/mongoose/node_modules/mpromise/.npmignore new file mode 100644 index 0000000..e86496f --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/.npmignore @@ -0,0 +1,4 @@ +*.sw* +node_modules/ +.DS_Store +.idea \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpromise/.travis.yml b/node_modules/mongoose/node_modules/mpromise/.travis.yml new file mode 100644 index 0000000..d63ba09 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 diff --git a/node_modules/mongoose/node_modules/mpromise/History.md b/node_modules/mongoose/node_modules/mpromise/History.md new file mode 100644 index 0000000..a64788e --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/History.md @@ -0,0 +1,74 @@ +0.5.1 / 2014-01-20 +================== + + * fixed; `end` is much more consistent (especially for `then` chains) + +0.4.4 / 2014-01-20 +================== + + * fixed; `end` is much more consistent (especially for `then` chains) + +0.4.3 / 2013-12-17 +================== + + * fixed; non-A+ behavior on fulfill and reject [lbeschastny](https://github.com/lbeschastny) + * tests; simplified harness + compatible with travis + compatible with windows + +0.5.0 / 2013-12-14 +================== + + * fixed; non-A+ behavior on fulfill and reject [lbeschastny](https://github.com/lbeschastny) + * tests; simplified harness + compatible with travis + compatible with windows + +0.4.2 / 2013-11-26 +================== + + * fixed; enter the domain only if not the present domain + * added; `end` returns the promise + +0.4.1 / 2013-10-26 +================== + + * Add `all` + * Longjohn for easier debugging + * can end a promise chain with an error handler + * Add ```chain``` + +0.4.0 / 2013-10-24 +================== + + * fixed; now plays nice with domains #3 [refack](https://github.com/refack) + * updated; compatibility for Promises A+ 2.0.0 [refack](https://github.com/refack) + * updated; guard against invalid arguments [refack](https://github.com/refack) + +0.3.0 / 2013-07-25 +================== + + * updated; sliced to 0.0.5 + * fixed; then is passed all fulfillment values + * use setImmediate if available + * conform to Promises A+ 1.1 + +0.2.1 / 2013-02-09 +================== + + * fixed; conformancy with A+ 1.2 + +0.2.0 / 2013-01-09 +================== + + * added; .end() + * fixed; only catch handler executions + +0.1.0 / 2013-01-08 +================== + + * cleaned up API + * customizable event names + * docs + +0.0.1 / 2013-01-07 +================== + + * original release + diff --git a/node_modules/mongoose/node_modules/mpromise/LICENSE b/node_modules/mongoose/node_modules/mpromise/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.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. diff --git a/node_modules/mongoose/node_modules/mpromise/README.md b/node_modules/mongoose/node_modules/mpromise/README.md new file mode 100644 index 0000000..2906f56 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/README.md @@ -0,0 +1,224 @@ +#mpromise +========== + +[![Build Status](https://travis-ci.org/aheckmann/mpromise.png)](https://travis-ci.org/aheckmann/mpromise) + +A [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com). + +## installation + +``` +$ npm install mpromise +``` + +## docs + +An `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed. + +The exports object is the Promise constructor. + +```js +var Promise = require('mpromise'); +``` + +The constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected). + +```js +var promise = new Promise(fn); +``` + +This is the same as passing the `fn` to `onResolve` directly. + +```js +var promise = new Promise; +promise.onResolve(function (err, args..) { + ... +}); +``` + +### Methods + +####fulfill + +Fulfilling a promise with values: + +```js +var promise = new Promise; +promise.fulfill(args...); +``` + +If the promise has already been fulfilled or rejected, no action is taken. + +####reject + +Rejecting a promise with a reason: + +```js +var promise = new Promise; +promise.reject(reason); +``` + +If the promise has already been fulfilled or rejected, no action is taken. + +####resolve + +Node.js callback style promise resolution `(err, args...)`: + +```js +var promise = new Promise; +promise.resolve([reason], [arg1, arg2, ...]); +``` + +If the promise has already been fulfilled or rejected, no action is taken. + +####onFulfill + +To register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`. + +```js +var promise = new Promise; +promise.onFulfill(function (a, b) { + assert.equal(3, a + b); +}); +promise.fulfill(1, 2); +``` + +The function will only be called once when the promise is fulfilled, never when rejected. + +Registering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise. + +```js +var promise = new Promise; +promise.fulfill(" :D "); +promise.onFulfill(function (arg) { + console.log(arg); // logs " :D " +}) +``` + +####onReject + +To register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`. + +```js +var promise = new Promise; +promise.onReject(function (reason) { + assert.equal('sad', reason); +}); +promise.reject('sad'); +``` + +The function will only be called once when the promise is rejected, never when fulfilled. + +Registering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise. + +```js +var promise = new Promise; +promise.reject(" :( "); +promise.onReject(function (reason) { + console.log(reason); // logs " :( " +}) +``` + +####onResolve + +Allows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject). + +```js +// fulfillment +var promise = new Promise; +promise.onResolve(function (err, a, b) { + console.log(a + b); // logs 3 +}); +promise.fulfill(1, 2); + +// rejection +var promise = new Promise; +promise.onResolve(function (err) { + if (err) { + console.log(err.message); // logs "failed" + } +}); +promise.reject(new Error('failed')); +``` + +####then + +Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick. + +Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests). + +```js +// promise.then(onFulfill, onReject); + +var p = new Promise; + +p.then(function (arg) { + return arg + 1; +}).then(function (arg) { + throw new Error(arg + ' is an error!'); +}).then(null, function (err) { + assert.ok(err instanceof Error); + assert.equal('2 is an error', err.message); +}); +p.fullfill(1); +``` + +####end + +Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception be rethrown. +You can pass an OnReject handler to `end` so that exceptions will be handled (like a final catch clause); +This method returns it's promise for easy use with `return`. + +```js +var p = new Promise; +p.then(function(){ throw new Error('shucks') }); +setTimeout(function () { + p.fulfill(); + // error was caught and swallowed by the promise returned from + // p.then(). we either have to always register handlers on + // the returned promises or we can do the following... +}, 10); + +// this time we use .end() which prevents catching thrown errors +var p = new Promise; +setTimeout(function () { + p.fulfill(); // throws "shucks" +}, 10); +return p.then(function(){ throw new Error('shucks') }).end(); // <-- +``` + + +### chain + +Allows direct promise to promise chaining (especially useful by a outside aggregating function). It doesn't use the asynchronous `resolve` algorithm and so excepts only another Promise as it's argument. + +```js +function makeMeAPromise(i) { + var p = new Promise; + p.fulfill(i); + return p; +} + +var returnPromise = initialPromise = new Promise; +for (i=0; i<10; ++i) + returnPromise = returnPromise.chain(makeMeAPromise(i)); + +initialPromise.fulfill(); +return returnPromise; +``` + +###Event names + +If you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively. + +```js +Promise.SUCCESS = 'complete'; +Promise.FAILURE = 'err'; +``` + +###Luke, use the Source +For more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js). + +## license + +[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE) diff --git a/node_modules/mongoose/node_modules/mpromise/lib/promise.js b/node_modules/mongoose/node_modules/mpromise/lib/promise.js new file mode 100644 index 0000000..ff2768f --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/lib/promise.js @@ -0,0 +1,440 @@ +'use strict'; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +function toArray(arr, start, end) { + return Array.prototype.slice.call(arr, start, end) +} +function strongUnshift(x, arrLike) { + var arr = toArray(arrLike); + arr.unshift(x); + return arr; +} + + +/** + * Promise constructor. + * + * _NOTE: The success and failure event names can be overridden by setting `Promise.SUCCESS` and `Promise.FAILURE` respectively._ + * + * @param {Function} back a function that accepts `fn(err, ...){}` as signature + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `reject`: Emits when the promise is rejected (event name may be overridden) + * @event `fulfill`: Emits when the promise is fulfilled (event name may be overridden) + * @api public + */ +function Promise(back) { + this.emitter = new EventEmitter(); + this.emitted = {}; + this.ended = false; + if ('function' == typeof back) + this.onResolve(back); +} + + +/* + * Module exports. + */ +module.exports = Promise; + + +/*! + * event names + */ +Promise.SUCCESS = 'fulfill'; +Promise.FAILURE = 'reject'; + + +/** + * Adds `listener` to the `event`. + * + * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event. + * + * @param {String} event + * @param {Function} callback + * @return {Promise} this + * @api private + */ +Promise.prototype.on = function (event, callback) { + if (this.emitted[event]) + callback.apply(undefined, this.emitted[event]); + else + this.emitter.on(event, callback); + + return this; +}; + + +/** + * Keeps track of emitted events to run them on `on`. + * + * @api private + */ +Promise.prototype.safeEmit = function (event) { + // ensures a promise can't be fulfill() or reject() more than once + if (event == Promise.SUCCESS || event == Promise.FAILURE) { + if (this.emitted[Promise.SUCCESS] || this.emitted[Promise.FAILURE]) { + return this; + } + this.emitted[event] = toArray(arguments, 1); + } + + this.emitter.emit.apply(this.emitter, arguments); + return this; +}; + + +/** + * Fulfills this promise with passed arguments. + * + * If this promise has already been fulfilled or rejected, no action is taken. + * + * @api public + */ +Promise.prototype.fulfill = function () { + return this.safeEmit.apply(this, strongUnshift(Promise.SUCCESS, arguments)); +}; + + +/** + * Rejects this promise with `reason`. + * + * If this promise has already been fulfilled or rejected, no action is taken. + * + * @api public + * @param {Object|String} reason + * @return {Promise} this + */ +Promise.prototype.reject = function (reason) { + if (this.ended && !this.hasRejectListeners()) throw reason; + return this.safeEmit(Promise.FAILURE, reason); +}; + + +/** + * Resolves this promise to a rejected state if `err` is passed or + * fulfilled state if no `err` is passed. + * + * @param {Error} [err] error or null + * @param {Object} [val] value to fulfill the promise with + * @api public + */ +Promise.prototype.resolve = function (err, val) { + if (err) return this.reject(err); + return this.fulfill(val); +}; + + +/** + * Adds a listener to the SUCCESS event. + * + * @return {Promise} this + * @api public + */ +Promise.prototype.onFulfill = function (fn) { + if (!fn) return this; + if ('function' != typeof fn) throw new TypeError("fn should be a function"); + return this.on(Promise.SUCCESS, fn); +}; + + +Promise.prototype.hasRejectListeners = function () { + return this.emitter.listeners(Promise.FAILURE).length > 0; +}; + + +/** + * Adds a listener to the FAILURE event. + * + * @return {Promise} this + * @api public + */ +Promise.prototype.onReject = function (fn) { + if (!fn) return this; + if ('function' != typeof fn) throw new TypeError("fn should be a function"); + return this.on(Promise.FAILURE, fn); +}; + + +/** + * Adds a single function as a listener to both SUCCESS and FAILURE. + * + * It will be executed with traditional node.js argument position: + * function (err, args...) {} + * + * Also marks the promise as `end`ed, since it's the common use-case, and yet has no + * side effects unless `fn` is undefined or null. + * + * @param {Function} fn + * @return {Promise} this + */ +Promise.prototype.onResolve = function (fn) { + this.end(); + if (!fn) return this; + if ('function' != typeof fn) throw new TypeError("fn should be a function"); + this.on(Promise.FAILURE, function (err) { fn.call(this, err); }); + this.on(Promise.SUCCESS, function () { fn.apply(this, strongUnshift(null, arguments)); }); + return this; +}; + + +/** + * Creates a new promise and returns it. If `onFulfill` or + * `onReject` are passed, they are added as SUCCESS/ERROR callbacks + * to this promise after the next tick. + * + * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. Read for more detail how to use this method. + * + * ####Example: + * + * var p = new Promise; + * p.then(function (arg) { + * return arg + 1; + * }).then(function (arg) { + * throw new Error(arg + ' is an error!'); + * }).then(null, function (err) { + * assert.ok(err instanceof Error); + * assert.equal('2 is an error', err.message); + * }); + * p.complete(1); + * + * @see promises-A+ https://github.com/promises-aplus/promises-spec + * @param {Function} onFulfill + * @param {Function} [onReject] + * @return {Promise} newPromise + */ +Promise.prototype.then = function (onFulfill, onReject) { + var newPromise = new Promise; + + if ('function' == typeof onFulfill) { + this.onFulfill(handler(newPromise, onFulfill)); + } else { + this.onFulfill(newPromise.fulfill.bind(newPromise)); + } + + if ('function' == typeof onReject) { + this.onReject(handler(newPromise, onReject)); + } else { + this.onReject(newPromise.reject.bind(newPromise)); + } + + return newPromise; +}; + + +function handler(promise, fn) { + function newTickHandler() { + var pDomain = promise.emitter.domain; + if (pDomain && pDomain !== process.domain) pDomain.enter(); + try { + var x = fn.apply(undefined, boundHandler.args); + } catch (err) { + promise.reject(err); + return; + } + resolve(promise, x); + } + function boundHandler() { + boundHandler.args = arguments; + process.nextTick(newTickHandler); + } + return boundHandler; +} + + +function resolve(promise, x) { + function fulfillOnce() { + if (done++) return; + resolve.apply(undefined, strongUnshift(promise, arguments)); + } + function rejectOnce(reason) { + if (done++) return; + promise.reject(reason); + } + + if (promise === x) { + promise.reject(new TypeError("promise and x are the same")); + return; + } + var rest = toArray(arguments, 1); + var type = typeof x; + if ('undefined' == type || null == x || !('object' == type || 'function' == type)) { + promise.fulfill.apply(promise, rest); + return; + } + + try { + var theThen = x.then; + } catch (err) { + promise.reject(err); + return; + } + + if ('function' != typeof theThen) { + promise.fulfill.apply(promise, rest); + return; + } + + var done = 0; + try { + var ret = theThen.call(x, fulfillOnce, rejectOnce); + return ret; + } catch (err) { + if (done++) return; + promise.reject(err); + } +} + + +/** + * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. + * + * ####Example: + * + * var p = new Promise; + * p.then(function(){ throw new Error('shucks') }); + * setTimeout(function () { + * p.fulfill(); + * // error was caught and swallowed by the promise returned from + * // p.then(). we either have to always register handlers on + * // the returned promises or we can do the following... + * }, 10); + * + * // this time we use .end() which prevents catching thrown errors + * var p = new Promise; + * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- + * setTimeout(function () { + * p.fulfill(); // throws "shucks" + * }, 10); + * + * @api public + * @param {Function} [onReject] + * @return {Promise} this + */ +Promise.prototype.end = function (onReject) { + this.onReject(onReject); + this.ended = true; + return this; +}; + + +/** + * A debug utility function that adds handlers to a promise that will log some output to the `console` + * + * ####Example: + * + * var p = new Promise; + * p.then(function(){ throw new Error('shucks') }); + * setTimeout(function () { + * p.fulfill(); + * // error was caught and swallowed by the promise returned from + * // p.then(). we either have to always register handlers on + * // the returned promises or we can do the following... + * }, 10); + * + * // this time we use .end() which prevents catching thrown errors + * var p = new Promise; + * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- + * setTimeout(function () { + * p.fulfill(); // throws "shucks" + * }, 10); + * + * @api public + * @param {Promise} p + * @param {String} name + * @return {Promise} this + */ +Promise.trace = function (p, name) { + p.then( + function () { + console.log("%s fulfill %j", name, toArray(arguments)); + }, + function () { + console.log("%s reject %j", name, toArray(arguments)); + } + ) +}; + + +Promise.prototype.chain = function (p2) { + var p1 = this; + p1.onFulfill(p2.fulfill.bind(p2)); + p1.onReject(p2.reject.bind(p2)); + return p2; +}; + + +Promise.prototype.all = function (promiseOfArr) { + var pRet = new Promise; + this.then(promiseOfArr).then( + function (promiseArr) { + var count = 0; + var ret = []; + var errSentinel; + if (!promiseArr.length) pRet.resolve(); + promiseArr.forEach(function (promise, index) { + if (errSentinel) return; + count++; + promise.then( + function (val) { + if (errSentinel) return; + ret[index] = val; + --count; + if (count == 0) pRet.fulfill(ret); + }, + function (err) { + if (errSentinel) return; + errSentinel = err; + pRet.reject(err); + } + ); + }); + return pRet; + } + , pRet.reject.bind(pRet) + ); + return pRet; +}; + + +Promise.hook = function (arr) { + var p1 = new Promise; + var pFinal = new Promise; + var signalP = function () { + --count; + if (count == 0) + pFinal.fulfill(); + return pFinal; + }; + var count = 1; + var ps = p1; + arr.forEach(function (hook) { + ps = ps.then( + function () { + var p = new Promise; + count++; + hook(p.resolve.bind(p), signalP); + return p; + } + ) + }); + ps = ps.then(signalP); + p1.resolve(); + return ps; +}; + + +/* This is for the A+ tests, but it's very useful as well */ +Promise.fulfilled = function fulfilled() { var p = new Promise; p.fulfill.apply(p, arguments); return p; }; +Promise.rejected = function rejected(reason) { return new Promise().reject(reason); }; +Promise.deferred = function deferred() { + var p = new Promise; + return { + promise: p, + reject: p.reject.bind(p), + resolve: p.fulfill.bind(p), + callback: p.resolve.bind(p) + } +}; +/* End A+ tests adapter bit */ + + diff --git a/node_modules/mongoose/node_modules/mpromise/package.json b/node_modules/mongoose/node_modules/mpromise/package.json new file mode 100644 index 0000000..def276e --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/package.json @@ -0,0 +1,61 @@ +{ + "name": "mpromise", + "version": "0.5.4", + "publishConfig": { + "tag": "beta" + }, + "description": "Promises A+ conformant implementation", + "main": "lib/promise.js", + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "promises-aplus-tests": "2.0.3", + "mocha": "1.17.1" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mpromise.git" + }, + "keywords": [ + "promise", + "mongoose", + "aplus", + "a+", + "plus" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/aheckmann/mpromise/issues" + }, + "homepage": "https://github.com/aheckmann/mpromise", + "_id": "mpromise@0.5.4", + "dist": { + "shasum": "b610613ec6de37419f944b35f0783b4de9f5dc75", + "tarball": "http://registry.npmjs.org/mpromise/-/mpromise-0.5.4.tgz" + }, + "_from": "mpromise@0.5.4", + "_npmVersion": "1.3.26", + "_npmUser": { + "name": "refack", + "email": "refael@empeeric.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "refack", + "email": "refael@empeeric.com" + } + ], + "directories": {}, + "_shasum": "b610613ec6de37419f944b35f0783b4de9f5dc75", + "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.5.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js b/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js new file mode 100644 index 0000000..a6a6be7 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js @@ -0,0 +1,28 @@ +var Promise = require('../') + , Domain = require('domain').Domain + , assert = require('assert'); + + +describe("domains", function () { + it("exceptions should not breakout of domain boundaries", function (done) { + if (process.version.indexOf('v0.10') != 0) return done(); + var d = new Domain; + d.on('error', function (err) { + assert.equal(err.message, 'gaga'); + done() + }); + + var p = new Promise(); + d.run(function () { + p.then( + function () {} + ).then( + function () { throw new Error('gaga'); } + ).end(); + }); + + process.nextTick(function () { + p.fulfill(); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.test.js b/node_modules/mongoose/node_modules/mpromise/test/promise.test.js new file mode 100644 index 0000000..30be690 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/test/promise.test.js @@ -0,0 +1,554 @@ +/*global describe,it */ +/** + * Module dependencies. + */ + +var assert = require('assert'); +var Promise = require('../'); + +/** + * Test. + */ + +describe('promise', function () { + it('events fire right after fulfill()', function (done) { + var promise = new Promise() + , called = 0; + + promise.on('fulfill', function (a, b) { + assert.equal(a, '1'); + assert.equal(b, '2'); + called++; + }); + + promise.fulfill('1', '2'); + + promise.on('fulfill', function (a, b) { + assert.equal(a, '1'); + assert.equal(b, '2'); + called++; + }); + + assert.equal(2, called); + done(); + }); + + it('events fire right after reject()', function (done) { + var promise = new Promise() + , called = 0; + + promise.on('reject', function (err) { + assert.ok(err instanceof Error); + called++; + }); + + promise.reject(new Error('booyah')); + + promise.on('reject', function (err) { + assert.ok(err instanceof Error); + called++; + }); + + assert.equal(2, called); + done() + }); + + describe('onResolve()', function () { + it('from constructor works', function (done) { + var called = 0; + + var promise = new Promise(function (err) { + assert.ok(err instanceof Error); + called++; + }); + + promise.reject(new Error('dawg')); + + assert.equal(1, called); + done(); + }); + + it('after fulfill()', function (done) { + var promise = new Promise() + , called = 0; + + promise.fulfill('woot'); + + promise.onResolve(function (err, data) { + assert.equal(data, 'woot'); + called++; + }); + + promise.onResolve(function (err) { + assert.strictEqual(err, null); + called++; + }); + + assert.equal(2, called); + done(); + }) + }); + + describe('onFulfill shortcut', function () { + it('works', function (done) { + var promise = new Promise() + , called = 0; + + promise.onFulfill(function (woot) { + assert.strictEqual(woot, undefined); + called++; + }); + + promise.fulfill(); + + assert.equal(1, called); + done(); + }); + }); + + describe('onReject shortcut', function () { + it('works', function (done) { + var promise = new Promise() + , called = 0; + + promise.onReject(function (err) { + assert.ok(err instanceof Error); + called++; + }); + + promise.reject(new Error); + assert.equal(1, called); + done(); + }) + }); + + describe('return values', function () { + it('on()', function (done) { + var promise = new Promise(); + assert.ok(promise.on('jump', function () {}) instanceof Promise); + done() + }); + + it('onFulfill()', function (done) { + var promise = new Promise(); + assert.ok(promise.onFulfill(function () {}) instanceof Promise); + done(); + }); + it('onReject()', function (done) { + var promise = new Promise(); + assert.ok(promise.onReject(function () {}) instanceof Promise); + done(); + }); + it('onResolve()', function (done) { + var promise = new Promise(); + assert.ok(promise.onResolve(function () {}) instanceof Promise); + done(); + }) + }); + + describe('casting errors', function () { + describe('reject()', function () { + it('does not cast arguments to Error', function (done) { + var p = new Promise(function (err) { + assert.equal(3, err); + done(); + }); + + p.reject(3); + }) + }) + }); + + describe('then', function () { + describe('catching', function () { + it('should not catch returned promise fulfillments', function (done) { + var errorSentinal + , p = new Promise; + p.then(function () { throw errorSentinal = new Error("boo!") }); + + p.fulfill(); + done(); + }); + + + it('should not catch returned promise fulfillments even async', function (done) { + var errorSentinal + , p = new Promise; + p.then(function () { throw errorSentinal = new Error("boo!") }); + + setTimeout(function () { + p.fulfill(); + done(); + }, 10); + }); + + + it('can be disabled using .end()', function (done) { + if (process.version.indexOf('v0.8') == 0) return done(); + var errorSentinal + , overTimeout + , domain = require('domain').create(); + + domain.once('error', function (err) { + assert(err, errorSentinal); + clearTimeout(overTimeout); + done() + }); + + domain.run(function () { + var p = new Promise; + var p2 = p.then(function () { + throw errorSentinal = new Error('shucks') + }); + p2.end(); + + p.fulfill(); + }); + overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 10); + }); + + + it('can be disabled using .end() even when async', function (done) { + if (process.version.indexOf('v0.10') != 0) return done(); + var errorSentinal + , overTimeout + , domain = require('domain').create(); + + domain.on('error', function (err) { + assert(err, errorSentinal); + clearTimeout(overTimeout); + done() + }); + + domain.run(function () { + var p = new Promise; + var p2 = p.then(function () { + throw errorSentinal = new Error("boo!") + }); + p2.end(); + + setTimeout(function () {p.fulfill();}, 10); + }); + overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 20); + }); + + + it('can be handled using .end() so no throwing', function (done) { + var errorSentinal + , overTimeout + , domain = require('domain').create(); + + domain.run(function () { + var p = new Promise; + var p2 = p.then(function () { + throw errorSentinal = new Error("boo!") + }); + p2.end(function (err) { + assert.equal(err, errorSentinal); + clearTimeout(overTimeout); + done() + }); + + setTimeout(function () {p.fulfill();}, 10); + }); + overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 20); + }); + + }); + + it('persistent', function (done) { + var p = new Promise; + v = null; + + function ensure(val) { + v = v || val; + assert.equal(v, val); + } + + function guard() { + throw new Error('onReject should not be called'); + } + + p.then(ensure, guard).end(); + + p.fulfill('foo'); + p.fulfill('bar'); + p.reject(new Error('baz')); + + p.then(ensure, guard).end(); + + setTimeout(done, 0); + }); + + + it('accepts multiple completion values', function (done) { + var p = new Promise; + + p.then(function (a, b) { + assert.equal(2, arguments.length); + assert.equal('hi', a); + assert.equal(4, b); + done(); + }, done).end(); + + p.fulfill('hi', 4); + }) + }); + + describe('fulfill values and splats', function () { + it('should handle multiple values', function (done) { + var p = new Promise; + p.onFulfill(function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + }); + p.fulfill('a', 'b', 'c'); + }); + + it('should handle multiple values from a then', function (done) { + Promise.fulfilled().then( + function () { + return Promise.fulfilled().then( + function () { + var p = new Promise; + p.fulfill('a', 'b', 'c'); + return p; + } + ); + } + ).onFulfill( + function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + } + ).end() + }); + + it('should work with `fulfilled` convenience method', function (done) { + Promise.fulfilled('a', 'b', 'c').then(function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + }) + }); + }); + + + describe('end', function () { + it("should return the promise", function (done) { + var p = new Promise; + var p1 = p.end(); + assert.equal(p, p1); + done(); + }); + + + it("should throw for chain", function (done) { + var p = new Promise; + p.then().then().then().then().end(); + try { + p.reject('bad'); + } catch (e) { + done(); + } + }); + + + it("should not throw for chain with reject handler", function (done) { + var p = new Promise; + p.then().then().then().then().end(function () { + done(); + }); + try { + p.reject('bad'); + } catch (e) { + done(e); + } + }); + }); + + + describe('chain', function () { + it('should propagate fulfillment', function (done) { + var varSentinel = {a: 'a'}; + var p1 = new Promise; + p1.chain(new Promise(function (err, doc) { + assert.equal(doc, varSentinel); + done(); + })); + p1.fulfill(varSentinel); + }); + + + it('should propagate rejection', function (done) { + var e = new Error("gaga"); + var p1 = new Promise; + p1.chain(new Promise(function (err) { + assert.equal(err, e); + done(); + })); + p1.reject(e); + }); + + + it('should propagate resolution err', function (done) { + var e = new Error("gaga"); + var p1 = new Promise; + p1.chain(new Promise(function (err) { + assert.equal(err, e); + done(); + })); + p1.resolve(e); + }); + + + it('should propagate resolution val', function (done) { + var varSentinel = {a: 'a'}; + var p1 = new Promise; + p1.chain(new Promise(function (err, val) { + assert.equal(val, varSentinel); + done(); + })); + p1.resolve(null, varSentinel); + }) + }); + + + describe("all", function () { + it("works", function (done) { + var count = 0; + var p = new Promise; + var p2 = p.all(function () { + return [ + (function () { + var p = new Promise(); + count++; + p.resolve(); + return p; + })() + , (function () { + var p = new Promise(); + count++; + p.resolve(); + return p; + })() + ]; + }); + p2.then(function () { + assert.equal(count, 2); + done(); + }); + p.resolve(); + }); + + + it("handles rejects", function (done) { + var count = 0; + var p = new Promise; + var p2 = p.all(function () { + return [ + (function () { + var p = new Promise(); + count++; + p.resolve(); + return p; + })() + , (function () { + count++; + throw new Error("gaga"); + })() + ]; + }); + p2.onReject(function (err) { + assert(err.message, "gaga"); + assert.equal(count, 2); + done(); + }); + p.resolve(); + }); + }); + + + describe("deferred", function () { + it("works", function (done) { + var d = Promise.deferred(); + assert.ok(d.promise instanceof Promise); + assert.ok(d.reject instanceof Function); + assert.ok(d.resolve instanceof Function); + assert.ok(d.callback instanceof Function); + done(); + }); + }); + + + describe("hook", function () { + it("works", function (done) { + var run = 0; + var l1 = function (ser, par) { + run++; + ser(); + par(); + }; + Promise.hook([l1, l1, l1]).then(function () { + assert(run, 3); + done(); + }) + + }); + + + it("works with async serial hooks", function (done) { + this.timeout(800); + var run = 0; + var l1 = function (ser, par) { + run++; + setTimeout(function () {ser();}, 200); + par(); + }; + Promise.hook([l1, l1, l1]).then(function () { + assert(run, 3); + done(); + }) + }); + + + it("works with async parallel hooks", function (done) { + this.timeout(400); + var run = 0; + var l1 = function (ser, par) { + run++; + ser(); + setTimeout(function () {par();}, 200); + }; + Promise.hook([l1, l1, l1]).then(function () { + assert(run, 3); + done(); + }) + }); + + + it("catches errors in hook logic", function (done) { + var run = 0; + var l1 = function (ser, par) { + run++; + ser(); + par(); + }; + var l2 = function (ser, par) { + run++; + ser(); + par(); + throw new Error("err") + }; + Promise.hook([l1, l2, l1]).end(function (err) { + assert(run, 2); + done(); + }); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js b/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js new file mode 100644 index 0000000..d30bb32 --- /dev/null +++ b/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js @@ -0,0 +1,15 @@ +/** + * Module dependencies. + */ +var Promise = require('../lib/promise'); +var aplus = require('promises-aplus-tests'); + +// tests +describe("run A+ suite", function () { + aplus.mocha({ + fulfilled: Promise.fulfilled, + rejected: Promise.rejected, + deferred: Promise.deferred + }); +}); + diff --git a/node_modules/mongoose/node_modules/mquery/.npmignore b/node_modules/mongoose/node_modules/mquery/.npmignore new file mode 100644 index 0000000..5a14ae1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/.npmignore @@ -0,0 +1,3 @@ +*.sw* +node_modules/ +coverage/ diff --git a/node_modules/mongoose/node_modules/mquery/.travis.yml b/node_modules/mongoose/node_modules/mquery/.travis.yml new file mode 100644 index 0000000..4dc3a7d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 +services: + - mongodb diff --git a/node_modules/mongoose/node_modules/mquery/History.md b/node_modules/mongoose/node_modules/mquery/History.md new file mode 100644 index 0000000..052dc61 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/History.md @@ -0,0 +1,215 @@ + +1.5.0 / 2015-03-31 +================== + + * fixed; debug output + * fixed; allow hint usage with count #61 [trueinsider](https://github.com/trueinsider) + +1.4.0 / 2015-03-29 +================== + + * added; object support to slice() #60 [vkarpov15](https://github.com/vkarpov15) + * debug; improved output #57 [flyvictor](https://github.com/flyvictor) + +1.3.0 / 2014-11-06 +================== + + * added; setTraceFunction() #53 from [jlai](https://github.com/jlai) + +1.2.1 / 2014-09-26 +================== + + * fixed; distinct assignment in toConstructor() #51 from [esco](https://github.com/esco) + +1.2.0 / 2014-09-18 +================== + + * added; stream() support for find() + +1.1.0 / 2014-09-15 +================== + + * add #then for co / koa support + * start checking code coverage + +1.0.0 / 2014-07-07 +================== + + * Remove broken require() calls until they're actually implemented #48 [vkarpov15](https://github.com/vkarpov15) + +0.9.0 / 2014-05-22 +================== + + * added; thunk() support + * release 0.8.0 + +0.8.0 / 2014-05-15 +================== + + * added; support for maxTimeMS #44 [yoitsro](https://github.com/yoitsro) + * updated; devDependency (driver to 1.4.4) + +0.7.0 / 2014-05-02 +================== + + * fixed; pass $maxDistance in $near object as described in docs #43 [vkarpov15](https://github.com/vkarpov15) + * fixed; cloning buffers #42 [gjohnson](https://github.com/gjohnson) + * tests; a little bit more `mongodb` agnostic #34 [refack](https://github.com/refack) + +0.6.0 / 2014-04-01 +================== + + * fixed; Allow $meta args in sort() so text search sorting works #37 [vkarpov15](https://github.com/vkarpov15) + +0.5.3 / 2014-02-22 +================== + + * fixed; cloning mongodb.Binary + +0.5.2 / 2014-01-30 +================== + + * fixed; cloning ObjectId constructors + * fixed; cloning of ReadPreferences #30 [ashtuchkin](https://github.com/ashtuchkin) + * tests; use specific mongodb version #29 [AvianFlu](https://github.com/AvianFlu) + * tests; remove dependency on ObjectId #28 [refack](https://github.com/refack) + * tests; add failing ReadPref test + +0.5.1 / 2014-01-17 +================== + + * added; deprecation notice to tags parameter #27 [ashtuchkin](https://github.com/ashtuchkin) + * readme; add links + +0.5.0 / 2014-01-16 +================== + + * removed; mongodb driver dependency #26 [ashtuchkin](https://github.com/ashtuchkin) + * removed; first class support of read preference tags #26 (still supported though) [ashtuchkin](https://github.com/ashtuchkin) + * added; better ObjectId clone support + * fixed; cloning objects that have no constructor #21 + * docs; cleaned up [ashtuchkin](https://github.com/ashtuchkin) + +0.4.2 / 2014-01-08 +================== + + * updated; debug module 0.7.4 [refack](https://github.com/refack) + +0.4.1 / 2014-01-07 +================== + + * fixed; inclusive/exclusive logic + +0.4.0 / 2014-01-06 +================== + + * added; selected() + * added; selectedInclusively() + * added; selectedExclusively() + +0.3.3 / 2013-11-14 +================== + + * Fix Mongo DB Dependency #20 [rschmukler](https://github.com/rschmukler) + +0.3.2 / 2013-09-06 +================== + + * added; geometry support for near() + +0.3.1 / 2013-08-22 +================== + + * fixed; update retains key order #19 + +0.3.0 / 2013-08-22 +================== + + * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) + * added; validation of findAndModify varients + * clone update doc before execution + * stricter env checks + +0.2.7 / 2013-08-2 +================== + + * Now support GeoJSON point values for Query#near + +0.2.6 / 2013-07-30 +================== + + * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively + +0.2.5 / 2013-07-30 +================== + + * updated docs + * changed internal representation of `sort` to use objects instead of arrays + +0.2.4 / 2013-07-25 +================== + + * updated; sliced to 0.0.5 + +0.2.3 / 2013-07-09 +================== + + * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) + +0.2.2 / 2013-07-09 +================== + + * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) + +0.2.1 / 2013-07-08 +================== + + * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) + +0.2.0 / 2013-07-05 +================== + + * use $geoWithin by default + +0.1.2 / 2013-07-02 +================== + + * added use$geoWithin flag [ebensing](https://github.com/ebensing) + * fix read preferences typo [ebensing](https://github.com/ebensing) + * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) + +0.1.1 / 2013-06-24 +================== + + * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) + * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) + * bump mongodb dev dep + +0.1.0 / 2013-05-06 +================== + + * findAndModify; return the query + * move mquery.proto.canMerge to mquery.canMerge + * overwrite option now works with non-empty objects + * use strict mode + * validate count options + * validate distinct options + * add aggregate to base collection methods + * clone merge arguments + * clone merged update arguments + * move subclass to mquery.prototype.toConstructor + * fixed; maxScan casing + * use regexp-clone + * added; geometry/intersects support + * support $and + * near: do not use "radius" + * callbacks always fire on next turn of loop + * defined collection interface + * remove time from tests + * clarify goals + * updated docs; + +0.0.1 / 2012-12-15 +================== + + * initial release diff --git a/node_modules/mongoose/node_modules/mquery/LICENSE b/node_modules/mongoose/node_modules/mquery/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.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. diff --git a/node_modules/mongoose/node_modules/mquery/Makefile b/node_modules/mongoose/node_modules/mquery/Makefile new file mode 100644 index 0000000..dbb2831 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/Makefile @@ -0,0 +1,22 @@ + +test: + @NODE_ENV=test ./node_modules/.bin/mocha $(T) $(TESTS) + +test-cov: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + -- -u exports \ + +open-cov: + open coverage/lcov-report/index.html + +test-travis: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + --report lcovonly \ + -- -u exports \ + --bail + +.PHONY: test test-cov open-cov test-travis diff --git a/node_modules/mongoose/node_modules/mquery/README.md b/node_modules/mongoose/node_modules/mquery/README.md new file mode 100644 index 0000000..f7bf7f4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/README.md @@ -0,0 +1,1220 @@ +#mquery +=========== + +`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases. + +##Features + + - fluent query builder api + - custom base query support + - MongoDB 2.4 geoJSON support + - method + option combinations validation + - node.js driver compatibility + - environment detection + - [debug](https://github.com/visionmedia/debug) support + - separated collection implementations for maximum flexibility + +[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery) + +##Use + +```js +require('mongodb').connect(uri, function (err, db) { + if (err) return handleError(err); + + // get a collection + var collection = db.collection('artists'); + + // pass it to the constructor + mquery(collection).find({..}, callback); + + // or pass it to the collection method + mquery().find({..}).collection(collection).exec(callback) + + // or better yet, create a custom query constructor that has it always set + var Artist = mquery(collection).toConstructor(); + Artist().find(..).where(..).exec(callback) +}) +``` + +`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). + + +##Fluent API + +- [find](#find) +- [findOne](#findOne) +- [count](#count) +- [remove](#remove) +- [update](#update) +- [findOneAndUpdate](#findoneandupdate) +- [findOneAndRemove](#findoneandremove) +- [distinct](#distinct) +- [exec](#exec) +- [stream](#stream) +- [all](#all) +- [and](#and) +- [box](#box) +- [circle](#circle) +- [elemMatch](#elemmatch) +- [equals](#equals) +- [exists](#exists) +- [geometry](#geometry) +- [gt](#gt) +- [gte](#gte) +- [in](#in) +- [intersects](#intersects) +- [lt](#lt) +- [lte](#lte) +- [maxDistance](#maxdistance) +- [mod](#mod) +- [ne](#ne) +- [nin](#nin) +- [nor](#nor) +- [near](#near) +- [or](#or) +- [polygon](#polygon) +- [regex](#regex) +- [select](#select) +- [selected](#selected) +- [selectedInclusively](#selectedinclusively) +- [selectedExclusively](#selectedexclusively) +- [size](#size) +- [slice](#slice) +- [within](#within) +- [where](#where) +- [$where](#where-1) +- [batchSize](#batchsize) +- [comment](#comment) +- [hint](#hint) +- [limit](#limit) +- [maxScan](#maxscan) +- [maxTime](#maxtime) +- [skip](#skip) +- [sort](#sort) +- [read](#read) +- [slaveOk](#slaveok) +- [snapshot](#snapshot) +- [tailable](#tailable) + +## Helpers + +- [collection](#collection) +- [then](#then) +- [thunk](#thunk) +- [merge](#mergeobject) +- [setOptions](#setoptionsoptions) +- [setTraceFunction](#settracefunctionfunc) +- [mquery.setGlobalTraceFunction](#mquerysetglobaltracefunctionfunc) +- [mquery.canMerge](#mquerycanmerge) +- [mquery.use$geoWithin](#mqueryusegeowithin) + +###find() + +Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().find() +mquery().find(match) +mquery().find(callback) +mquery().find(match, function (err, docs) { + assert(Array.isArray(docs)); +}) +``` + +###findOne() + +Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().findOne() +mquery().findOne(match) +mquery().findOne(callback) +mquery().findOne(match, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) +``` + +###count() + +Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().count() +mquery().count(match) +mquery().count(callback) +mquery().count(match, function (err, number){ + console.log('we found %d matching documents', number); +}) +``` + +###remove() + +Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().remove() +mquery().remove(match) +mquery().remove(callback) +mquery().remove(match, function (err){}) +``` + +###update() + +Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. + +```js +mquery().update() +mquery().update(match, updateDocument) +mquery().update(match, updateDocument, options) + +// the following all execute the command +mquery().update(callback) +mquery().update({$set: updateDocument, callback) +mquery().update(match, updateDocument, callback) +mquery().update(match, updateDocument, options, function (err, result){}) +mquery().update(true) // executes (unsafe write) +``` + +#####the update document + +All paths passed that are not `$atomic` operations will become `$set` ops. For example: + +```js +mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) +``` + +becomes + +```js +collection.update({ _id: id }, { $set: { title: 'words' }}, callback) +``` + +This behavior can be overridden using the `overwrite` option (see below). + +#####options + +Options are passed to the `setOptions()` method. + +- overwrite + +Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. + +```js +var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); +q.update({ }, callback); // overwrite with an empty doc +``` + +The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. + +```js +// create a base query +var base = mquery({ _id: 108 }).collection(collection).toConstructor(); + +base().findOne(function (err, doc) { + console.log(doc); // { _id: 108, name: 'cajon' }) + + base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { + base.findOne(function (err, doc) { + console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten + }); + }); +}) +``` + +- multi + +Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. + +```js +mquery() + .collection(coll) + .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) + +// another way of doing it +mquery({ name: /^match/ }) + .collection(coll) + .setOptions({ multi: true }) + .update({ $addToSet: { arr: 4 }}, callback) + +// update multiple documents with an empty doc +var q = mquery(collection).where({ name: /^match/ }); +q.setOptions({ multi: true, overwrite: true }) +q.update({ }); +q.update(function (err, result) { + console.log(arguments); +}); +``` + +###findOneAndUpdate() + +Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. + +#####options + +Options are passed to the `setOptions()` method. + +- `new`: boolean - true to return the modified document rather than the original. defaults to true +- `upsert`: boolean - creates the object if it doesn't exist. defaults to false +- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update + +```js +query.findOneAndUpdate() +query.findOneAndUpdate(updateDocument) +query.findOneAndUpdate(match, updateDocument) +query.findOneAndUpdate(match, updateDocument, options) + +// the following all execute the command +query.findOneAndUpdate(callback) +query.findOneAndUpdate(updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +###findOneAndRemove() + +Declares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. + +#####options + +Options are passed to the `setOptions()` method. + +- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove + +```js +A.where().findOneAndRemove() +A.where().findOneAndRemove(match) +A.where().findOneAndRemove(match, options) + +// the following all execute the command +A.where().findOneAndRemove(callback) +A.where().findOneAndRemove(match, callback) +A.where().findOneAndRemove(match, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +###distinct() + +Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. + +```js +mquery().distinct() +mquery().distinct(match) +mquery().distinct(match, field) +mquery().distinct(field) + +// the following all execute the command +mquery().distinct(callback) +mquery().distinct(field, callback) +mquery().distinct(match, callback) +mquery().distinct(match, field, function (err, result) { + console.log(result); +}) +``` + +###exec() + +Executes the query. + +```js +mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) +``` + +###stream() + +Executes the query and returns a stream. + +```js +var stream = mquery().find().stream(options); +stream.on('data', cb); +stream.on('close', fn); +``` + +Note: this only works with `find()` operations. + +Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the [driver method](http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#stream). + +------------- + +###all() + +Specifies an `$all` query condition + +```js +mquery().where('permission').all(['read', 'write']) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) + +###and() + +Specifies arguments for an `$and` condition + +```js +mquery().and([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) + +###box() + +Specifies a `$box` condition + +```js +var lowerLeft = [40.73083, -73.99756] +var upperRight= [40.741404, -73.988135] + +mquery().where('location').within().box(lowerLeft, upperRight) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) + +###circle() + +Specifies a `$center` or `$centerSphere` condition. + +```js +var area = { center: [50, 50], radius: 10, unique: true } +query.where('loc').within().circle(area) +query.circle('loc', area); + +// for spherical calculations +var area = { center: [50, 50], radius: 10, unique: true, spherical: true } +query.where('loc').within().circle(area) +query.circle('loc', area); +``` + +- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) +- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) + +###elemMatch() + +Specifies an `$elemMatch` condition + +```js +query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + +query.elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) + +###equals() + +Specifies the complementary comparison value for the path specified with `where()`. + +```js +mquery().where('age').equals(49); + +// is the same as + +mquery().where({ 'age': 49 }); +``` + +###exists() + +Specifies an `$exists` condition + +```js +// { name: { $exists: true }} +mquery().where('name').exists() +mquery().where('name').exists(true) +mquery().exists('name') + +// { name: { $exists: false }} +mquery().where('name').exists(false); +mquery().exists('name', false); +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) + +###geometry() + +Specifies a `$geometry` condition + +```js +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + +// or +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + +// or +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) +``` + +`geometry()` **must** come after `intersects()`, `within()`, or `near()`. + +The `object` argument must contain `type` and `coordinates` properties. + +- type `String` +- coordinates `Array` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) + +###gt() + +Specifies a `$gt` query condition. + +```js +mquery().where('clicks').gt(999) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) + +###gte() + +Specifies a `$gte` query condition. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) + +```js +mquery().where('clicks').gte(1000) +``` + +###in() + +Specifies an `$in` query condition. + +```js +mquery().where('author_id').in([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) + +###intersects() + +Declares an `$geoIntersects` query for `geometry()`. + +```js +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) + +// geometry arguments are supported +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) +``` + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) + +###lt() + +Specifies a `$lt` query condition. + +```js +mquery().where('clicks').lt(50) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) + +###lte() + +Specifies a `$lte` query condition. + +```js +mquery().where('clicks').lte(49) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) + +###maxDistance() + +Specifies a `$maxDistance` query condition. + +```js +mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) + +###mod() + +Specifies a `$mod` condition + +```js +mquery().where('count').mod(2, 0) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) + +###ne() + +Specifies a `$ne` query condition. + +```js +mquery().where('status').ne('ok') +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) + +###nin() + +Specifies an `$nin` query condition. + +```js +mquery().where('author_id').nin([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) + +###nor() + +Specifies arguments for an `$nor` condition. + +```js +mquery().nor([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) + +###near() + +Specifies arguments for a `$near` or `$nearSphere` condition. + +These operators return documents sorted by distance. + +####Example + +```js +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); + +// GeoJSON +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); +query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); + +// For a $nearSphere condition, pass the `spherical` option. +query.near({ center: [10, 10], maxDistance: 5, spherical: true }); +``` + +[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) + +###or() + +Specifies arguments for an `$or` condition. + +```js +mquery().or([{ color: 'red' }, { status: 'emergency' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) + +###polygon() + +Specifies a `$polygon` condition + +```js +mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) +mquery().polygon('loc', [10,20], [13, 25], [7,15]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) + +###regex() + +Specifies a `$regex` query condition. + +```js +mquery().where('name').regex(/^sixstepsrecords/) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) + +###select() + +Specifies which document fields to include or exclude + +```js +// 1 means include, 0 means exclude +mquery().select({ name: 1, address: 1, _id: 0 }) + +// or + +mquery().select('name address -_id') +``` + +#####String syntax + +When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + +```js +// include a and b, exclude c +query.select('a b -c'); + +// or you may use object notation, useful when +// you have keys already prefixed with a "-" +query.select({a: 1, b: 1, c: 0}); +``` + +_Cannot be used with `distinct()`._ + +###selected() + +Determines if the query has selected any fields. + +```js +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selected() // true +``` + +###selectedInclusively() + +Determines if the query has selected any fields inclusively. + +```js +var query = mquery().select('name'); +query.selectedInclusively() // true + +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selectedInclusively() // false +query.selectedExclusively() // true +``` + +###selectedExclusively() + +Determines if the query has selected any fields exclusively. + +```js +var query = mquery().select('-name'); +query.selectedExclusively() // true + +var query = mquery(); +query.selected() // false +query.select('name'); +query.selectedExclusively() // false +query.selectedInclusively() // true +``` + +###size() + +Specifies a `$size` query condition. + +```js +mquery().where('someArray').size(6) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) + +###slice() + +Specifies a `$slice` projection for a `path` + +```js +mquery().where('comments').slice(5) +mquery().where('comments').slice(-5) +mquery().where('comments').slice([-10, 5]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) + +###within() + +Sets a `$geoWithin` or `$within` argument for geo-spatial queries. + +```js +mquery().within().box() +mquery().within().circle() +mquery().within().geometry() + +mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +mquery().where('loc').within({ polygon: [[],[],[],[]] }); + +mquery().where('loc').within([], [], []) // polygon +mquery().where('loc').within([], []) // box +mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry +``` + +As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) + +###where() + +Specifies a `path` for use with chaining + +```js +// instead of writing: +mquery().find({age: {$gte: 21, $lte: 65}}); + +// we can instead write: +mquery().where('age').gte(21).lte(65); + +// passing query conditions is permitted too +mquery().find().where({ name: 'vonderful' }) + +// chaining +mquery() +.where('age').gte(21).lte(65) +.where({ 'name': /^vonderful/i }) +.where('friends').slice(10) +.exec(callback) +``` + +###$where() + +Specifies a `$where` condition. + +Use `$where` when you need to select documents using a JavaScript expression. + +```js +query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) + +query.$where(function () { + return this.comments.length > 10 || this.name.length > 5; +}) +``` + +Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. + +----------- + +###batchSize() + +Specifies the batchSize option. + +```js +query.batchSize(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) + +###comment() + +Specifies the comment option. + +```js +query.comment('login query'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) + +###hint() + +Sets query hints. + +```js +mquery().hint({ indexA: 1, indexB: -1 }) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) + +###limit() + +Specifies the limit option. + +```js +query.limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) + +###maxScan() + +Specifies the maxScan option. + +```js +query.maxScan(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) + +###maxTime() + +Specifies the maxTimeMS option. + +```js +query.maxTime(100) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.maxTimeMS/) + + +###skip() + +Specifies the skip option. + +```js +query.skip(100).limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) + +###sort() + +Sets the query sort order. + +If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + +If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + +```js +// these are equivalent +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) + +###read() + +Sets the readPreference option for the query. + +```js +mquery().read('primary') +mquery().read('p') // same as primary + +mquery().read('primaryPreferred') +mquery().read('pp') // same as primaryPreferred + +mquery().read('secondary') +mquery().read('s') // same as secondary + +mquery().read('secondaryPreferred') +mquery().read('sp') // same as secondaryPreferred + +mquery().read('nearest') +mquery().read('n') // same as nearest +``` + +#####Preferences: + +- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. +- `secondary` - Read from secondary if available, otherwise error. +- `primaryPreferred` - Read from primary if available, otherwise a secondary. +- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. +- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + +Aliases + +- `p` primary +- `pp` primaryPreferred +- `s` secondary +- `sp` secondaryPreferred +- `n` nearest + +#####Preference Tags: + +To keep the separation of concerns between `mquery` and your driver +clean, `mquery#read()` no longer handles specifying a second `tags` argument as of version 0.5. +If you need to specify tags, pass any non-string argument as the first argument. +`mquery` will pass this argument untouched to your collections methods later. +For example: + +```js +// example of specifying tags using the Node.js driver +var ReadPref = require('mongodb').ReadPreference; +var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +mquery(..).read(preference).exec(); +``` + +Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + +###slaveOk() + +Sets the slaveOk option. `true` allows reading from secondaries. + +**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 + +```js +query.slaveOk() // true +query.slaveOk(true) +query.slaveOk(false) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) + +###snapshot() + +Specifies this query as a snapshot query. + +```js +mquery().snapshot() // true +mquery().snapshot(true) +mquery().snapshot(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) + +###tailable() + +Sets tailable option. + +```js +mquery().tailable() <== true +mquery().tailable(true) +mquery().tailable(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) + +##Helpers + +###collection() + +Sets the querys collection. + +```js +mquery().collection(aCollection) +``` + +###then() + +Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error. + +```js +mquery().find(..).then(success, error); +``` + +This is very useful when combined with [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa), which automatically resolve promise-like objects for you. + +```js +co(function*(){ + var doc = yield mquery().findOne({ _id: 499 }); + console.log(doc); // { _id: 499, name: 'amazing', .. } +})(); +``` + +_NOTE_: +The returned promise is a [bluebird](https://github.com/petkaantonov/bluebird/) promise but this is customizable. If you want to +use your favorite promise library, simply set `mquery.Promise = YourPromiseConstructor`. +Your `Promise` must be [promises A+](http://promisesaplus.com/) compliant. + +###thunk() + +Returns a thunk which when called runs the query's `exec` method passing the results to the callback. + +```js +var thunk = mquery(collection).find({..}).thunk(); + +thunk(function(err, results) { + +}) +``` + +###merge(object) + +Merges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged. + +```js +var drum = mquery({ type: 'drum' }).collection(instruments); +var redDrum = mqery({ color: 'red' }).merge(drum); +redDrum.count(function (err, n) { + console.log('there are %d red drums', n); +}) +``` + +Internally uses `mquery.canMerge` to determine validity. + +###setOptions(options) + +Sets query options. + +```js +mquery().setOptions({ collection: coll, limit: 20 }) +``` + +#####options + +- [tailable](#tailable) * +- [sort](#sort) * +- [limit](#limit) * +- [skip](#skip) * +- [maxScan](#maxscan) * +- [maxTime](#maxtime) * +- [batchSize](#batchSize) * +- [comment](#comment) * +- [snapshot](#snapshot) * +- [hint](#hint) * +- [slaveOk](#slaveOk) * +- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }` +- [collection](#collection): the collection to query against + +_* denotes a query helper method is also available_ + +###setTraceFunction(func) + +Set a function to trace this query. Useful for profiling or logging. + +```js +function traceFunction (method, queryInfo, query) { + console.log('starting ' + method + ' query'); + + return function (err, result, millis) { + console.log('finished ' + method + ' query in ' + millis + 'ms'); + }; +} + +mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb); +``` + +The trace function is passed (method, queryInfo, query) + +- method is the name of the method being called (e.g. findOne) +- queryInfo contains information about the query: + - conditions: query conditions/criteria + - options: options such as sort, fields, etc + - doc: document being updated +- query is the query object + +The trace function should return a callback function which accepts: +- err: error, if any +- result: result, if any +- millis: time spent waiting for query result + +NOTE: stream requests are not traced. + +###mquery.setGlobalTraceFunction(func) + +Similar to `setTraceFunction()` but automatically applied to all queries. + +```js +mquery.setTraceFunction(traceFunction); +``` + +###mquery.canMerge(conditions) + +Determines if `conditions` can be merged using `mquery().merge()`. + +```js +var query = mquery({ type: 'drum' }); +var okToMerge = mquery.canMerge(anObject) +if (okToMerge) { + query.merge(anObject); +} +``` + +##mquery.use$geoWithin + +MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. + +If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. + +```js +mquery.use$geoWithin = false; +``` + +##Custom Base Queries + +Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. + +```js +var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); + +// use it! +greatMovies().count(function (err, n) { + console.log('There are %d great movies', n); +}); + +greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { + console.log(docs); +}); +``` + +##Validation + +Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. + +##Debug support + +Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: + + DEBUG=mquery node yourprogram.js + +Read the debug module documentation for more details. + +## General compatibility + +#### ObjectIds + +`mquery` clones query arguments before passing them to a `collection` method for execution. +This prevents accidental side-affects to the objects you pass. +To clone `ObjectIds` we need to make some assumptions. + +First, to check if an object is an `ObjectId`, we check its constructors name. If it matches either +`ObjectId` or `ObjectID` we clone it. + +To clone `ObjectIds`, we call its optional `clone` method. If a `clone` method does not exist, we fall +back to calling `new obj.constructor(obj.id)`. We assume, for compatibility with the +Node.js driver, that the `ObjectId` instance has a public `id` property and that +when creating an `ObjectId` instance we can pass that `id` as an argument. + +#### Read Preferences + +`mquery` supports specifying [Read Preferences]() to control from which MongoDB node your query will read. +The Read Preferences spec also support specifying tags. To pass tags, some +drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags. +If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. `mquery` will store whatever you provide and pass later to your collection during execution. + +##Future goals + + - mongo shell compatibility + - browser compatibility + +## Installation + + $ npm install mquery + +## License + +[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) + diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js b/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js new file mode 100644 index 0000000..bce3c38 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * methods a collection must implement + */ + +var methods = [ + 'find' + , 'findOne' + , 'update' + , 'remove' + , 'count' + , 'distinct' + , 'findAndModify' + , 'aggregate' + , 'findStream' +]; + +/** + * Collection base class from which implementations inherit + */ + +function Collection () {} + +for (var i = 0, len = methods.length; i < len; ++i) { + var method = methods[i]; + Collection.prototype[method] = notImplemented(method); +} + +module.exports = exports = Collection; +Collection.methods = methods; + +/** + * creates a function which throws an implementation error + */ + +function notImplemented (method) { + return function () { + throw new Error('collection.' + method + ' not implemented'); + } +} + diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/index.js b/node_modules/mongoose/node_modules/mquery/lib/collection/index.js new file mode 100644 index 0000000..e3cf44d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/collection/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var env = require('../env') + +if ('unknown' == env.type) { + throw new Error('Unknown environment') +} + +module.exports = + env.isNode ? require('./node') : + env.isMongo ? require('./collection') : + require('./collection'); + diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js b/node_modules/mongoose/node_modules/mquery/lib/collection/node.js new file mode 100644 index 0000000..f254456 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/collection/node.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * Module dependencies + */ + +var Collection = require('./collection'); +var utils = require('../utils'); + +function NodeCollection (col) { + this.collection = col; + this.collectionName = col.collectionName; +} + +/** + * inherit from collection base class + */ + +utils.inherits(NodeCollection, Collection); + +/** + * find(match, options, function(err, docs)) + */ + +NodeCollection.prototype.find = function (match, options, cb) { + this.collection.find(match, options, function (err, cursor) { + if (err) return cb(err); + + cursor.toArray(cb); + }); +} + +/** + * findOne(match, options, function(err, doc)) + */ + +NodeCollection.prototype.findOne = function (match, options, cb) { + this.collection.findOne(match, options, cb); +} + +/** + * count(match, options, function(err, count)) + */ + +NodeCollection.prototype.count = function (match, options, cb) { + this.collection.count(match, options, cb); +} + +/** + * distinct(prop, match, options, function(err, count)) + */ + +NodeCollection.prototype.distinct = function (prop, match, options, cb) { + this.collection.distinct(prop, match, options, cb); +} + +/** + * update(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.update = function (match, update, options, cb) { + this.collection.update(match, update, options, cb); +} + +/** + * remove(match, options, function(err[, result]) + */ + +NodeCollection.prototype.remove = function (match, options, cb) { + this.collection.remove(match, options, cb); +} + +/** + * findAndModify(match, update, options, function(err, doc)) + */ + +NodeCollection.prototype.findAndModify = function (match, update, options, cb) { + var sort = Array.isArray(options.sort) ? options.sort : []; + this.collection.findAndModify(match, sort, update, options, cb); +} + +/** + * var stream = findStream(match, findOptions, streamOptions) + */ + +NodeCollection.prototype.findStream = function(match, findOptions, streamOptions) { + return this.collection.find(match, findOptions).stream(streamOptions); +} + +/** + * aggregation(operators..., function(err, doc)) + * TODO + */ + +/** + * Expose + */ + +module.exports = exports = NodeCollection; + diff --git a/node_modules/mongoose/node_modules/mquery/lib/env.js b/node_modules/mongoose/node_modules/mquery/lib/env.js new file mode 100644 index 0000000..3313b46 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/env.js @@ -0,0 +1,22 @@ +'use strict'; + +exports.isNode = 'undefined' != typeof process + && 'object' == typeof module + && 'object' == typeof global + && 'function' == typeof Buffer + && process.argv + +exports.isMongo = !exports.isNode + && 'function' == typeof printjson + && 'function' == typeof ObjectId + && 'function' == typeof rs + && 'function' == typeof sh; + +exports.isBrowser = !exports.isNode + && !exports.isMongo + && 'undefined' != typeof window; + +exports.type = exports.isNode ? 'node' + : exports.isMongo ? 'mongo' + : exports.isBrowser ? 'browser' + : 'unknown' diff --git a/node_modules/mongoose/node_modules/mquery/lib/mquery.js b/node_modules/mongoose/node_modules/mquery/lib/mquery.js new file mode 100644 index 0000000..f335ec4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/mquery.js @@ -0,0 +1,2608 @@ +'use strict'; + +/** + * Dependencies + */ + +var slice = require('sliced') +var assert = require('assert') +var util = require('util') +var utils = require('./utils') +var debug = require('debug')('mquery'); + +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query({ name: 'mquery' }); + * query.setOptions({ collection: moduleCollection }) + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [criteria] + * @param {Object} [options] + * @api public + */ + +function Query (criteria, options) { + if (!(this instanceof Query)) + return new Query(criteria, options); + + var proto = this.constructor.prototype; + + this.op = proto.op || undefined; + + this.options = {}; + this.setOptions(proto.options); + + this._conditions = proto._conditions + ? utils.clone(proto._conditions) + : {}; + + this._fields = proto._fields + ? utils.clone(proto._fields) + : undefined; + + this._update = proto._update + ? utils.clone(proto._update) + : undefined; + + this._path = proto._path || undefined; + this._distinct = proto._distinct || undefined; + this._collection = proto._collection || undefined; + this._traceFunction = proto._traceFunction || undefined; + + if (options) { + this.setOptions(options); + } + + if (criteria) { + if (criteria.find && criteria.remove && criteria.update) { + // quack quack! + this.collection(criteria); + } else { + this.find(criteria); + } + } +} + +/** + * This is a parameter that the user can set which determines if mquery + * uses $within or $geoWithin for queries. It defaults to true which + * means $geoWithin will be used. If using MongoDB < 2.4 you should + * set this to false. + * + * @api public + * @property use$geoWithin + */ + +var $withinCmd = '$geoWithin'; +Object.defineProperty(Query, 'use$geoWithin', { + get: function ( ) { return $withinCmd == '$geoWithin' } + , set: function (v) { + if (true === v) { + // mongodb >= 2.4 + $withinCmd = '$geoWithin'; + } else { + $withinCmd = '$within'; + } + } +}); + +/** + * Converts this query to a constructor function with all arguments and options retained. + * + * ####Example + * + * // Create a query that will read documents with a "video" category from + * // `aCollection` on the primary node in the replica-set unless it is down, + * // in which case we'll read from a secondary node. + * var query = mquery({ category: 'video' }) + * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); + * + * // create a constructor based off these settings + * var Video = query.toConstructor(); + * + * // Video is now a subclass of mquery() and works the same way but with the + * // default query parameters and options set. + * + * // run a query with the previous settings but filter for movies with names + * // that start with "Life". + * Video().where({ name: /^Life/ }).exec(cb); + * + * @return {Query} new Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor () { + function CustomQuery (criteria, options) { + if (!(this instanceof CustomQuery)) + return new CustomQuery(criteria, options); + Query.call(this, criteria, options); + } + + utils.inherits(CustomQuery, Query); + + // set inherited defaults + var p = CustomQuery.prototype; + + p.options = {}; + p.setOptions(this.options); + + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._traceFunction = this._traceFunction; + + return CustomQuery; +} + +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * + * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * - collection the collection to query against + * + * _* denotes a query helper method is also available_ + * + * @param {Object} options + * @api public + */ + +Query.prototype.setOptions = function (options) { + if (!(options && utils.isObject(options))) + return this; + + // set arbitrary options + var methods = utils.keys(options) + , method + + for (var i = 0; i < methods.length; ++i) { + method = methods[i]; + + // use methods if exist (safer option manipulation) + if ('function' == typeof this[method]) { + var args = utils.isArray(options[method]) + ? options[method] + : [options[method]]; + this[method].apply(this, args) + } else { + this.options[method] = options[method]; + } + } + + return this; +} + +/** + * Sets this Querys collection. + * + * @param {Collection} coll + * @return {Query} this + */ + +Query.prototype.collection = function collection (coll) { + this._collection = new Query.Collection(coll); + + return this; +} + +/** + * Specifies a `$where` condition + * + * Use `$where` when you need to select documents using a JavaScript expression. + * + * ####Example + * + * query.$where('this.comments.length > 10 || this.name.length > 5') + * + * query.$where(function () { + * return this.comments.length > 10 || this.name.length > 5; + * }) + * + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ + +Query.prototype.$where = function (js) { + this._conditions.$where = js; + return this; +} + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @param {String} [path] + * @param {Object} [val] + * @return {Query} this + * @api public + */ + +Query.prototype.where = function () { + if (!arguments.length) return this; + if (!this.op) this.op = 'find'; + + var type = typeof arguments[0]; + + if ('string' == type) { + this._path = arguments[0]; + + if (2 === arguments.length) { + this._conditions[this._path] = arguments[1]; + } + + return this; + } + + if ('object' == type && !Array.isArray(arguments[0])) { + return this.merge(arguments[0]); + } + + throw new TypeError('path must be a string or object'); +} + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.equals = function equals (val) { + this._ensurePath('equals'); + var path = this._path; + this._conditions[path] = val; + return this; +} + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.or = function or (array) { + var or = this._conditions.$or || (this._conditions.$or = []); + if (!utils.isArray(array)) array = [array]; + or.push.apply(or, array); + return this; +} + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.nor = function nor (array) { + var nor = this._conditions.$nor || (this._conditions.$nor = []); + if (!utils.isArray(array)) array = [array]; + nor.push.apply(nor, array); + return this; +} + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.and = function and (array) { + var and = this._conditions.$and || (this._conditions.$and = []); + if (!Array.isArray(array)) array = [array]; + and.push.apply(and, array); + return this; +} + +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/*! + * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance + * + * Thing.where('type').nin(array) + */ + +'gt gte lt lte ne in nin all regex size maxDistance'.split(' ').forEach(function ($conditional) { + Query.prototype[$conditional] = function () { + var path, val; + + if (1 === arguments.length) { + this._ensurePath($conditional); + val = arguments[0]; + path = this._path; + } else { + val = arguments[1]; + path = arguments[0]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds['$' + $conditional] = val; + return this; + }; +}) + +/** + * Specifies a `$mod` condition + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.mod = function () { + var val, path; + + if (1 === arguments.length) { + this._ensurePath('mod') + val = arguments[0]; + path = this._path; + } else if (2 === arguments.length && !utils.isArray(arguments[1])) { + this._ensurePath('mod') + val = slice(arguments); + path = this._path; + } else if (3 === arguments.length) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +} + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.exists = function () { + var path, val; + + if (0 === arguments.length) { + this._ensurePath('exists'); + path = this._path; + val = true; + } else if (1 === arguments.length) { + if ('boolean' === typeof arguments[0]) { + this._ensurePath('exists'); + path = this._path; + val = arguments[0]; + } else { + path = arguments[0]; + val = true; + } + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$exists = val; + return this; +} + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @api public + */ + +Query.prototype.elemMatch = function () { + if (null == arguments[0]) + throw new TypeError("Invalid argument"); + + var fn, path, criteria; + + if ('function' === typeof arguments[0]) { + this._ensurePath('elemMatch'); + path = this._path; + fn = arguments[0]; + } else if (utils.isObject(arguments[0])) { + this._ensurePath('elemMatch'); + path = this._path; + criteria = arguments[0]; + } else if ('function' === typeof arguments[1]) { + path = arguments[0]; + fn = arguments[1]; + } else if (arguments[1] && utils.isObject(arguments[1])) { + path = arguments[0]; + criteria = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (fn) { + criteria = new Query; + fn(criteria); + criteria = criteria._conditions; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$elemMatch = criteria; + return this; +} + +// Spatial queries + +/** + * Sugar for geo-spatial queries. + * + * ####Example + * + * query.within().box() + * query.within().circle() + * query.within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * ####NOTE: + * + * Must be used after `where()`. + * + * @memberOf Query + * @return {Query} this + * @api public + */ + +Query.prototype.within = function within () { + // opinionated, must be used after where + this._ensurePath('within'); + this._geoComparison = $withinCmd; + + if (0 === arguments.length) { + return this; + } + + if (2 === arguments.length) { + return this.box.apply(this, arguments); + } else if (2 < arguments.length) { + return this.polygon.apply(this, arguments); + } + + var area = arguments[0]; + + if (!area) + throw new TypeError('Invalid argument'); + + if (area.center) + return this.circle(area); + + if (area.box) + return this.box.apply(this, area.box); + + if (area.polygon) + return this.polygon.apply(this, area.polygon); + + if (area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +} + +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box('loc', lowerLeft, upperRight ) + * + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see Query#within #query_Query-within + * @param {String} path + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.box = function () { + var path, box; + + if (3 === arguments.length) { + // box('loc', [], []) + path = arguments[0]; + box = [arguments[1], arguments[2]]; + } else if (2 === arguments.length) { + // box([], []) + this._ensurePath('box'); + path = this._path; + box = [arguments[0], arguments[1]]; + } else { + throw new TypeError("Invalid argument"); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { '$box': box }; + return this; +} + +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @param {String|Array} [path] + * @param {Array|Object} [val] + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.polygon = function () { + var val, path; + + if ('string' == typeof arguments[0]) { + // polygon('loc', [],[],[]) + path = arguments[0]; + val = slice(arguments, 1); + } else { + // polygon([],[],[]) + this._ensurePath('polygon'); + path = this._path; + val = slice(arguments); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { '$polygon': val }; + return this; +} + +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * // for spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.circle = function () { + var path, val; + + if (1 === arguments.length) { + this._ensurePath('circle'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!('radius' in val && val.center)) + throw new Error('center and radius are required'); + + var conds = this._conditions[path] || (this._conditions[path] = {}); + + var type = val.spherical + ? '$centerSphere' + : '$center'; + + var wKey = this._geoComparison || $withinCmd; + conds[wKey] = {}; + conds[wKey][type] = [val.center, val.radius]; + + if ('unique' in val) + conds[wKey].$uniqueDocs = !! val.unique; + + return this; +} + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * query.near({ center: { type: 'Point', coordinates: [..] }}) + * query.near().geometry({ type: 'Point', coordinates: [..] }) + * + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.near = function near () { + var path, val; + + this._geoComparison = '$near'; + + if (0 === arguments.length) { + return this; + } else if (1 === arguments.length) { + this._ensurePath('near'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!val.center) { + throw new Error('center is required'); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + + var type = val.spherical + ? '$nearSphere' + : '$near'; + + // center could be a GeoJSON object or an Array + if (Array.isArray(val.center)) { + conds[type] = val.center; + + var radius = 'maxDistance' in val + ? val.maxDistance + : null; + + if (null != radius) { + conds.$maxDistance = radius; + } + } else { + // GeoJSON? + if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { + throw new Error(util.format("Invalid GeoJSON specified for %s", type)); + } + conds[type] = { $geometry : val.center }; + + // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere + if ('maxDistance' in val) { + conds[type]['$maxDistance'] = val.maxDistance; + } + } + + return this; +} + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * @param {Object} [arg] + * @return {Query} this + * @api public + */ + +Query.prototype.intersects = function intersects () { + // opinionated, must be used after where + this._ensurePath('intersects'); + + this._geoComparison = '$geoIntersects'; + + if (0 === arguments.length) { + return this; + } + + var area = arguments[0]; + + if (null != area && area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +} + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * The most recent path passed to `where()` is used. + * + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @api public + */ + +Query.prototype.geometry = function geometry () { + if (!('$within' == this._geoComparison || + '$geoWithin' == this._geoComparison || + '$near' == this._geoComparison || + '$geoIntersects' == this._geoComparison)) { + throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); + } + + var val, path; + + if (1 === arguments.length) { + this._ensurePath('geometry'); + path = this._path; + val = arguments[0]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!(val.type && Array.isArray(val.coordinates))) { + throw new TypeError('Invalid argument'); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison] = { $geometry: val }; + + return this; +} + +// end spatial + +/** + * Specifies which document fields to include or exclude + * + * ####String syntax + * + * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + * + * ####Example + * + * // include a and b, exclude c + * query.select('a b -c'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({a: 1, b: 1, c: 0}); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +Query.prototype.select = function select () { + var arg = arguments[0]; + if (!arg) return this; + + if (arguments.length !== 1) { + throw new Error("Invalid select: select only takes 1 argument"); + } + + this._validate('select'); + + var fields = this._fields || (this._fields = {}); + var type = typeof arg; + + if ('string' == type || 'object' == type && 'number' == typeof arg.length && !Array.isArray(arg)) { + if ('string' == type) + arg = arg.split(/\s+/); + + for (var i = 0, len = arg.length; i < len; ++i) { + var field = arg[i]; + if (!field) continue; + var include = '-' == field[0] ? 0 : 1; + if (include === 0) field = field.substring(1); + fields[field] = include; + } + + return this; + } + + if (utils.isObject(arg) && !Array.isArray(arg)) { + var keys = utils.keys(arg); + for (var i = 0; i < keys.length; ++i) { + fields[keys[i]] = arg[keys[i]]; + } + return this; + } + + throw new TypeError('Invalid select() argument. Must be string or object.'); +} + +/** + * Specifies a $slice condition for a `path` + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @api public + */ + +Query.prototype.slice = function () { + if (0 === arguments.length) + return this; + + this._validate('slice'); + + var path, val; + + if (1 === arguments.length) { + var arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + var keys = Object.keys(arg); + var numKeys = keys.length; + for (var i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); + } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (3 === arguments.length) { + path = arguments[0]; + val = slice(arguments, 1); + } + + var myFields = this._fields || (this._fields = {}); + myFields[path] = { '$slice': val }; + return this; +} + +/** + * Sets the sort order + * + * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Example + * + * // these are equivalent + * query.sort({ field: 'asc', test: -1 }); + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @api public + */ + +Query.prototype.sort = function (arg) { + if (!arg) return this; + + this._validate('sort'); + + var type = typeof arg; + + if (1 === arguments.length && 'string' == type) { + arg = arg.split(/\s+/); + + for (var i = 0, len = arg.length; i < len; ++i) { + var field = arg[i]; + if (!field) continue; + var ascend = '-' == field[0] ? -1 : 1; + if (ascend === -1) field = field.substring(1); + push(this.options, field, ascend); + } + + return this; + } + + if (utils.isObject(arg)) { + var keys = utils.keys(arg); + for (var i = 0; i < keys.length; ++i) { + var field = keys[i]; + push(this.options, field, arg[field]); + } + + return this; + } + + throw new TypeError('Invalid sort() argument. Must be a string or object.'); +} + +/*! + * @ignore + */ + +function push (opts, field, value) { + if (value && value.$meta) { + var s = opts.sort || (opts.sort = {}); + s[field] = { $meta : value.$meta }; + return; + } + + var val = String(value || 1).toLowerCase(); + if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) { + if (utils.isArray(value)) value = '['+value+']'; + throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }'); + } + // store `sort` in a sane format + var s = opts.sort || (opts.sort = {}); + var valueStr = value.toString() + .replace("asc", "1") + .replace("ascending", "1") + .replace("desc", "-1") + .replace("descending", "-1"); + s[field] = parseInt(valueStr, 10); +} + +/** + * Specifies the limit option. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D + * @api public + */ +/** + * Specifies the skip option. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D + * @api public + */ +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan + * @api public + */ +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D + * @api public + */ +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment + * @api public + */ + +/*! + * limit, skip, maxScan, batchSize, comment + * + * Sets these associated options. + * + * query.comment('feed query'); + */ + +;['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) { + Query.prototype[method] = function (v) { + this._validate(method); + this.options[method] = v; + return this; + }; +}) + +/** + * Specifies the maxTimeMS option. + * + * ####Example + * + * query.maxTime(100) + * + * @method maxTime + * @memberOf Query + * @param {Number} val + * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS + * @api public + */ + +Query.prototype.maxTime = function (v) { + this._validate('maxTime'); + this.options.maxTimeMS = v; + return this; +}; + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * mquery().snapshot() // true + * mquery().snapshot(true) + * mquery().snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D + * @return {Query} this + * @api public + */ + +Query.prototype.snapshot = function () { + this._validate('snapshot'); + + this.options.snapshot = arguments.length + ? !! arguments[0] + : true + + return this; +} + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object} val a hint object + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint + * @api public + */ + +Query.prototype.hint = function () { + if (0 === arguments.length) return this; + + this._validate('hint'); + + var arg = arguments[0]; + if (utils.isObject(arg)) { + var hint = this.options.hint || (this.options.hint = {}); + + // must keep object keys in order so don't use Object.keys() + for (var k in arg) { + hint[k] = arg[k]; + } + + return this; + } + + throw new TypeError('Invalid hint. ' + arg); +} + +/** + * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see read() + * @return {Query} this + * @api public + */ + +Query.prototype.slaveOk = function (v) { + this.options.slaveOk = arguments.length ? !!v : true; + return this; +} + +/** + * Sets the readPreference option for the query. + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // you can also use mongodb.ReadPreference class to also specify tags + * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @param {String|ReadPreference} pref one of the listed preference options or their aliases + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = function (pref) { + if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { + console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."); + Query.prototype.read.deprecationWarningIssued = true; + } + this.options.readPreference = utils.readPref(pref); + return this; +} + +/** + * Sets tailable option. + * + * ####Example + * + * query.tailable() <== true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} v defaults to true + * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors + * @api public + */ + +Query.prototype.tailable = function () { + this._validate('tailable'); + + this.options.tailable = arguments.length + ? !! arguments[0] + : true; + + return this; +} + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ + +Query.prototype.merge = function (source) { + if (!source) + return this; + + if (!Query.canMerge(source)) + throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); + + if (source instanceof Query) { + // if source has a feature, apply it to ourselves + + if (source._conditions) { + utils.merge(this._conditions, source._conditions); + } + + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields); + } + + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options); + } + + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } + + if (source._distinct) { + this._distinct = source._distinct; + } + + return this; + } + + // plain object + utils.merge(this._conditions, source); + + return this; +} + +/** + * Finds documents. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.find() + * query.find(callback) + * query.find({ name: 'Burning Lights' }, callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function (criteria, callback) { + this.op = 'find'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var self = this + , conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec() + + debug('find', this._collection.collectionName, conds, options); + callback = this._wrapCallback('find', callback, { + conditions: conds + , options: options + }); + + this._collection.find(conds, options, utils.tick(callback)); + return this; +} + +/** + * Executes the query as a findOne() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.findOne().where('name', /^Burning/); + * + * query.findOne({ name: /^Burning/ }) + * + * query.findOne({ name: /^Burning/ }, callback); // executes + * + * query.findOne(function (err, doc) { + * if (err) return handleError(err); + * if (doc) { + * // doc may be null if no document matched + * + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.findOne = function (criteria, callback) { + this.op = 'findOne'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var self = this + , conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec(); + + debug('findOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('findOne', callback, { + conditions: conds + , options: options + }); + + this._collection.findOne(conds, options, utils.tick(callback)); + + return this; +} + +/** + * Exectues the query as a count() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.count().where('color', 'black').exec(callback); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count + * @api public + */ + +Query.prototype.count = function (criteria, callback) { + this.op = 'count'; + this._validate(); + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var conds = this._conditions + , options = this._optionsForExec() + + debug('count', this._collection.collectionName, conds, options); + callback = this._wrapCallback('count', callback, { + conditions: conds + , options: options + }); + + this._collection.count(conds, options, utils.tick(callback)); + return this; +} + +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(criteria, field, fn) + * distinct(criteria, field) + * distinct(field, fn) + * distinct(field) + * distinct(fn) + * distinct() + * + * @param {Object|Query} [criteria] + * @param {String} [field] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct + * @api public + */ + +Query.prototype.distinct = function (criteria, field, callback) { + this.op = 'distinct'; + this._validate(); + + if (!callback) { + switch (typeof field) { + case 'function': + callback = field; + if ('string' == typeof criteria) { + field = criteria; + criteria = undefined; + } + break; + case 'undefined': + case 'string': + break; + default: + throw new TypeError('Invalid `field` argument. Must be string or function') + break; + } + + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = field = undefined; + break; + case 'string': + field = criteria; + criteria = undefined; + break; + } + } + + if ('string' == typeof field) { + this._distinct = field; + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) { + return this; + } + + if (!this._distinct) { + throw new Error('No value for `distinct` has been declared'); + } + + var conds = this._conditions + , options = this._optionsForExec() + + debug('distinct', this._collection.collectionName, conds, options); + callback = this._wrapCallback('distinct', callback, { + conditions: conds + , options: options + }); + + this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); + + return this; +} + +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * mquery({ _id: id }).update({ title: 'words' }, ...) + * + * becomes + * + * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).where({ _id: id }).exec(); + * + * var q = mquery(collection).update(); // not executed + * + * // overwriting with empty docs + * var q.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = mquery(collection).where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * mquery() + * .collection(coll) + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * // more multi updates + * mquery({ }) + * .collection(coll) + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * mquery({ email: 'address@example.com' }) + * .collection(coll) + * .update({ $inc: { counter: 1 }}, callback) + * + * // summary + * update(criteria, doc, opts, cb) // executes + * update(criteria, doc, opts) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.update = function update (criteria, doc, options, callback) { + this.op = 'update'; + var force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (doc) { + this._mergeUpdate(doc); + } + + if (utils.isObject(options)) { + // { overwrite: true } + this.setOptions(options); + } + + // we are done if we don't have callback and they are + // not forcing an unsafe write. + if (!(force || callback)) + return this; + + if (!this._update || + !this.options.overwrite && 0 === utils.keys(this._update).length) { + callback && utils.soon(callback.bind(null, null, 0)); + return this; + } + + options = this._optionsForExec(); + if (!callback) options.safe = false; + + var criteria = this._conditions; + doc = this._updateForExec(); + + debug('update', this._collection.collectionName, criteria, doc, options); + callback = this._wrapCallback('update', callback, { + conditions: criteria + , doc: doc + , options: options + }); + + this._collection.update(criteria, doc, options, utils.tick(callback)); + + return this; +} + +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * mquery(collection).remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. + * + * // not executed + * var query = mquery(collection).remove({ name: 'Anne Murray' }) + * + * // executed + * mquery(collection).remove({ name: 'Anne Murray' }, callback) + * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.remove = function (criteria, callback) { + this.op = 'remove'; + var force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } + + if (!(force || callback)) + return this; + + var options = this._optionsForExec() + if (!callback) options.safe = false; + + var conds = this._conditions; + + debug('remove', this._collection.collectionName, conds, options); + callback = this._wrapCallback('remove', callback, { + conditions: conds + , options: options + }); + + this._collection.remove(conds, options, utils.tick(callback)); + + return this; +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - true to return the modified document rather than the original. defaults to true + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = {}; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if ('function' == typeof criteria) { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options && this.setOptions(options); + + if (!callback) return this; + return this._findAndModify('update', callback); +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = function (conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); + + if ('function' == typeof options) { + callback = options; + options = undefined; + } else if ('function' == typeof conditions) { + callback = conditions; + conditions = undefined; + } + + // apply conditions + if (Query.canMerge(conditions)) { + this.merge(conditions); + } + + // apply options + options && this.setOptions(options); + + if (!callback) return this; + + return this._findAndModify('remove', callback); +} + +/** + * _findAndModify + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ + +Query.prototype._findAndModify = function (type, callback) { + assert.equal('function', typeof callback); + + var opts = this._optionsForExec() + , self = this + , fields + , sort + , doc + + if ('remove' == type) { + opts.remove = true; + } else { + if (!('new' in opts)) opts.new = true; + if (!('upsert' in opts)) opts.upsert = false; + + doc = this._updateForExec() + if (!doc) { + if (opts.upsert) { + // still need to do the upsert to empty doc + doc = { $set: {} }; + } else { + return this.findOne(callback); + } + } + } + + var fields = this._fieldsForExec(); + if (fields) { + opts.fields = fields; + } + + var conds = this._conditions; + + debug('findAndModify', this._collection.collectionName, conds, doc, opts); + callback = this._wrapCallback('findAndModify', callback, { + conditions: conds + , doc: doc + , options: opts + }); + + this._collection + .findAndModify(conds, doc, opts, utils.tick(callback)); + + return this; +} + +/** + * Wrap callback to add tracing + * + * @param {Function} callback + * @param {Object} [queryInfo] + * @api private + */ +Query.prototype._wrapCallback = function (method, callback, queryInfo) { + var traceFunction = this._traceFunction || Query.traceFunction; + + if (traceFunction) { + queryInfo.collectionName = this._collection.collectionName; + + var traceCallback = traceFunction && + traceFunction.call(null, method, queryInfo, this); + + var startTime = new Date().getTime(); + + return function wrapperCallback (err, result) { + if (traceCallback) { + var millis = new Date().getTime() - startTime; + traceCallback.call(null, err, result, millis); + } + + if (callback) { + callback.apply(null, arguments); + } + }; + } + + return callback; +} + +/** + * Add trace function that gets called when the query is executed. + * The function will be called with (method, queryInfo, query) and + * should return a callback function which will be called + * with (err, result, millis) when the query is complete. + * + * queryInfo is an object containing: { + * collectionName: , + * conditions: , + * options: , + * doc: [document to update, if applicable] + * } + * + * NOTE: Does not trace stream queries. + * + * @param {Function} traceFunction + * @return {Query} this + * @api public + */ +Query.prototype.setTraceFunction = function (traceFunction) { + this._traceFunction = traceFunction; + return this; +} + +/** + * Executes the query + * + * ####Examples + * + * query.exec(); + * query.exec(callback); + * query.exec('update'); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @api public + */ + +Query.prototype.exec = function exec (op, callback) { + switch (typeof op) { + case 'function': + callback = op; + op = null; + break; + case 'string': + this.op = op; + break; + } + + assert.ok(this.op, "Missing query type: (find, update, etc)"); + + if ('update' == this.op || 'remove' == this.op) { + callback || (callback = true); + } + + this[this.op](callback); +} + +/** + * Returns a thunk which when called runs this.exec() + * + * The thunk receives a callback function which will be + * passed to `this.exec()` + * + * @return {Function} + * @api public + */ + +Query.prototype.thunk = function() { + var self = this; + return function(cb) { + self.exec(cb); + } +} + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + var self = this; + var promise = new Query.Promise(function(success, error) { + self.exec(function(err, val) { + self = resolve = reject = null; + if (err) return error(err); + success(val); + }); + }); + return promise.then(resolve, reject); +} + +/** + * Returns a stream for the given find query. + * + * @throws Error if operation is not a find + * @returns {Stream} Node 0.8 style + */ + +Query.prototype.stream = function(streamOptions) { + if ('find' != this.op) + throw new Error('stream() is only available for find'); + + var conds = this._conditions; + + var options = this._optionsForExec() + options.fields = this._fieldsForExec() + + debug('stream', this._collection.collectionName, conds, options, streamOptions); + + return this._collection.findStream(conds, options, streamOptions); +} + +/** + * Determines if field selection has been made. + * + * @return {Boolean} + * @api public + */ + +Query.prototype.selected = function selected () { + return !! (this._fields && Object.keys(this._fields).length > 0); +} + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * query.selectedExlusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedInclusively = function selectedInclusively () { + if (!this._fields) return false; + + var keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (0 === this._fields[key]) return false; + } + + return true; +} + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExlusively() // false + * query.select('-name') + * query.selectedExlusively() // true + * query.selectedInclusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedExclusively = function selectedExclusively () { + if (!this._fields) return false; + + var keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (0 === this._fields[key]) return true; + } + + return false; +} + +/** + * Merges `doc` with the current update object. + * + * @param {Object} doc + */ + +Query.prototype._mergeUpdate = function (doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +} + +/** + * Returns default options. + * + * @return {Object} + * @api private + */ + +Query.prototype._optionsForExec = function () { + var options = utils.clone(this.options, { retainKeyOrder: true }); + return options; +} + +/** + * Returns fields selection for this query. + * + * @return {Object} + * @api private + */ + +Query.prototype._fieldsForExec = function () { + return utils.clone(this._fields); +} + +/** + * Return an update document with corrected $set operations. + * + * @api private + */ + +Query.prototype._updateForExec = function () { + var update = utils.clone(this._update, { retainKeyOrder: true }) + , ops = utils.keys(update) + , i = ops.length + , ret = {} + , hasKeys + , val + + while (i--) { + var op = ops[i]; + + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } + + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = update[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } + + return ret; +} + +/** + * Make sure _path is set. + * + * @parmam {String} method + */ + +Query.prototype._ensurePath = function (method) { + if (!this._path) { + var msg = method + '() must be used after where() ' + + 'when called with these arguments' + throw new Error(msg); + } +} + +/*! + * Permissions + */ + +Query.permissions = require('./permissions'); + +Query._isPermitted = function (a, b) { + var denied = Query.permissions[b]; + if (!denied) return true; + return true !== denied[a]; +} + +Query.prototype._validate = function (action) { + var fail; + var validator; + + if (undefined === action) { + + validator = Query.permissions[this.op]; + if ('function' != typeof validator) return true; + + fail = validator(this); + + } else if (!Query._isPermitted(action, this.op)) { + fail = action; + } + + if (fail) { + throw new Error(fail + ' cannot be used with ' + this.op); + } +} + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @param {Object} conds + * @return {Boolean} + */ + +Query.canMerge = function (conds) { + return conds instanceof Query || utils.isObject(conds); +} + +/** + * Set a trace function that will get called whenever a + * query is executed. + * + * See `setTraceFunction()` for details. + * + * @param {Object} conds + * @return {Boolean} + */ +Query.setGlobalTraceFunction = function (traceFunction) { + Query.traceFunction = traceFunction; +} + +/*! + * Exports. + */ + +Query.utils = utils; +Query.env = require('./env') +Query.Collection = require('./collection'); +Query.BaseCollection = require('./collection/collection'); +Query.Promise = require('bluebird'); +module.exports = exports = Query; + +// TODO +// test utils + diff --git a/node_modules/mongoose/node_modules/mquery/lib/permissions.js b/node_modules/mongoose/node_modules/mquery/lib/permissions.js new file mode 100644 index 0000000..5008a97 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/permissions.js @@ -0,0 +1,90 @@ +'use strict'; + +var denied = exports; + +denied.distinct = function (self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice' + } + + var keys = Object.keys(denied.distinct); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.distinct.select = +denied.distinct.slice = +denied.distinct.sort = +denied.distinct.limit = +denied.distinct.skip = +denied.distinct.batchSize = +denied.distinct.comment = +denied.distinct.maxScan = +denied.distinct.snapshot = +denied.distinct.hint = +denied.distinct.tailable = true; + + +// aggregation integration + + +denied.findOneAndUpdate = +denied.findOneAndRemove = function (self) { + var keys = Object.keys(denied.findOneAndUpdate); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +} +denied.findOneAndUpdate.limit = +denied.findOneAndUpdate.skip = +denied.findOneAndUpdate.batchSize = +denied.findOneAndUpdate.maxScan = +denied.findOneAndUpdate.snapshot = +denied.findOneAndUpdate.hint = +denied.findOneAndUpdate.tailable = +denied.findOneAndUpdate.comment = true; + + +denied.count = function (self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice' + } + + var keys = Object.keys(denied.count); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +} + +denied.count.select = +denied.count.slice = +denied.count.sort = +denied.count.batchSize = +denied.count.comment = +denied.count.maxScan = +denied.count.snapshot = +denied.count.tailable = true; diff --git a/node_modules/mongoose/node_modules/mquery/lib/utils.js b/node_modules/mongoose/node_modules/mquery/lib/utils.js new file mode 100644 index 0000000..6707ce2 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/lib/utils.js @@ -0,0 +1,331 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +var RegExpClone = require('regexp-clone') + +/** + * Clones objects + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ + +var clone = exports.clone = function clone (obj, options) { + if (obj === undefined || obj === null) + return obj; + + if (Array.isArray(obj)) + return exports.cloneArray(obj, options); + + if (obj.constructor) { + if (/ObjectI[dD]$/.test(obj.constructor.name)) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.id); + } + + if ('ReadPreference' === obj._type && obj.isValid && obj.toObject) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.mode, clone(obj.tags, options)); + } + + if ('Binary' == obj._bsontype && obj.buffer && obj.value) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.value(true), obj.sub_type); + } + + if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) + return new obj.constructor(+obj); + + if ('RegExp' === obj.constructor.name) + return RegExpClone(obj); + + if ('Buffer' === obj.constructor.name) + return exports.cloneBuffer(obj); + } + + if (isObject(obj)) + return exports.cloneObject(obj, options); + + if (obj.valueOf) + return obj.valueOf(); +}; + +/*! + * ignore + */ + +var cloneObject = exports.cloneObject = function cloneObject (obj, options) { + var retainKeyOrder = options && options.retainKeyOrder + , minimize = options && options.minimize + , ret = {} + , hasKeys + , keys + , val + , k + , i + + if (retainKeyOrder) { + for (k in obj) { + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } else { + // faster + + keys = Object.keys(obj); + i = keys.length; + + while (i--) { + k = keys[i]; + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + if (!hasKeys) hasKeys = true; + ret[k] = val; + } + } + } + + return minimize + ? hasKeys && ret + : ret; +}; + +var cloneArray = exports.cloneArray = function cloneArray (arr, options) { + var ret = []; + for (var i = 0, l = arr.length; i < l; i++) + ret.push(clone(arr[i], options)); + return ret; +}; + +/** + * process.nextTick helper. + * + * Wraps the given `callback` in a try/catch. If an error is + * caught it will be thrown on nextTick. + * + * node-mongodb-native had a habit of state corruption when + * an error was immediately thrown from within a collection + * method (find, update, etc) callback. + * + * @param {Function} [callback] + * @api private + */ + +var tick = exports.tick = function tick (callback) { + if ('function' !== typeof callback) return; + return function () { + // callbacks should always be fired on the next + // turn of the event loop. A side benefit is + // errors thrown from executing the callback + // will not cause drivers state to be corrupted + // which has historically been a problem. + var args = arguments; + soon(function(){ + callback.apply(this, args); + }); + } +} + +/** + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +var merge = exports.merge = function merge (to, from) { + var keys = Object.keys(from) + , i = keys.length + , key + + while (i--) { + key = keys[i]; + if ('undefined' === typeof to[key]) { + to[key] = from[key]; + } else { + if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } else { + to[key] = from[key]; + } + } + } +} + +/** + * Same as merge but clones the assigned values. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +var mergeClone = exports.mergeClone = function mergeClone (to, from) { + var keys = Object.keys(from) + , i = keys.length + , key + + while (i--) { + key = keys[i]; + if ('undefined' === typeof to[key]) { + // make sure to retain key order here because of a bug handling the $each + // operator in mongodb 2.4.4 + to[key] = clone(from[key], { retainKeyOrder : 1}); + } else { + if (exports.isObject(from[key])) { + mergeClone(to[key], from[key]); + } else { + // make sure to retain key order here because of a bug handling the + // $each operator in mongodb 2.4.4 + to[key] = clone(from[key], { retainKeyOrder : 1}); + } + } + } +} + +/** + * Read pref helper (mongo 2.2 drivers support this) + * + * Allows using aliases instead of full preference names: + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * @param {String} pref + */ + +exports.readPref = function readPref (pref) { + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return pref; +} + +/** + * Object.prototype.toString.call helper + */ + +var _toString = Object.prototype.toString; +var toString = exports.toString = function (arg) { + return _toString.call(arg); +} + +/** + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @return {Boolean} + */ + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == exports.toString(arg); +} + +/** + * Determines if `arg` is an array. + * + * @param {Object} + * @return {Boolean} + * @see nodejs utils + */ + +var isArray = exports.isArray = function (arg) { + return Array.isArray(arg) || + 'object' == typeof arg && '[object Array]' == exports.toString(arg); +} + +/** + * Object.keys helper + */ + +exports.keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) if (obj.hasOwnProperty(k)) { + keys.push(k); + } + return keys; +} + +/** + * Basic Object.create polyfill. + * Only one argument is supported. + * + * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create + */ + +exports.create = 'function' == typeof Object.create + ? Object.create + : create; + +function create (proto) { + if (arguments.length > 1) { + throw new Error("Adding properties is not supported") + } + + function F () {} + F.prototype = proto; + return new F; +} + +/** + * inheritance + */ + +exports.inherits = function (ctor, superCtor) { + ctor.prototype = exports.create(superCtor.prototype); + ctor.prototype.constructor = ctor; +} + +/** + * nextTick helper + * compat with node 0.10 which behaves differently than previous versions + */ + +var soon = exports.soon = 'function' == typeof setImmediate + ? setImmediate + : process.nextTick; + +/** + * Clones the contents of a buffer. + * + * @param {Buffer} buff + * @return {Buffer} + */ + +exports.cloneBuffer = function (buff) { + var dupe = new Buffer(buff.length); + buff.copy(dupe, 0, 0, buff.length); + return dupe; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..a3966cf --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +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/mongoose/node_modules/mquery/node_modules/bluebird/README.md b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md new file mode 100644 index 0000000..3f16e21 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md @@ -0,0 +1,676 @@ + + 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) + + +#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) +- 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](http://spion.github.io/promise-nuggets/) + - [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 + +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 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. + +#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/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..1171c14 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md @@ -0,0 +1,1538 @@ +## 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/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..edc8bbd --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,4693 @@ +/* @preserve + * 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. + * + */ +/** + * bluebird build version 2.9.9 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, progress, 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._withDomain = function(fn) { + if (_process !== undefined && + _process.domain != null && + !fn.domain) { + fn = _process.domain.bind(fn); + } + return fn; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + fn = this._withDomain(fn); + 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"); + } +}; + +Async.prototype.invokeLater = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.invoke = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.settlePromises = function(promise) { + this._normalQueue._pushOne(promise); + 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}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +function returnThis() { return this.value; } +function throwThis() { throw this.reason; } +function awaitBindingThenResolve(value) { + return this._then(returnThis, null, null, {value: value}, undefined); +} +function awaitBindingThenReject(reason) { + return this._then(throwThis, throwThis, null, {reason: reason}, undefined); +} +function setBinding(binding) { this._setBoundTo(binding); } +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + if (maybePromise instanceof Promise) { + if (maybePromise.isFulfilled()) { + thisArg = maybePromise.value(); + } else if (maybePromise.isRejected()) { + return Promise.reject(maybePromise.reason()); + } else { + var ret = this.then(); + var parent = ret; + ret = ret._then(awaitBindingThenResolve, + awaitBindingThenReject, + null, maybePromise, undefined); + maybePromise._then(setBinding, ret._reject, null, ret, null); + if (!ret._cancellable()) ret._setPendingCancellationParent(parent); + return ret; + } + } + var ret = this.then(); + ret._setBoundTo(thisArg); + return ret; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; + +Promise.prototype._setPendingCancellationParent = function(parent) { + this._settledValue = parent; +}; + +Promise.prototype._pendingCancellationParent = function() { + if (this.isPending() && this._settledValue !== undefined) { + var ret = this._settledValue; + ret.cancellable(); + this._settledValue = undefined; + return ret; + } +}; + +Promise.prototype._setIsBound = function () { + this._bitField = this._bitField | 131072; +}; + +Promise.prototype._unsetIsBound = function () { + this._bitField = this._bitField & (~131072); +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.prototype._setIsMigratingBinding = function () { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._unsetIsMigratingBinding = function () { + this._bitField = this._bitField & (~8388608); +}; + +Promise.prototype._isMigratingBinding = function () { + return (this._bitField & 8388608) === 8388608; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj === undefined) { + if (this._isBound()) { + this._boundTo = undefined; + } + this._unsetIsBound(); + } else { + this._setIsBound(); + this._boundTo = obj; + } +}; +}; + +},{}],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; + this._setCancellable(); + this._cancellationParent = this._pendingCancellationParent(); + 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); + error.stack = reconstructStack(message, stacks); + 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) { + 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._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")); + +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); + error.stack = parsed.message + "\n" + parsed.stack.join("\n"); + 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(); +}; + +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; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; + +},{"./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 wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, 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._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) { + 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 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(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + this._init$(undefined, -2); +} +util.inherits(MappingPromiseArray, PromiseArray); + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + 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(); +}; + + +}; + +},{"./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._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.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 (!haveInternalData) { + ret._setIsMigrated(); + if (receiver === undefined) { + ret._setIsMigratingBinding(); + receiver = this; + } + } + } + + 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(); + if (receiver === undefined) { + receiver = follower; + promise._setIsMigratingBinding(); + } + } + 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 = util.canAttachTrace(reason) && + typeof trace.stack === "string" && trace.stack.length > 0; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, trace === reason ? 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); + if (isPromise && promise._isMigratingBinding()) { + promise._unsetIsMigratingBinding(); + receiver = receiver._boundTo; + } + + 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_("./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_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./cancel.js')(Promise); +_dereq_('./promisify.js')(Promise, INTERNAL); +_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_('./call_get.js')(Promise); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./progress.js')(Promise, PromiseArray); +_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 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 noCopyPropsPattern = + /^(?:length|name|arguments|caller|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +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", + "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\ + 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 + ); +}; +} + +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; + } + 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; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + 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 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; + this._callback = fn; + this._accum = accum; + if (!rejected) this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + 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; +} +else if (typeof MutationObserver !== "undefined") { + 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 setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} +else { + schedule = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + }; +} +module.exports = schedule; + +},{"./util.js":38}],32:[function(_dereq_,module,exports){ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util.js"); + +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); + } +}; + +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; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + 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; + if (typeof message !== "string") { + message = "operation timed out"; + } + var 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"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } 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 = fn.apply(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 { + return tryCatchTarget.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; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + 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) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027*/ + function f() {} + f.prototype = obj; + return f; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +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)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +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, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object 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/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..98cafed --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * 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. + * + */ +/** + * bluebird build version 2.9.9 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, progress, 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._withDomain=function(t){return void 0===a||null==a.domain||t.domain||(t=a.domain.bind(t)),t},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),t=this._withDomain(t),"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")}},r.prototype.invokeLater=function(t,e,r){t=this._withDomain(t),this._lateQueue.push(t,e,r),this._queueTick()},r.prototype.invokeFirst=function(t,e,r){t=this._withDomain(t),this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype.invoke=function(t,e,r){t=this._withDomain(t),this._normalQueue.push(t,e,r),this._queueTick()},r.prototype.settlePromises=function(t){this._normalQueue._pushOne(t),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=n},{"./queue.js":28,"./schedule.js":31}],3:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){return this.value}function i(){throw this.reason}function o(t){return this._then(n,null,null,{value:t},void 0)}function s(t){return this._then(i,i,null,{reason:t},void 0)}function a(t){this._setBoundTo(t)}t.prototype.bind=function(e){var n=r(e);if(n instanceof t){if(!n.isFulfilled()){if(n.isRejected())return t.reject(n.reason());var i=this.then(),u=i;return i=i._then(o,s,null,n,void 0),n._then(a,i._reject,null,i,null),i._cancellable()||i._setPendingCancellationParent(u),i}e=n.value()}var i=this.then();return i._setBoundTo(e),i},t.bind=function(e,r){return t.resolve(r).bind(e)},t.prototype._setPendingCancellationParent=function(t){this._settledValue=t},t.prototype._pendingCancellationParent=function(){if(this.isPending()&&void 0!==this._settledValue){var t=this._settledValue;return t.cancellable(),this._settledValue=void 0,t}},t.prototype._setIsBound=function(){this._bitField=131072|this._bitField},t.prototype._unsetIsBound=function(){this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.prototype._setIsMigratingBinding=function(){this._bitField=8388608|this._bitField},t.prototype._unsetIsMigratingBinding=function(){this._bitField=-8388609&this._bitField},t.prototype._isMigratingBinding=function(){return 8388608===(8388608&this._bitField)},t.prototype._setBoundTo=function(t){void 0===t?(this._isBound()&&(this._boundTo=void 0),this._unsetIsBound()):(this._setIsBound(),this._boundTo=t)}}},{}],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:(this._setCancellable(),this._cancellationParent=this._pendingCancellationParent(),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),t.stack=r(a,u),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 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);t.stack=i.message+"\n"+i.stack.join("\n"),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()},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?[]:p,this._init$(void 0,-2)}function a(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 u=t("./util.js"),c=u.tryCatch,l=u.errorObj,h={},p=[];u.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]===h){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,p=this._promise._boundTo;this._promise._pushContext();var f=c(u).call(p,t,r,o);if(this._promise._popContext(),f===l)return this._reject(f.e);var _=i(f,this._promise);if(_ instanceof e){if(_=_._target(),_._isPending())return a>=1&&this._inFlight++,n[r]=h,_._proxyPromiseArray(this,r);if(!_._isFulfilled())return this._reject(_._reason());f=_._value()}n[r]=f}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"):a(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"):a(t,e,r,i).promise()}}},{"./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.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&&(s||(u._setIsMigrated(),void 0===i&&(u._setIsMigratingBinding(),i=this)));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(),void 0===a&&(a=t,s._setIsMigratingBinding())),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=s.canAttachTrace(t)&&"string"==typeof n.stack&&n.stack.length>0;this._attachExtraTrace(n,e?i:!1),this._reject(t,n===t?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);n&&r._isMigratingBinding()&&(r._unsetIsMigratingBinding(),u=u._boundTo),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("./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("./using.js")(e,o,f,y),t("./generators.js")(e,o,l,f),t("./nodeify.js")(e),t("./cancel.js")(e),t("./promisify.js")(e,l),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("./call_get.js")(e),t("./some.js")(e,_,o),t("./progress.js")(e,_),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|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 a=i(n,this._promise),u=!1,c=a instanceof e;c&&(a=a._target(),a._isPending()?a._proxyPromiseArray(this,-1):a._isFulfilled()?(n=a._value(),this._gotAccum=!0):(this._reject(a._reason()),u=!0)),c||this._zerothIsAccum||(this._gotAccum=!0),this._callback=r,this._accum=n,u||this._init$(void 0,-5)}function a(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 u=t("./util.js"),c=u.tryCatch,l=u.errorObj;u.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,h=this._gotAccum,p=this._valuesPhase;if(!p)for(p=this._valuesPhase=new Array(s),o=0;s>o;++o)p[o]=0;if(o=p[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=h=!0,p[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=h=!0):0===o?p[r]=1:(p[r]=2,this._accum=t),h){for(var f,_=this._callback,d=this._promise._boundTo,v=this._reducingIndex;s>v;++v)if(o=p[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),f=c(_).call(d,t,v,s)):f=c(_).call(d,this._accum,t,v,s),this._promise._popContext(),f===l)return this._reject(f.e);var y=i(f,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return p[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 a(this,t,e,null)},e.reduce=function(t,e,r,n){return a(t,e,r,n)}}},{"./util.js":38}],31:[function(t,e){"use strict";var r;if(t("./util.js").isNode){var n=process.versions.node.split(".").map(Number);r=0===n[0]&&n[1]>10||n[0]>0?global.setImmediate:process.nextTick}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 setTimeout?function(t){setTimeout(t,0)}:function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\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 C.apply(this,arguments)}catch(t){return F.e=t,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);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(){}return e.prototype=t,e}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;i 0; +}; + +Async.prototype._withDomain = function(fn) { + if (_process !== undefined && + _process.domain != null && + !fn.domain) { + fn = _process.domain.bind(fn); + } + return fn; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + fn = this._withDomain(fn); + 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"); + } +}; + +Async.prototype.invokeLater = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.invoke = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.settlePromises = function(promise) { + this._normalQueue._pushOne(promise); + 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; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js new file mode 100644 index 0000000..a026d1d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js @@ -0,0 +1,87 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +function returnThis() { return this.value; } +function throwThis() { throw this.reason; } +function awaitBindingThenResolve(value) { + return this._then(returnThis, null, null, {value: value}, undefined); +} +function awaitBindingThenReject(reason) { + return this._then(throwThis, throwThis, null, {reason: reason}, undefined); +} +function setBinding(binding) { this._setBoundTo(binding); } +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + if (maybePromise instanceof Promise) { + if (maybePromise.isFulfilled()) { + thisArg = maybePromise.value(); + } else if (maybePromise.isRejected()) { + return Promise.reject(maybePromise.reason()); + } else { + var ret = this.then(); + var parent = ret; + ret = ret._then(awaitBindingThenResolve, + awaitBindingThenReject, + null, maybePromise, undefined); + maybePromise._then(setBinding, ret._reject, null, ret, null); + if (!ret._cancellable()) ret._setPendingCancellationParent(parent); + return ret; + } + } + var ret = this.then(); + ret._setBoundTo(thisArg); + return ret; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; + +Promise.prototype._setPendingCancellationParent = function(parent) { + this._settledValue = parent; +}; + +Promise.prototype._pendingCancellationParent = function() { + if (this.isPending() && this._settledValue !== undefined) { + var ret = this._settledValue; + ret.cancellable(); + this._settledValue = undefined; + return ret; + } +}; + +Promise.prototype._setIsBound = function () { + this._bitField = this._bitField | 131072; +}; + +Promise.prototype._unsetIsBound = function () { + this._bitField = this._bitField & (~131072); +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.prototype._setIsMigratingBinding = function () { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._unsetIsMigratingBinding = function () { + this._bitField = this._bitField & (~8388608); +}; + +Promise.prototype._isMigratingBinding = function () { + return (this._bitField & 8388608) === 8388608; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj === undefined) { + if (this._isBound()) { + this._boundTo = undefined; + } + this._unsetIsBound(); + } else { + this._setIsBound(); + this._boundTo = obj; + } +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js new file mode 100644 index 0000000..ed6226e --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/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.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js new file mode 100644 index 0000000..62c166d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/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.js"); +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/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js new file mode 100644 index 0000000..b4d8855 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function(Promise) { +var errors = require("./errors.js"); +var async = require("./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; + this._setCancellable(); + this._cancellationParent = this._pendingCancellationParent(); + 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; +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js new file mode 100644 index 0000000..60714e1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js @@ -0,0 +1,492 @@ +"use strict"; +module.exports = function() { +var async = require("./async.js"); +var util = require("./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); + error.stack = reconstructStack(message, stacks); + 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) { + 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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js new file mode 100644 index 0000000..040f057 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util.js"); +var errors = require("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = require("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = 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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js new file mode 100644 index 0000000..ccd7702 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js @@ -0,0 +1,38 @@ +"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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js new file mode 100644 index 0000000..4af4b5d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js @@ -0,0 +1,139 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = require("./async.js"); +var Warning = require("./errors.js").Warning; +var util = require("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +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); + error.stack = parsed.message + "\n" + parsed.stack.join("\n"); + 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(); +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js new file mode 100644 index 0000000..c61a367 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js @@ -0,0 +1,54 @@ +"use strict"; +var util = require("./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; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js new file mode 100644 index 0000000..a37e22c --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js @@ -0,0 +1,12 @@ +"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); +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js new file mode 100644 index 0000000..c334bb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js @@ -0,0 +1,111 @@ +"use strict"; +var es5 = require("./es5.js"); +var Objectfreeze = es5.freeze; +var util = require("./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 +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/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/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/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/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js new file mode 100644 index 0000000..ed84a2a --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = require("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, 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._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) { + 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); +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js new file mode 100644 index 0000000..4c0568d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js @@ -0,0 +1,136 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = require("./errors.js"); +var TypeError = errors.TypeError; +var util = require("./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; +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js new file mode 100644 index 0000000..cf33eb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js @@ -0,0 +1,107 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util.js"); +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 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 (!false) { + 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; +}; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js new file mode 100644 index 0000000..6201217 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js @@ -0,0 +1,129 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var util = require("./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(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + this._init$(undefined, -2); +} +util.inherits(MappingPromiseArray, PromiseArray); + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + 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(); +}; + + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js new file mode 100644 index 0000000..3d3eeb1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js @@ -0,0 +1,44 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./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); + } +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js new file mode 100644 index 0000000..4bbafc4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js @@ -0,0 +1,57 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util.js"); +var async = require("./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.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/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js new file mode 100644 index 0000000..2e3e95e --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = require("./util.js"); +var async = require("./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); + } + } +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js new file mode 100644 index 0000000..3c7e5ef --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js @@ -0,0 +1,715 @@ +"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 = require("./util.js"); +var async = require("./async.js"); +var errors = require("./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 = require("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = require("./captured_trace.js")(); +var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + require("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = require("./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 (!haveInternalData) { + ret._setIsMigrated(); + if (receiver === undefined) { + ret._setIsMigratingBinding(); + receiver = this; + } + } + } + + 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(); + if (receiver === undefined) { + receiver = follower; + promise._setIsMigratingBinding(); + } + } + 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 = util.canAttachTrace(reason) && + typeof trace.stack === "string" && trace.stack.length > 0; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, trace === reason ? 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); + if (isPromise && promise._isMigratingBinding()) { + promise._unsetIsMigratingBinding(); + receiver = receiver._boundTo; + } + + 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; +require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +require("./direct_resolve.js")(Promise); +require("./synchronous_inspection.js")(Promise); +require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +require('./nodeify.js')(Promise); +require('./cancel.js')(Promise); +require('./promisify.js')(Promise, INTERNAL); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./settle.js')(Promise, PromiseArray); +require('./call_get.js')(Promise); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./progress.js')(Promise, PromiseArray); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./timers.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._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; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js new file mode 100644 index 0000000..6dac866 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = require("./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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js new file mode 100644 index 0000000..b180a32 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js @@ -0,0 +1,123 @@ +"use strict"; +var util = require("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = require("./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; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js new file mode 100644 index 0000000..8bcfc8e --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js @@ -0,0 +1,291 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util.js"); +var nodebackForPromise = require("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +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 (!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) { + 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", + "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\ + 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 + ); +}; +} + +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; + } + 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; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + 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); +}; +}; + diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js new file mode 100644 index 0000000..d6f9e64 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js @@ -0,0 +1,79 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var isObject = util.isObject; +var es5 = require("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + 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); +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/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/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js new file mode 100644 index 0000000..30e7bb0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = require("./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); +}; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js new file mode 100644 index 0000000..543bef3 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var util = require("./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; + this._callback = fn; + this._accum = accum; + if (!rejected) this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + 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; +} +else if (typeof MutationObserver !== "undefined") { + 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 setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} +else { + schedule = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + }; +} +module.exports = schedule; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js new file mode 100644 index 0000000..f9299c2 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js @@ -0,0 +1,40 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= 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(); +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js new file mode 100644 index 0000000..f3968cf --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util.js"); +var RangeError = require("./errors.js").RangeError; +var AggregateError = require("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + 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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js new file mode 100644 index 0000000..7aac149 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js @@ -0,0 +1,94 @@ +"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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js new file mode 100644 index 0000000..c858f86 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js @@ -0,0 +1,89 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./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; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + 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; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js new file mode 100644 index 0000000..ecf1b57 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var 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); +}; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js new file mode 100644 index 0000000..4038711 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js @@ -0,0 +1,202 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = require("./errors.js").TypeError; + var inherits = require("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + 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"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } 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 = fn.apply(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(); + }; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js new file mode 100644 index 0000000..54d7a85 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js @@ -0,0 +1,276 @@ +"use strict"; +var es5 = require("./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 { + return tryCatchTarget.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; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + 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) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027*/ + function f() {} + f.prototype = obj; + return f; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +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)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +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, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json new file mode 100644 index 0000000..74ba025 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json @@ -0,0 +1,97 @@ +{ + "name": "bluebird", + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "version": "2.9.9", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "scripts": { + "lint": "node scripts/jshint.js", + "test": "node tools/test.js", + "istanbul": "istanbul", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify" + }, + "homepage": "https://github.com/petkaantonov/bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "license": "MIT", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "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", + "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" + }, + "main": "./js/main/bluebird.js", + "browser": "./js/browser/bluebird.js", + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "LICENSE", + "zalgo.js" + ], + "gitHead": "6c202e8c8d8becaea8e554efce5aeebef038e216", + "_id": "bluebird@2.9.9", + "_shasum": "61a26904d43d7f6b19dff7ed917dbc92452ad6d3", + "_from": "bluebird@2.9.9", + "_npmVersion": "2.4.1", + "_nodeVersion": "1.1.0", + "_npmUser": { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + }, + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "dist": { + "shasum": "61a26904d43d7f6b19dff7ed917dbc92452ad6d3", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.9.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md new file mode 100644 index 0000000..c5a34e8 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md @@ -0,0 +1,115 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +``` +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_ + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + a('doing some work'); +}, 1200); +``` + +## License + +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> + +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/mongoose/node_modules/mquery/node_modules/debug/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js new file mode 100644 index 0000000..509dc0d --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js @@ -0,0 +1,137 @@ + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + if (!debug.enabled(name)) return function(){}; + + return function(fmt){ + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (debug[name] || curr); + debug[name] = curr; + + fmt = name + + ' ' + + fmt + + ' +' + debug.humanize(ms); + + // This hackery is required for IE8 + // where `console.log` doesn't have 'apply' + window.console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); + } +} + +/** + * The currently active debug mode names. + */ + +debug.names = []; +debug.skips = []; + +/** + * Enables a debug mode by name. This can include modes + * separated by a colon and wildcards. + * + * @param {String} name + * @api public + */ + +debug.enable = function(name) { + try { + localStorage.debug = name; + } catch(e){} + + var split = (name || '').split(/[\s,]+/) + , len = split.length; + + for (var i = 0; i < len; i++) { + name = split[i].replace('*', '.*?'); + if (name[0] === '-') { + debug.skips.push(new RegExp('^' + name.substr(1) + '$')); + } + else { + debug.names.push(new RegExp('^' + name + '$')); + } + } +}; + +/** + * Disable debug output. + * + * @api public + */ + +debug.disable = function(){ + debug.enable(''); +}; + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +debug.humanize = function(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +}; + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +debug.enabled = function(name) { + for (var i = 0, len = debug.skips.length; i < len; i++) { + if (debug.skips[i].test(name)) { + return false; + } + } + for (var i = 0, len = debug.names.length; i < len; i++) { + if (debug.names[i].test(name)) { + return true; + } + } + return false; +}; + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +// persist + +try { + if (window.localStorage) debug.enable(localStorage.debug); +} catch(e){} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js new file mode 100644 index 0000000..e02c13b --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js @@ -0,0 +1,5 @@ +if ('undefined' == typeof window) { + module.exports = require('./lib/debug'); +} else { + module.exports = require('./debug'); +} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js new file mode 100644 index 0000000..3b0a918 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js @@ -0,0 +1,147 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Enabled debuggers. + */ + +var names = [] + , skips = []; + +(process.env.DEBUG || '') + .split(/[\s,]+/) + .forEach(function(name){ + name = name.replace('*', '.*?'); + if (name[0] === '-') { + skips.push(new RegExp('^' + name.substr(1) + '$')); + } else { + names.push(new RegExp('^' + name + '$')); + } + }); + +/** + * Colors. + */ + +var colors = [6, 2, 3, 4, 5, 1]; + +/** + * Previous debug() call. + */ + +var prev = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Is stdout a TTY? Colored output is disabled when `true`. + */ + +var isatty = tty.isatty(2); + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function color() { + return colors[prevColor++ % colors.length]; +} + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +function humanize(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +} + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + function disabled(){} + disabled.enabled = false; + + var match = skips.some(function(re){ + return re.test(name); + }); + + if (match) return disabled; + + match = names.some(function(re){ + return re.test(name); + }); + + if (!match) return disabled; + var c = color(); + + function colored(fmt) { + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (prev[name] || curr); + prev[name] = curr; + + fmt = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[3' + c + 'm\u001b[90m' + + fmt + '\u001b[3' + c + 'm' + + ' +' + humanize(ms) + '\u001b[0m'; + + console.error.apply(this, arguments); + } + + function plain(fmt) { + fmt = coerce(fmt); + + fmt = new Date().toUTCString() + + ' ' + name + ' ' + fmt; + console.error.apply(this, arguments); + } + + colored.enabled = plain.enabled = true; + + return isatty || process.env.DEBUG_COLORS + ? colored + : plain; +} + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json new file mode 100644 index 0000000..8a959a5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json @@ -0,0 +1,62 @@ +{ + "name": "debug", + "version": "0.7.4", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*" + }, + "main": "lib/debug.js", + "browser": "./debug.js", + "engines": { + "node": "*" + }, + "files": [ + "lib/debug.js", + "debug.js", + "index.js" + ], + "component": { + "scripts": { + "debug/index.js": "index.js", + "debug/debug.js": "debug.js" + } + }, + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@0.7.4", + "dist": { + "shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", + "tarball": "http://registry.npmjs.org/debug/-/debug-0.7.4.tgz" + }, + "_from": "debug@0.7.4", + "_npmVersion": "1.3.13", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", + "_resolved": "https://registry.npmjs.org/debug/-/debug-0.7.4.tgz" +} diff --git a/node_modules/mongoose/node_modules/mquery/package.json b/node_modules/mongoose/node_modules/mquery/package.json new file mode 100644 index 0000000..1e5bde6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/package.json @@ -0,0 +1,67 @@ +{ + "name": "mquery", + "version": "1.5.1", + "description": "Expressive query building for MongoDB", + "main": "lib/mquery.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mquery.git" + }, + "dependencies": { + "bluebird": "2.9.9", + "debug": "0.7.4", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "devDependencies": { + "mongodb": "1.4.12", + "mocha": "1.9.x", + "istanbul": "0.3.2" + }, + "bugs": { + "url": "https://github.com/aheckmann/mquery/issues/new" + }, + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "keywords": [ + "mongodb", + "query", + "builder" + ], + "homepage": "https://github.com/aheckmann/mquery/", + "gitHead": "3afc81bed9af1cbccce830630052ef670de522a4", + "_id": "mquery@1.5.1", + "_shasum": "f60bbf8a1e0ec6ef3ff1f22123b8b03f83a91625", + "_from": "mquery@1.5.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "ebensing", + "email": "ebensing38@gmail.com" + }, + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "dist": { + "shasum": "f60bbf8a1e0ec6ef3ff1f22123b8b03f83a91625", + "tarball": "http://registry.npmjs.org/mquery/-/mquery-1.5.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mquery/-/mquery-1.5.1.tgz" +} diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/node_modules/mongoose/node_modules/mquery/test/collection/browser.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/node_modules/mongoose/node_modules/mquery/test/collection/node.js new file mode 100644 index 0000000..43f446e --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/test/collection/node.js @@ -0,0 +1,29 @@ + +var assert = require('assert') +var slice = require('sliced') +var mongo = require('mongodb') +var utils = require('../../').utils; + +var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; +var db; + +exports.getCollection = function (cb) { + mongo.Db.connect(uri, function (err, db_) { + assert.ifError(err); + db = db_; + + var collection = db.collection('stuff'); + collection.opts.safe = true; + + // clean test db before starting + db.dropDatabase(function () { + cb(null, collection); + }); + }) +} + +exports.dropCollection = function (cb) { + db.dropDatabase(function () { + db.close(cb); + }) +} diff --git a/node_modules/mongoose/node_modules/mquery/test/env.js b/node_modules/mongoose/node_modules/mquery/test/env.js new file mode 100644 index 0000000..9b9b80b --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/test/env.js @@ -0,0 +1,20 @@ + +var assert = require('assert') +var env = require('../').env; + +console.log('environment: %s', env.type); + +var col; +switch (env.type) { + case 'node': + col = require('./collection/node'); + break; + case 'mongo': + col = require('./collection/mongo'); + case 'browser': + col = require('./collection/browser'); + default: + throw new Error('missing collection implementation for environment: ' + env.type); +} + +module.exports = exports = col; diff --git a/node_modules/mongoose/node_modules/mquery/test/index.js b/node_modules/mongoose/node_modules/mquery/test/index.js new file mode 100644 index 0000000..f6c1050 --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/test/index.js @@ -0,0 +1,2858 @@ +var mquery = require('../'); +var assert = require('assert'); + +describe('mquery', function(){ + var col; + + before(function(done){ + // get the env specific collection interface + require('./env').getCollection(function (err, collection) { + assert.ifError(err); + col = collection; + done(); + }); + }) + + after(function(done){ + require('./env').dropCollection(done); + }) + + describe('mquery', function(){ + it('is a function', function(){ + assert.equal('function', typeof mquery); + }) + it('creates instances with the `new` keyword', function(){ + assert.ok(mquery() instanceof mquery); + }) + describe('defaults', function(){ + it('are set', function(){ + var m = mquery(); + assert.strictEqual(undefined, m.op); + assert.deepEqual({}, m.options); + }) + }) + describe('criteria', function(){ + it('if collection-like is used as collection', function(){ + var m = mquery(col); + assert.equal(col, m._collection.collection); + }) + it('non-collection-like is used as criteria', function(){ + var m = mquery({ works: true }); + assert.ok(!m._collection); + assert.deepEqual({ works: true }, m._conditions); + }) + }) + describe('options', function(){ + it('are merged when passed', function(){ + var m = mquery(col, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + var m = mquery({ name: 'mquery' }, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + }) + }) + }) + + describe('toConstructor', function(){ + it('creates subclasses of mquery', function(){ + var opts = { safe: { w: 'majority' }, readPreference: 'p' }; + var match = { name: 'test', count: { $gt: 101 }}; + var select = { name: 1, count: 0 } + var update = { $set: { x: true }}; + var path = 'street'; + + var q = mquery().setOptions(opts); + q.where(match); + q.select(select); + q.update(update); + q.where(path); + q.find(); + + var M = q.toConstructor(); + var m = M(); + + assert.ok(m instanceof mquery); + assert.deepEqual(opts, m.options); + assert.deepEqual(match, m._conditions); + assert.deepEqual(select, m._fields); + assert.deepEqual(update, m._update); + assert.equal(path, m._path); + assert.equal('find', m.op); + }) + }) + + describe('setOptions', function(){ + it('calls associated methods', function(){ + var m = mquery(); + assert.equal(m._collection, null); + m.setOptions({ collection: col }); + assert.equal(m._collection.collection, col); + }) + it('directly sets option when no method exists', function(){ + var m = mquery(); + assert.equal(m.options.woot, null); + m.setOptions({ woot: 'yay' }); + assert.equal(m.options.woot, 'yay'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.setOptions(); + assert.equal(m, n); + var n = m.setOptions({ x: 1 }); + assert.equal(m, n); + }) + }) + + describe('collection', function(){ + it('sets the _collection', function(){ + var m = mquery(); + m.collection(col); + assert.equal(m._collection.collection, col); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.collection(col); + assert.equal(m, n); + }) + }) + + describe('$where', function(){ + it('sets the $where condition', function(){ + var m = mquery(); + function go () {} + m.$where(go); + assert.ok(go === m._conditions.$where); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.$where('x'); + assert.equal(m, n); + }) + }) + + describe('where', function(){ + it('without arguments', function(){ + var m = mquery(); + m.where(); + assert.deepEqual({}, m._conditions); + }) + it('with non-string/object argument', function(){ + var m = mquery(); + + assert.throws(function(){ + m.where([]); + }, /path must be a string or object/); + }) + describe('with one argument', function(){ + it('that is an object', function(){ + var m = mquery(); + m.where({ name: 'flawed' }); + assert.strictEqual(m._conditions.name, 'flawed'); + }) + it('that is a query', function(){ + var m = mquery({ name: 'first' }); + var n = mquery({ name: 'changed' }); + m.where(n); + assert.strictEqual(m._conditions.name, 'changed'); + }) + it('that is a string', function(){ + var m = mquery(); + m.where('name'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, undefined); + }) + }) + it('with two arguments', function(){ + var m = mquery(); + m.where('name', 'The Great Pumpkin'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x', 'y'); + assert.equal(m, n); + var n = m.where() + assert.equal(m, n); + }) + }) + + describe('equals', function(){ + it('must be called after where()', function(){ + var m = mquery(); + assert.throws(function () { + m.equals(); + }, /must be used after where/) + }) + it('sets value of path set with where()', function(){ + var m = mquery(); + m.where('age').equals(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x').equals(3); + assert.equal(m, n); + }) + }) + + describe('or', function(){ + it('pushes onto the internal $or condition', function(){ + var m = mquery(); + m.or({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.or(arg); + assert.deepEqual(arg, m._conditions.$or) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.or(arg); + m.or({ y: 1 }) + m.or([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or) + }) + it('is chainable', function(){ + var m = mquery(); + m.or({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('nor', function(){ + it('pushes onto the internal $nor condition', function(){ + var m = mquery(); + m.nor({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.nor(arg); + assert.deepEqual(arg, m._conditions.$nor) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.nor(arg); + m.nor({ y: 1 }) + m.nor([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor) + }) + it('is chainable', function(){ + var m = mquery(); + m.nor({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('and', function(){ + it('pushes onto the internal $and condition', function(){ + var m = mquery(); + m.and({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.and(arg); + assert.deepEqual(arg, m._conditions.$and) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.and(arg); + m.and({ y: 1 }) + m.and([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and) + }) + it('is chainable', function(){ + var m = mquery(); + m.and({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions) + }) + }) + + function generalCondition (type) { + return function () { + it('accepts 2 args', function(){ + var m = mquery()[type]('count', 3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('uses previously set `where` path if 1 arg passed', function(){ + var m = mquery().where('count')[type](3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('throws if 1 arg was passed but no previous `where` was used', function(){ + assert.throws(function(){ + mquery()[type](3); + }, /must be used after where/); + }) + it('is chainable', function(){ + var m = mquery().where('count')[type](3).where('x', 8); + var check = {x: 8, count: {}}; + check.count['$' + type] = 3; + assert.deepEqual(m._conditions, check); + }) + it('overwrites previous value', function(){ + var m = mquery().where('count')[type](3)[type](8); + var check = {}; + check['$' + type] = 8; + assert.deepEqual(m._conditions.count, check); + }) + } + } + + 'gt gte lt lte ne in nin regex size maxDistance'.split(' ').forEach(function (type) { + describe(type, generalCondition(type)) + }) + + describe('mod', function () { + describe('with 1 argument', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod([30, 10]) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod([10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + describe('with 2 arguments and second is non-Array', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod('x', 10) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod(10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + it('with 2 arguments and second is an array', function(){ + var m = mquery().mod('madmen', [10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('with 3 arguments', function(){ + var m = mquery().mod('madmen', 10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('is chainable', function(){ + var m = mquery().mod('madmen', 10, 20).where('x', 8); + var check = { madmen: { $mod: [10,20] }, x: 8}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('exists', function(){ + it('with 0 args', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('name').exists(); + var check = { name: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('with 1 arg', function(){ + describe('that is boolean', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().exists('name', false); + var check = { name: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + describe('that is not boolean', function(){ + it('sets the value to `true`', function(){ + var m = mquery().where('name').exists('yummy'); + var check = { yummy: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + }) + + describe('with 2 args', function(){ + it('works', function(){ + var m = mquery().exists('yummy', false); + var check = { yummy: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + + it('is chainable', function(){ + var m = mquery().where('name').exists().find({ x: 1 }); + var check = { name: { $exists: true }, x: 1}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('elemMatch', function(){ + describe('with null/undefined first argument', function(){ + assert.throws(function () { + mquery().elemMatch(); + }, /Invalid argument/); + assert.throws(function () { + mquery().elemMatch(null); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().elemMatch('', {}); + }); + }) + + describe('with 1 argument', function(){ + it('throws if not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch([]); + }, /Invalid argument/); + }) + + describe('that is an object', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch({}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('that is a function', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch(function(){}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch(function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + }) + + describe('with 2 arguments', function(){ + describe('and the 2nd is an object', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('and the 2nd is a function', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + it('and the 2nd is not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch('comment', []); + }, /Invalid argument/); + }) + }) + }) + + describe('within', function(){ + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').within(), m); + }) + describe('when called with arguments', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().within([]); + }, /must be used after where/); + }) + + describe('of length 1', function(){ + it('throws if not a recognized shape', function(){ + assert.throws(function () { + mquery().where('loc').within({}); + }, /Invalid argument/) + assert.throws(function () { + mquery().where('loc').within(null); + }, /Invalid argument/) + }) + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('geoWithin', function(){ + before(function(){ + mquery.use$geoWithin = false; + }) + after(function(){ + mquery.use$geoWithin = true; + }) + describe('when called with arguments', function(){ + describe('of length 1', function(){ + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('box', function(){ + describe('with 1 argument', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box('sometihng'); + }, /Invalid argument/); + }) + }) + describe('with > 3 arguments', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box(1,2,3,4); + }, /Invalid argument/); + }) + }) + + describe('with 2 arguments', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().box([],[]); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('loc').box([1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + + describe('with 3 arguments', function(){ + it('works', function(){ + var m = mquery().box('loc', [1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + }) + + describe('polygon', function(){ + describe('when first argument is not a string', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().polygon({}); + }, /must be used after where/); + + assert.doesNotThrow(function () { + mquery().where('loc').polygon([1,2], [2,3], [3,6]); + }); + }) + + it('assigns arguments to within polygon condition', function(){ + var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + + describe('when first arg is a string', function(){ + it('assigns remaining arguments to within polygon condition', function(){ + var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + }) + + describe('circle', function(){ + describe('with one arg', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().circle('x'); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('loc').circle({center:[0,0], radius: 3 }); + }); + }) + it('works', function(){ + var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); + assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); + }) + }) + describe('with 3 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().where('loc').circle(1,2,3); + }, /Invalid argument/); + }) + }) + describe('requires radius and center', function(){ + assert.throws(function () { + mquery().circle('loc', { center: 1 }); + }, /center and radius are required/); + assert.throws(function () { + mquery().circle('loc', { radius: 1 }); + }, /center and radius are required/); + assert.doesNotThrow(function () { + mquery().circle('loc', { center: [1,2], radius: 1 }); + }); + }) + }) + + describe('geometry', function(){ + // within + intersects + var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; + + it('must be called after within or intersects', function(done){ + assert.throws(function () { + mquery().where('a').geometry(point); + }, /must come after/); + + assert.doesNotThrow(function () { + mquery().where('a').within().geometry(point); + }); + + assert.doesNotThrow(function () { + mquery().where('a').intersects().geometry(point); + }); + + done(); + }) + + describe('when called with one argument', function(){ + describe('after within()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').within().geometry(point); + assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + describe('after intersects()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').intersects().geometry(point); + assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + it('and arg does not quack like geoJSON', function(done){ + assert.throws(function () { + mquery().where('b').within().geometry({type:1, coordinates:2}); + }, /Invalid argument/); + done(); + }) + }) + + describe('when called with zero arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry(); + }, /Invalid argument/); + + done(); + }) + }) + + describe('when called with more than one arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); + }, /Invalid argument/); + done(); + }) + }) + }) + + describe('intersects', function(){ + it('must be used after where()', function(done){ + var m = mquery(); + assert.throws(function () { + m.intersects(); + }, /must be used after where/) + done(); + }) + + it('sets geo comparison to "$intersects"', function(done){ + var n = mquery().where('a').intersects(); + assert.equal('$geoIntersects', n._geoComparison); + done(); + }) + + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').intersects(), m); + }) + + it('calls geometry if argument quacks like geojson', function(done){ + var m = mquery(); + var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; + var ran = false; + + m.geometry = function (arg) { + ran = true; + assert.deepEqual(o, arg); + } + + m.where('a').intersects(o); + assert.ok(ran); + + done(); + }) + + it('throws if argument is not geometry-like', function(done){ + var m = mquery().where('a'); + + assert.throws(function () { + m.intersects(null); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(undefined); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(false); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects({}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects([]); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(function(){}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(NaN); + }, /Invalid argument/); + + done(); + }) + }) + + describe('near', function(){ + // near nearSphere + describe('with 0 args', function(){ + it('is compatible with geometry()', function(done){ + var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); + done(); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().near(1); + }, /must be used after where/) + }) + it('does not throw if used after where()', function(){ + assert.doesNotThrow(function () { + mquery().where('loc').near({center:[1,1]}); + }) + }) + }) + describe('with > 2 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().near(1,2,3); + }, /Invalid argument/) + }) + }) + + it('creates $geometry args for GeoJSON', function(){ + var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); + }) + + it('expects `center`', function(){ + assert.throws(function () { + mquery().near('loc', { maxDistance: 3 }); + }, /center is required/) + assert.doesNotThrow(function () { + mquery().near('loc', { center: [3,4] }); + }) + }) + + it('accepts spherical conditions', function(){ + var m = mquery().where('loc').near({ center: [1,2], spherical: true }); + assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); + }) + + it('is non-spherical by default', function(){ + var m = mquery().where('loc').near({ center: [1,2] }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); + }) + + it('supports maxDistance', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); + }) + + it('is chainable', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); + }) + + describe('supports passing GeoJSON, gh-13', function(){ + it('with center', function(){ + var m = mquery().where('loc').near({ + center: { type: 'Point', coordinates: [1,1] } + , maxDistance: 2 + }); + + var expect = { + loc: { + $near: { + $geometry: { + type: 'Point' + , coordinates : [1,1] + } + , $maxDistance : 2 + } + } + } + + assert.deepEqual(m._conditions, expect); + }) + }) + }) + + // fields + + describe('select', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.select()); + }) + }) + + it('accepts an object', function(){ + var o = { x: 1, y: 1 } + var m = mquery().select(o); + assert.deepEqual(m._fields, o); + }) + + it('accepts a string', function(){ + var o = 'x -y'; + var m = mquery().select(o); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + }) + + it('does not accept an array', function(done){ + assert.throws(function () { + var o = ['x', '-y']; + var m = mquery().select(o); + }, /Invalid select/); + done(); + }) + + it('merges previous arguments', function(){ + var o = { x: 1, y: 0, a: 1 } + var m = mquery().select(o); + m.select('z -u w').select({ x: 0 }) + assert.deepEqual(m._fields, { + x: 0 + , y: 0 + , z: 1 + , u: 0 + , w: 1 + , a: 1 + }); + }) + + it('rejects non-string, object, arrays', function(){ + assert.throws(function () { + mquery().select(function(){}); + }, /Invalid select\(\) argument/); + }) + + it('accepts aguments objects', function(){ + var m = mquery(); + function t () { + m.select(arguments); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + } + t('x', '-y'); + }) + + noDistinct('select'); + no('count', 'select'); + }) + + describe('selected', function() { + it('returns true when fields have been selected', function(done) { + var m = mquery().select({ name: 1 }); + assert.ok(m.selected()); + + var m = mquery().select('name'); + assert.ok(m.selected()); + + done(); + }); + + it('returns false when no fields have been selected', function(done) { + var m = mquery(); + assert.strictEqual(false, m.selected()); + done(); + }); + }); + + describe('selectedInclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.strictEqual(false, mquery().selectedInclusively()); + assert.equal(false, mquery().select({}).selectedInclusively()); + done(); + }); + it('when any fields have been excluded', function(done) { + assert.strictEqual(false, mquery().select('-name').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); + assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when fields have been included', function(done) { + assert.equal(true, mquery().select('name').selectedInclusively()); + assert.equal(true, mquery().select({ name:1 }).selectedInclusively()); + done(); + }); + }); + }); + + describe('selectedExclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.equal(false, mquery().selectedExclusively()); + assert.equal(false, mquery().select({}).selectedExclusively()); + done(); + }); + it('when fields have only been included', function(done) { + assert.equal(false, mquery().select('name').selectedExclusively()); + assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when any field has been excluded', function(done) { + assert.equal(true, mquery().select('-name').selectedExclusively()); + assert.equal(true, mquery().select({ name:0 }).selectedExclusively()); + assert.equal(true, mquery().select('-_id').selectedExclusively()); + assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); + assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); + done(); + }); + }); + }); + + describe('slice', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.slice()); + }) + it('is a noop', function(){ + var m = mquery().slice(); + assert.deepEqual(m._fields, undefined); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not called after where()', function(){ + assert.throws(function () { + mquery().slice(1); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('a').slice(1); + }); + }) + it('that is a number', function(){ + var query = mquery(); + query.where('collection').slice(5); + assert.deepEqual(query._fields, {collection: {$slice: 5}}); + }) + it('that is an array', function(){ + var query = mquery(); + query.where('collection').slice([5,10]); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + it('that is an object', function() { + var query = mquery(); + query.slice({ collection: [5, 10] }); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + }) + + describe('with 2 args', function(){ + describe('and first is a number', function(){ + it('throws if not called after where', function(){ + assert.throws(function () { + mquery().slice(2,3); + }, /must be used after where/); + }) + it('does not throw if used after where', function(){ + var query = mquery(); + query.where('collection').slice(2,3); + assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); + }) + }) + it('and first is not a number', function(){ + var query = mquery().slice('collection', [-5, 2]); + assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); + }) + }) + + describe('with 3 args', function(){ + it('works', function(){ + var query = mquery(); + query.slice('collection', 14, 10); + assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); + }) + }) + + noDistinct('slice'); + no('count', 'slice'); + }) + + // options + + describe('sort', function(){ + describe('with 0 args', function(){ + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.sort()); + }) + it('has no affect', function(){ + var m = mquery(); + assert.equal(m.options.sort, undefined); + }) + }) + + it('works', function(){ + var query = mquery(); + query.sort('a -c b'); + assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); + + query = mquery(); + query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); + assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); + + query = mquery(); + var e= undefined; + try { + query.sort(['a', 1]); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + + e= undefined; + try { + query.sort('a', 1, 'c', -1, 'b', 1); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + }) + + it('handles $meta sort options', function(){ + var query = mquery(); + query.sort({ score: { $meta : "textScore" } }); + assert.deepEqual(query.options.sort, { score : { $meta : "textScore" } }); + }) + + no('count', 'sort'); + }) + + function simpleOption (type, options) { + describe(type, function(){ + it('sets the ' + type + ' option', function(){ + var m = mquery()[type](2); + var optionName = options.name || type; + assert.equal(2, m.options[optionName]); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m[type](3), m); + }) + + if (!options.distinct) noDistinct(type); + if (!options.count) no('count', type); + }) + } + + var negated = { + limit: {distinct: false, count: true} + , skip: {distinct: false, count: true} + , maxScan: {distinct: false, count: false} + , batchSize: {distinct: false, count: false} + , maxTime: {distinct: true, count: true, name: 'maxTimeMS' } + , comment: {distinct: false, count: false} + }; + Object.keys(negated).forEach(function (key) { + simpleOption(key, negated[key]); + }) + + describe('snapshot', function(){ + it('works', function(){ + var query = mquery(); + query.snapshot(); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(true); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(false); + assert.equal(false, query.options.snapshot); + }) + noDistinct('snapshot'); + no('count', 'snapshot'); + }) + + describe('hint', function(){ + it('accepts an object', function(){ + var query2 = mquery(); + query2.hint({'a': 1, 'b': -1}); + assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); + }) + + it('rejects everything else', function(){ + assert.throws(function(){ + mquery().hint('c'); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(['c']); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(1); + }, /Invalid hint./); + }) + + describe('does not have side affects', function(){ + it('on invalid arg', function(){ + var m = mquery(); + try { + m.hint(1); + } catch (err) { + // ignore + } + assert.equal(undefined, m.options.hint); + }) + it('on missing arg', function(){ + var m = mquery().hint(); + assert.equal(undefined, m.options.hint); + }) + }) + + noDistinct('hint'); + }) + + describe('slaveOk', function(){ + it('works', function(){ + var query = mquery(); + query.slaveOk(); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(true); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(false); + assert.equal(false, query.options.slaveOk); + }) + }) + + describe('read', function(){ + it('sets associated readPreference option', function(){ + var m = mquery(); + m.read('p'); + assert.equal('primary', m.options.readPreference); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.read('sp')); + }) + }) + + describe('tailable', function(){ + it('works', function(){ + var query = mquery(); + query.tailable(); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(true); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(false); + assert.equal(false, query.options.tailable); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.tailable()); + }) + noDistinct('tailable'); + no('count', 'tailable'); + }) + + // query utilities + + describe('merge', function(){ + describe('with falsy arg', function(){ + it('returns itself', function(){ + var m = mquery(); + assert.equal(m, m.merge()); + assert.equal(m, m.merge(null)); + assert.equal(m, m.merge(0)); + }) + }) + describe('with an argument', function(){ + describe('that is not a query or plain object', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().merge([]); + }, /Invalid argument/); + assert.throws(function () { + mquery().merge('merge'); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().merge({}); + }, /Invalid argument/); + }) + }) + + describe('that is a query', function(){ + it('merges conditions, field selection, and options', function(){ + var m = mquery({ x: 'hi' }, { select: 'x y', another: true }) + var n = mquery().merge(m); + assert.deepEqual(n._conditions, m._conditions); + assert.deepEqual(n._fields, m._fields); + assert.deepEqual(n.options, m.options); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(m); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = mquery({ x: 'hi' }); + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + + describe('that is an object', function(){ + it('merges', function(){ + var m = { x: 'hi' }; + var n = mquery().merge(m); + assert.deepEqual(n._conditions, { x: 'hi' }); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(original); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = { x: 'hi' }; + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + }) + }) + + // queries + + describe('find', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.find() + }) + assert.doesNotThrow(function () { + m.find({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery().find({ x: 1 }).find().find({ y: 2 }); + assert.deepEqual(m._conditions, {x:1,y:2}); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.tailable(); + m.select('_id'); + var a = mquery().find(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).find({ name: 'mquery' }, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery' }); + mquery(col).find(m, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery' }).collection(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }) + }) + }) + + describe('findOne', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.findOne() + }) + assert.doesNotThrow(function () { + m.findOne({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('findOne', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().findOne(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery findone' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery findone' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).findOne({ name: 'mquery findone' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery(col).where({ name: 'mquery findone' }); + mquery(col).findOne(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery findone' }).collection(col).findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }) + }) + }) + + describe('count', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.count() + }) + assert.doesNotThrow(function () { + m.count({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.count({ x: 1 }).count().count({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('count', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().count(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery count' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery count' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).count({ name: 'mquery count' }, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery count' }); + mquery(col).count(m, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery count' }).collection(col).count(function (err, count) { + assert.ifError(err); + assert.ok(1 === count); + done(); + }); + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').count(); + }, /sort cannot be used with count/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('limit', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().limit(3).count(); + }) + done(); + }) + + it('skip', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().skip(3).count(); + }) + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).count(); + }, /batchSize cannot be used with count/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').count(); + }, /comment cannot be used with count/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).count(); + }, /maxScan cannot be used with count/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().count(); + }, /snapshot cannot be used with count/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().count(); + }, /tailable cannot be used with count/); + done(); + }) + }) + }) + + describe('distinct', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.distinct() + }) + assert.doesNotThrow(function () { + m.distinct('name') + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }) + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }, 'name') + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).distinct('name'); + var n = m.distinct({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.equal('name', n._distinct); + assert.equal('distinct', n.op); + }); + + it('overwrites field', function(){ + var m = mquery({ name: 'mquery' }).distinct('name'); + m.distinct('rename'); + assert.equal(m._distinct, 'rename'); + m.distinct({x:1}, 'renamed'); + assert.equal(m._distinct, 'renamed'); + }) + + it('merges other queries', function(){ + var m = mquery().distinct({ name: 'mquery' }, 'age') + m.read('nearest'); + var a = mquery().distinct(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + assert.deepEqual(a._distinct, m._distinct); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery distinct' }, done); + }) + + it('when distinct arg is passed with a callback', function(done){ + mquery(col).distinct('distinct', function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + describe('when criteria is passed with a callback', function(){ + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct({ name: 'mquery distinct' }, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when Query is passed with a callback', function(){ + var m = mquery({ name: 'mquery distinct' }); + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct(m, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when just a callback is passed', function(done){ + it('if distinct arg was declared', function(done){ + var m = mquery({ name: 'mquery distinct' }); + m.collection(col); + m.distinct('age'); + m.distinct(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }) + it('but not if no distinct arg was declared', function(){ + var m = mquery(); + m.collection(col); + assert.throws(function () { + m.distinct(function(){}); + }, /No value for `distinct`/); + }) + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').distinct(); + }, /sort cannot be used with distinct/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3).distinct(); + }, /limit cannot be used with distinct/); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3).distinct(); + }, /skip cannot be used with distinct/); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).distinct(); + }, /batchSize cannot be used with distinct/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').distinct(); + }, /comment cannot be used with distinct/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).distinct(); + }, /maxScan cannot be used with distinct/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().distinct(); + }, /snapshot cannot be used with distinct/); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 }).distinct(); + }, /hint cannot be used with distinct/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().distinct(); + }, /tailable cannot be used with distinct/); + done(); + }) + }) + }) + + describe('update', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }, { multi: true }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update() + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).update({ y: 2 }); + var n = m.where({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.deepEqual({ y: 2 }, n._update); + assert.equal('update', n.op); + }); + + it('merges update doc arg', function(){ + var a = [1,2]; + var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); + m.update({ z: 'stuff' }); + assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.ok(!m.options.overwrite); + m.update({}, { z: 'renamed' }, { overwrite: true }); + assert.ok(m.options.overwrite === true); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + a.push(3); + assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + }) + + it('merges other options', function(){ + var m = mquery(); + m.setOptions({ overwrite: true }); + m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }) + assert.deepEqual({ age: 77 }, m._conditions); + assert.deepEqual({ name: 'pagemill' }, m._update); + assert.deepEqual({ overwrite: true, multi: true }, m.options); + }) + + describe('executes', function(){ + var id; + before(function (done) { + col.insert({ name: 'mquery update', age: 1 }, { safe: true }, function (err, docs) { + var elem = docs[0]; + id = elem._id; + done(); + }); + }); + + after(function(done){ + col.remove({ _id: id }, done); + }) + + describe('when conds + doc + opts + callback passed', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }) + m.update({}, { name: 'Sparky' }, { safe: true }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Sparky'); + done(); + }) + }) + }) + }) + + describe('when conds + doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'fairgrounds'); + done(); + }) + }) + }) + }) + + describe('when doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'changed'); + done(); + }) + }) + }) + }) + + describe('when just callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ name: 'Frankenweenie' }); + m.update(function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Frankenweenie'); + done(); + }) + }) + }) + }) + + describe('without a callback', function(){ + it('when forced by exec()', function(done){ + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, multi: true }); + m.update({ name: 'forced' }); + + var update = m._collection.update; + m._collection.update = function (conds, doc, opts, cb) { + m._collection.update = update; + + assert.ok(!opts.safe); + assert.ok(true === opts.multi); + assert.equal('forced', doc.$set.name); + done(); + } + + m.exec() + }) + }) + + describe('except when update doc is empty and missing overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(0 === num); + setTimeout(function(){ + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + assert.equal('Frankenweenie', doc.name); + done(); + }) + }, 300); + }) + }) + }); + + describe('when update doc is set with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ all: 'yep', two: 2 }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal('yep', doc.all); + assert.equal(2, doc.two); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when update doc is empty with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(1, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when boolean (true) - exec()', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }); + m.update({ name: 'bool' }).update(true); + setTimeout(function () { + m.findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('bool', doc.name); + done(); + }) + }, 300) + }) + }) + }) + }) + + describe('remove', function(){ + describe('with 0 args', function(){ + var name = 'remove: no args test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + it('does not execute', function(done){ + var remove = col.remove; + col.remove = function () { + col.remove = remove; + done(new Error('remove executed!')); + } + + var m = mquery(col).where({ name: name }).remove() + setTimeout(function () { + col.remove = remove; + done(); + }, 10); + }) + + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.remove()); + }) + }) + + describe('with 1 argument', function(){ + var name = 'remove: 1 arg test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + describe('that is a', function(){ + it('plain object', function(){ + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove({ color: '#fff' }) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('query', function(){ + var q = mquery({ color: '#fff' }); + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove(q) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('function', function(done){ + mquery(col, { safe: true }).where({name: name}).remove(function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(null, doc); + done(); + }) + }); + }) + + it('boolean (true) - execute', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + mquery(col).remove(true); + setTimeout(function () { + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(0, docs.length); + done(); + }) + }, 300) + }) + }) + }) + }) + }) + + describe('with 2 arguments', function(){ + var name = 'remove: 2 arg test' + beforeEach(function(done){ + col.remove({}, { safe: true }, function (err) { + assert.ifError(err); + col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }) + }) + + describe('plain object + callback', function(){ + it('works', function(done){ + mquery(col).remove({ name: name }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + + describe('mquery + callback', function(){ + it('works', function(done){ + var m = mquery({ name: name }); + mquery(col).remove(m, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + }) + }) + + function validateFindAndModifyOptions (method) { + describe('validates its option', function(){ + it('sort', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().sort('x')[method](); + }) + done(); + }) + + it('select', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().select('x')[method](); + }) + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3)[method](); + }, new RegExp('limit cannot be used with ' + method)); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3)[method](); + }, new RegExp('skip cannot be used with ' + method)); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 })[method](); + }, new RegExp('batchSize cannot be used with ' + method)); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300)[method](); + }, new RegExp('maxScan cannot be used with ' + method)); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot()[method](); + }, new RegExp('snapshot cannot be used with ' + method)); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 })[method](); + }, new RegExp('hint cannot be used with ' + method)); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable()[method](); + }, new RegExp('tailable cannot be used with ' + method)); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery')[method](); + }, new RegExp('comment cannot be used with ' + method)); + done(); + }) + }) + } + + describe('findOneAndUpdate', function(){ + var name = 'findOneAndUpdate + fn' + + validateFindAndModifyOptions('findOneAndUpdate'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndUpdate(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); + assert.deepEqual(n._update, { $set: { name: '1 arg' }}); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }).update({ x: 1 }); + var n = mquery().findOneAndUpdate(m); + assert.deepEqual(n._update, { x: 1 }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + name = '1 arg'; + var n = m.update({ $set: { name: name }}); + n.findOneAndUpdate(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + update', function(){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('query + update', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndUpdate(n, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('update + callback', function(done){ + var m = mquery(col).where({ name: name }); + m.findOneAndUpdate({ $inc: { age: 10 }}, function (err, doc) { + assert.ifError(err); + assert.equal(10, doc.age); + done(); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + update + options', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); + assert.deepEqual({ name: name}, n._conditions); + assert.deepEqual({ works: true }, n._update); + assert.deepEqual({ new: false }, n.options); + }) + it('conditions + update + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: true }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + describe('with 4 args', function(){ + it('conditions + update + options + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + }) + + describe('findOneAndRemove', function(){ + var name = 'findOneAndRemove' + + validateFindAndModifyOptions('findOneAndRemove'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndRemove(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndRemove({ name: '1 arg' }); + assert.deepEqual(n._conditions, { name: '1 arg' }); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }); + var n = m.findOneAndRemove(m); + assert.deepEqual(n._conditions, { name: name }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + m.findOneAndRemove(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + options', function(){ + var m = mquery(col); + m.findOneAndRemove({ name: name }, { new: false }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ new: false }, m.options); + }) + it('query + options', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndRemove(n, { sort: { x: 1 }}); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ sort: { 'x': 1 }}, m.options); + }) + it('conditions + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + it('query + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var n = mquery({ name: name }) + var m = mquery(col); + m.findOneAndRemove(n, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + options + callback', function(done){ + name = 'findOneAndRemove + conds + options + cb'; + col.insert([{ name: name }, { name: 'a' }], { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + }) + + describe('exec', function(){ + beforeEach(function(done){ + col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); + }) + + afterEach(function(done){ + mquery(col).remove(done); + }) + + it('requires an op', function(){ + assert.throws(function () { + mquery().exec() + }, /Missing query type/); + }) + + describe('find', function() { + it('works', function(done){ + var m = mquery(col).find({ name: 'exec' }); + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + + it('works with readPreferences', function (done) { + var m = mquery(col).find({ name: 'exec' }); + try { + var rp = new require('mongodb').ReadPreference('primary'); + m.read(rp); + } catch (e) { + if (e.code === 'MODULE_NOT_FOUND') + e = null; + done(e); + return; + } + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }); + + it('findOne', function(done){ + var m = mquery(col).findOne({ age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal(2, doc.age); + done(); + }) + }) + + it('count', function(done){ + var m = mquery(col).count({ name: 'exec' }); + m.exec(function (err, count) { + assert.ifError(err); + assert.equal(2, count); + done(); + }) + }) + + it('distinct', function(done){ + var m = mquery({ name: 'exec' }); + m.collection(col); + m.distinct('age'); + m.exec(function (err, array) { + assert.ifError(err); + assert.ok(Array.isArray(array)); + assert.equal(2, array.length); + assert(~array.indexOf(1)); + assert(~array.indexOf(2)); + done(); + }); + }) + + describe('update', function(){ + var num; + + it('with a callback', function(done){ + var m = mquery(col); + m.where({ name: 'exec' }) + + m.count(function (err, _num) { + assert.ifError(err); + num = _num; + m.setOptions({ multi: true }) + m.update({ name: 'exec + update' }); + m.exec(function (err, res) { + assert.ifError(err); + assert.equal(num, res); + mquery(col).find({ name: 'exec + update' }, function (err, docs) { + assert.ifError(err); + assert.equal(num, docs.length); + done(); + }) + }) + }) + }) + + it('without a callback', function(done){ + var m = mquery(col) + m.where({ name: 'exec + update' }).setOptions({ multi: true }) + m.update({ name: 'exec' }); + + // unsafe write + m.exec(); + + setTimeout(function () { + mquery(col).find({ name: 'exec' }, function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }, 200) + }) + it('preserves key ordering', function(done) { + var m = mquery(col); + + var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); + var doc = m2._updateForExec().$set; + var count = 0; + for (var i in doc) { + if (count == 0) { + assert.equal('1', i); + } else if (count == 1) { + assert.equal('2', i); + } else if (count ==2) { + assert.equal('3', i); + } + count++; + } + done(); + }); + }) + + describe('remove', function(){ + it('with a callback', function(done){ + var m = mquery(col).where({ age: 2 }).remove(); + m.exec(function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }) + }) + + it('without a callback', function(done){ + var m = mquery(col).where({ age: 1 }).remove(); + m.exec(); + + setTimeout(function () { + mquery(col).where('name', 'exec').count(function(err, num) { + assert.equal(1, num); + done(); + }) + }, 200) + }) + }) + + describe('findOneAndUpdate', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('findOneAndUpdate', doc.name); + done(); + }); + }) + }) + + describe('findOneAndRemove', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndRemove({ name: 'exec', age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('exec', doc.name); + assert.equal(2, doc.age); + mquery(col).count({ name: 'exec' }, function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }); + }); + }) + }) + }) + + describe('setTraceFunction', function() { + beforeEach(function(done){ + col.insert([{ name: 'trace', age: 93 }], done); + }) + + it('calls trace function when executing query', function(done) { + var m = mquery(col); + + var resultTraceCalled; + + m.setTraceFunction(function (method, queryInfo) { + try { + assert.equal('findOne', method); + assert.equal('trace', queryInfo.conditions.name); + } catch (e) { + done(e); + } + + return function(err, result, millis) { + try { + assert.equal(93, result.age); + } catch (e) { + done(e); + } + resultTraceCalled = true; + }; + }); + + m.findOne({name: 'trace'}, function (err, doc) { + assert.ifError(err); + assert.equal(resultTraceCalled, true); + assert.equal(93, doc.age); + done(); + }); + }); + + it('inherits trace function when calling toConstructor', function(done) { + function traceFunction () { return function() {} }; + + var tracedQuery = mquery().setTraceFunction(traceFunction).toConstructor(); + + var query = tracedQuery(); + assert.equal(traceFunction, query._traceFunction); + + done(); + }); + }); + + describe('thunk', function() { + it('returns a function', function(done) { + assert.equal('function', typeof mquery().thunk()); + done(); + }); + + it('passes the fn arg to `exec`', function(done) { + function cb() {} + var m = mquery(); + + m.exec = function testing(fn) { + assert.equal(this, m); + assert.equal(cb, fn); + done(); + } + + m.thunk()(cb); + }); + }); + + describe('then', function() { + before(function(done){ + col.insert([{ name: 'then', age: 1 }, { name: 'then', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'then' }).exec(done); + }) + + it('returns a promise A+ compat object', function(done) { + var m = mquery(col).find(); + assert.equal('function', typeof m.then); + done(); + }); + + it('creates a promise that is resolved on success', function(done) { + var promise = mquery(col).count({ name: 'then' }).then(); + promise.then(function(count){ + assert.equal(2, count); + done(); + }, done); + }); + + it('supports other Promise libs', function(done) { + var bluebird = mquery.Promise; + + // hack for testing + mquery.Promise = function P() { + mquery.Promise = bluebird; + this.then = function(x, y) { + return x + y; + } + } + + var val = mquery(col).count({ name: 'exec' }).then(1, 2); + assert.equal(val, 3); + done(); + }); + }); + + describe('stream', function() { + before(function(done){ + col.insert([{ name: 'stream', age: 1 }, { name: 'stream', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'stream' }).exec(done); + }) + + describe('throws', function() { + describe('if used with non-find operations', function() { + var ops = ['update', 'findOneAndUpdate', 'remove', 'count', 'distinct']; + + ops.forEach(function(op) { + assert.throws(function(){ + mquery(col)[op]().stream(); + }); + }); + }); + }); + + it('returns a stream', function(done) { + var stream = mquery(col).find({ name: 'stream' }).stream(); + var count = 0; + var err; + + stream.on('data', function(doc){ + assert.equal('stream', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(2, count); + done(); + }); + }); + + it('supports find options', function(done) { + var stream = mquery(col) + .find({ name: 'stream' }) + .limit(1) + .select('-_id') + .stream({ transform: xform }); + + function xform(doc) { + doc.name = doc.name + '-xformed'; + return doc; + } + + var count = 0; + var err; + + stream.on('data', function(doc){ + assert(!doc._id); + assert.equal('stream-xformed', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(1, count); + done(); + }); + }); + + }); + + function noDistinct (type) { + it('cannot be used with distinct()', function(done){ + assert.throws(function () { + mquery().distinct('name')[type](4); + }, new RegExp(type + ' cannot be used with distinct')); + done(); + }) + } + + function no (method, type) { + it('cannot be used with ' + method + '()', function(done){ + assert.throws(function () { + mquery()[method]()[type](4); + }, new RegExp(type + ' cannot be used with ' + method)); + done(); + }) + } + + // query internal + + describe('_updateForExec', function(){ + it('returns a clone of the update object with same key order #19', function(done){ + var update = {}; + update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; + + var q = mquery().update({ x: 1 }, update); + + // capture original key order + var order = []; + for (var key in q._update.$push.n) { + order.push(key); + } + + // compare output + var doc = q._updateForExec(); + var i = 0; + for (var key in doc.$push.n) { + assert.equal(key, order[i]); + i++; + } + + done(); + }) + }) +}) diff --git a/node_modules/mongoose/node_modules/mquery/test/utils.test.js b/node_modules/mongoose/node_modules/mquery/test/utils.test.js new file mode 100644 index 0000000..fa5972a --- /dev/null +++ b/node_modules/mongoose/node_modules/mquery/test/utils.test.js @@ -0,0 +1,143 @@ + +var utils = require('../lib/utils'); +var assert = require('assert'); + +var mongo; +try { + mongo = new require('mongodb'); +} catch (e) {} + +describe('lib/utils', function() { + describe('clone', function() { + it('clones constructors named ObjectId', function(done) { + function ObjectId (id) { + this.id = id; + } + + var o1 = new ObjectId('1234'); + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectId); + + done(); + }); + + it('clones constructors named ObjectID', function(done) { + function ObjectID (id) { + this.id = id; + } + + var o1 = new ObjectID('1234'); + var o2 = utils.clone(o1); + + assert.ok(o2 instanceof ObjectID); + done(); + }); + + it('does not clone constructors named ObjectIdd', function(done) { + function ObjectIdd (id) { + this.id = id; + } + + var o1 = new ObjectIdd('1234'); + var o2 = utils.clone(o1); + assert.ok(!(o2 instanceof ObjectIdd)); + + done(); + }); + + it('optionally clones ObjectId constructors using its clone method', function(done) { + function ObjectID (id) { + this.id = id; + this.cloned = false; + } + + ObjectID.prototype.clone = function () { + var ret = new ObjectID(this.id); + ret.cloned = true; + return ret; + } + + var id = 1234; + var o1 = new ObjectID(id); + assert.equal(id, o1.id); + assert.equal(false, o1.cloned); + + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectID); + assert.equal(id, o2.id); + assert.ok(o2.cloned); + done(); + }); + + it('clones mongodb.ReadPreferences', function (done) { + if (!mongo) return done(); + + var tags = [ + {dc: 'tag1'} + ]; + var prefs = [ + new mongo.ReadPreference("primary"), + new mongo.ReadPreference(mongo.ReadPreference.PRIMARY_PREFERRED), + new mongo.ReadPreference("primary", tags), + mongo.ReadPreference("primary", tags) + ]; + + var prefsCloned = utils.clone(prefs); + + for (var i = 0; i < prefsCloned.length; i++) { + assert.notEqual(prefs[i], prefsCloned[i]); + assert.ok(prefsCloned[i] instanceof mongo.ReadPreference); + assert.ok(prefsCloned[i].isValid()); + if (prefs[i].tags) { + assert.ok(prefsCloned[i].tags); + assert.notEqual(prefs[i].tags, prefsCloned[i].tags); + assert.notEqual(prefs[i].tags[0], prefsCloned[i].tags[0]); + } else { + assert.equal(prefsCloned[i].tags, null); + } + } + + done(); + }); + + it('clones mongodb.Binary', function(done){ + if (!mongo) return done(); + + var buf = new Buffer('hi'); + var binary= new mongo.Binary(buf, 2); + var clone = utils.clone(binary); + assert.equal(binary.sub_type, clone.sub_type); + assert.equal(String(binary.buffer), String(buf)); + assert.ok(binary !== clone); + done(); + }) + + it('handles objects with no constructor', function(done) { + var name ='335'; + + var o = Object.create(null); + o.name = name; + + var clone; + assert.doesNotThrow(function() { + clone = utils.clone(o); + }); + + assert.equal(name, clone.name); + assert.ok(o != clone); + done(); + }); + + it('handles buffers', function(done){ + var buff = new Buffer(10); + buff.fill(1); + var clone = utils.clone(buff); + + for (var i = 0; i < buff.length; i++) { + assert.equal(buff[i], clone[i]); + } + + done(); + }); + }); +}); diff --git a/node_modules/mongoose/node_modules/ms/.npmignore b/node_modules/mongoose/node_modules/ms/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/mongoose/node_modules/ms/Makefile b/node_modules/mongoose/node_modules/ms/Makefile new file mode 100644 index 0000000..dded504 --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/Makefile @@ -0,0 +1,8 @@ + +test: + ./node_modules/.bin/mocha test/test.js + +test-browser: + ./node_modules/.bin/serve test/ + +.PHONY: test diff --git a/node_modules/mongoose/node_modules/ms/README.md b/node_modules/mongoose/node_modules/ms/README.md new file mode 100644 index 0000000..c93d43f --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/README.md @@ -0,0 +1,65 @@ + +# ms.js + +Ever find yourself doing math in your head or writing `1000 * 60 * 60 …`? +Don't want to add obstrusive `Number` prototype extensions to your reusable +/ distributable modules and projects? + +`ms` is a tiny utility that you can leverage when your application needs to +accept a number of miliseconds as a parameter. + +If a number is supplied to `ms`, it returns it immediately (e.g: +If a string that contains the number is supplied, it returns it immediately as +a number (e.g: it returns `100` for `'100'`). + +However, if you pass a string with a number and a valid unit, hte number of +equivalent ms is returned. + +```js +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5ms') // 5000 +ms('100') // '100' +ms(100) // 100 +``` + +## How to use + +### Node + +```js +require('ms') +``` + +### Browser + +```html + +``` + +## Credits + +(The MIT License) + +Copyright (c) 2011 Guillermo Rauch <guillermo@learnboost.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. diff --git a/node_modules/mongoose/node_modules/ms/ms.js b/node_modules/mongoose/node_modules/ms/ms.js new file mode 100644 index 0000000..b4621bc --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/ms.js @@ -0,0 +1,35 @@ +/** + +# ms.js + +No more painful `setTimeout(fn, 60 * 4 * 3 * 2 * 1 * Infinity * NaN * '☃')`. + + ms('2d') // 172800000 + ms('1.5h') // 5400000 + ms('1h') // 3600000 + ms('1m') // 60000 + ms('5s') // 5000 + ms('500ms') // 500 + ms('100') // '100' + ms(100) // 100 + +**/ + +(function (g) { + var r = /(\d*.?\d+)([mshd]+)/ + , _ = {} + + _.ms = 1; + _.s = 1000; + _.m = _.s * 60; + _.h = _.m * 60; + _.d = _.h * 24; + + function ms (s) { + if (s == Number(s)) return Number(s); + r.exec(s.toLowerCase()); + return RegExp.$1 * _[RegExp.$2]; + } + + g.top ? g.ms = ms : module.exports = ms; +})(this); diff --git a/node_modules/mongoose/node_modules/ms/package.json b/node_modules/mongoose/node_modules/ms/package.json new file mode 100644 index 0000000..f22b22a --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/package.json @@ -0,0 +1,39 @@ +{ + "name": "ms", + "version": "0.1.0", + "description": "Tiny ms conversion utility", + "main": "./ms", + "devDependencies": { + "mocha": "*", + "expect.js": "*", + "serve": "*" + }, + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "_id": "ms@0.1.0", + "dependencies": {}, + "engines": { + "node": "*" + }, + "_engineSupported": true, + "_npmVersion": "1.0.106", + "_nodeVersion": "v0.4.12", + "_defaultsLoaded": true, + "dist": { + "shasum": "f21fac490daf1d7667fd180fe9077389cc9442b2", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.1.0.tgz" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "directories": {}, + "_shasum": "f21fac490daf1d7667fd180fe9077389cc9442b2", + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.1.0.tgz", + "_from": "ms@0.1.0", + "readme": "ERROR: No README data found!" +} diff --git a/node_modules/mongoose/node_modules/ms/test/index.html b/node_modules/mongoose/node_modules/ms/test/index.html new file mode 100644 index 0000000..79edc40 --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/test/index.html @@ -0,0 +1,19 @@ + + + + ms.js tests + + + + + + + + + + + + +
+ + diff --git a/node_modules/mongoose/node_modules/ms/test/support/jquery.js b/node_modules/mongoose/node_modules/ms/test/support/jquery.js new file mode 100644 index 0000000..8ccd0ea --- /dev/null +++ b/node_modules/mongoose/node_modules/ms/test/support/jquery.js @@ -0,0 +1,9266 @@ +/*! + * jQuery JavaScript Library v1.7.1 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Mon Nov 21 21:11:03 2011 -0500 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document, + navigator = window.navigator, + location = window.location; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.7.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).off( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery.Callbacks( "once memory" ); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +return jQuery; + +})(); + + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } + } + } + }, + // Fire callbacks + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return self; +}; + + + + +var // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve: doneList, + reject: failList, + notify: progressList + }, + promise = { + done: doneList.add, + fail: failList.add, + progress: progressList.add, + + state: function() { + return state; + }, + + // Deprecated + isResolved: doneList.fired, + isRejected: failList.fired, + + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + return this; + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "notify" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise({}), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( function() { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function() { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } +}); + + + + +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + marginDiv, + fragment, + tds, + events, + eventName, + i, + isSupported, + div = document.createElement( "div" ), + documentElement = document.documentElement; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = "
a"; + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( window.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.style.width = "2px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + fragment.removeChild( div ); + + // Null elements to avoid leaks in IE + fragment = select = opt = marginDiv = div = input = null; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, outer, inner, table, td, offsetSupport, + conMarginTop, ptlm, vb, style, html, + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + conMarginTop = 1; + ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; + vb = "visibility:hidden;border:0;"; + style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; + html = "
" + + "" + + "
"; + + container = document.createElement("div"); + container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
t
"; + tds = div.getElementsByTagName( "td" ); + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Figure out if the W3C box model works as expected + div.innerHTML = ""; + div.style.width = div.style.paddingLeft = "1px"; + jQuery.boxModel = support.boxModel = div.offsetWidth === 2; + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.style.cssText = ptlm + vb; + div.innerHTML = html; + + outer = div.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder: ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + body.removeChild( container ); + div = container = null; + + jQuery.extend( support, offsetSupport ); + }); + + return support; +})(); + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ internalKey ] : internalKey; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ internalKey ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + } else { + elem[ internalKey ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, attr, name, + data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { + attr = this[0].attributes; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + jQuery._data( this[0], "parsedAttrs", true ); + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var self = jQuery( this ), + args = [ parts[0], value ]; + + self.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && + ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function() { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, l, + i = 0; + + if ( value && elem.nodeType === 1 ) { + attrNames = value.toLowerCase().split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + + // See #9699 for explanation of this approach (setting first, then removal) + jQuery.attr( elem, name, "" ); + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) +jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.nodeValue = value + "" ); + } + }; + + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); + + + + +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /\bhover(\.\S+)?\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function( elem, m ) { + var attrs = elem.attributes || {}; + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || (attrs.id || {}).value === m[2]) && + (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) + ); + }, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + quick: quickParse( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, origType, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + old = null; + for ( ; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + handlerQueue = [], + i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Determine handlers that should run if there are delegated events + // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery(this); + jqcur.context = this.ownerDocument || this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = ( + handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) + ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + ret; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + }); + form._submit_attached = true; + } + }); + // return undefined since we don't need an event listener + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + elem._change_attached = true; + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on.call( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace('.', ''), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set, seed ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); + } + } + } + return ret; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +Sizzle.selectors.attrMap = {}; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push({ selector: selectors[ i ], elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} + + + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
", "
" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + col: [ 2, "", "
" ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and